Deep dive · Distributed systems · Go · v1.0.8

sluice.
A velocity data platform for Go

Traffic arrives as fast as your users generate it; your datastore is built for a slower, steadier shape. sluice is a Redis-backed state plane between the two. It absorbs writes, serves reads, loads working sets and answers live queries at traffic speed. Your system of record only ever sees a few efficient batches.

One library and one state plane work with any datastore. First-class adapters exist for AWS DocumentDB / MongoDB, AWS DynamoDB and PostgreSQL.

10K–100K TPS ingest ~1,000× I/O reduction sub-µs L1 · sub-ms L2 reads ReadBulk pre-warming DocumentDB · DynamoDB · PostgreSQL no silent loss Redis & Valkey cluster-safe

Section 01

Introduction

sluice is an open-source Go library that sits between high-velocity traffic (SQS queues, Kafka topics, webhook floods, synchronous HTTP and gRPC APIs) and a system of record. It ships first-class adapters for AWS DocumentDB / MongoDB, AWS DynamoDB and PostgreSQL, and two small interfaces let you bring your own store. It plays two roles at once, and the tension between them is what makes the design interesting.

On the write side it is a velocity shield. Every incoming event is absorbed into a Redis-backed state journal in sub-millisecond time and acknowledged, while background flushers coalesce thousands of events into a handful of bulk writes. The datastore never sees the storm; it sees a calm, ordered trickle.

On the read side it is a hot-state journal. The same Redis structure that absorbed the writes becomes the authoritative read surface for the keys that are active right now: a logged-in user, an open session, an HTTP handler reading back what it just wrote. An optional in-process L1 sits in front of it for sub-microsecond reads, and cold keys fall through to the datastore transparently.

The one-sentence thesis. Treat Redis not as a cache in front of your database, but as a durable, deduplicating write journal that also happens to be the fastest possible read path for whatever is currently hot, and that never expires anything it has not yet persisted.

The library was born in ad-tech, where millions of customers receive nudges, bids and inventory updates at rates no single primary can absorb. But the shape of the problem (wide, incoherent, spiky write traffic against a store optimised for coherent bulk work) appears everywhere: loyalty platforms, payment ledgers, IoT telemetry, session-state services. sluice generalises the pattern behind a small, contract-driven API.

The scale envelope it is built for

Metric Value
Sustained ingest10K events/sec
Peak spike100K events/sec
Unique correlation keys at peak~80–90K/sec (wide-breadth traffic)
Bulk writes/sec reaching the store~100–130
I/O reduction vs individual writes~1,000×
Max datastore lag250 ms (configurable FlushWindow)
L1 Read() (same pod)sub-microsecond, in-process LRU
L2 Read()sub-millisecond, one pipelined round-trip
Cross-pod L1 convergencemilliseconds, via a Redis Streams broadcast
Working-set loadone set-based query per lookup key (ReadBulk)
Crash recoveryat-least-once; unflushed state never expires

The rest of this article walks the design in the order you would need it to rebuild it yourself: the problem (§2), the write path (§3), the read path and its tiers (§4), working-set pre-warming (§5), the durability model (§6), datastores and deployment topologies (§7), observability (§8), the public API (§9), configuration (§10) and upgrade notes (§11).

1.1 · What's new in 1.0.8

1.0.8 is the largest release since 1.0.0. It turns sluice from a write buffer for document stores into a general velocity platform, and it closes every silent-loss path found in a review of the write, flush and commit machinery.

Any datastore

New DynamoDB and PostgreSQL sink/source adapters alongside DocumentDB. See §7.1.

L1 local journal

A sharded in-process LRU with cross-pod convergence over Redis Streams, plus ReadFresh as a strong-consistency escape hatch. See §4.4.

Set-based pre-warming

ReadBulk collapses N+1 lookups into one query and hydrates the result in pipelines. See §5.

No silent loss

Unflushed state never expires, commits are conditional on a per-key sequence, degraded mode preserves order, and batched writes ack correctly. See §6.

Composable topologies

Build() needs only a namespace and Redis, so one binary can run as a full pod, reader-only gateway, pre-warmer or ingester. See §7.3.

Observability

A Prometheus recorder, a Grafana dashboard and reference alert rules, including a data-loss alarm. See §8.

The release has breaking changes; they are listed with migration steps in §11.

Section 02

The core problem it solves

Event-driven platforms do not have a data-volume problem; they have a data-velocity problem. They produce wide-breadth, incoherent, spiky traffic: one event, one customer, one field changed, arriving unbatched and uncoordinated from dozens of consumer workers. A nudge-inventory stream at 100K TPS is not 100K updates to a few records. It is 100K updates spread across 80–90K different records, with a long tail of keys that receive three or four events within the same second.

Forwarding that traffic naively to a datastore produces four compounding failures.

① Single-primary bottleneck

DocumentDB, MongoDB and PostgreSQL route all writes through one primary. Every individual event is a separate round-trip against a node that cannot scale horizontally for write throughput.

② Per-write cost multiplication

Each secondary index multiplies the I/O of every write. On DynamoDB the same burst becomes WCU spend, and every GSI you add for lookups multiplies it again.

③ Connection-pool saturation

DocumentDB caps connections per instance class, and PostgreSQL pays a backend process and a transaction per write. A spike that wakes 200 workers exhausts the pool, and latency collapses for everyone, including unrelated readers.

④ Round-trip explosion

100,000 events touching 80,000 unique customers become 100,000 round-trips, when the same work is ~100 bulk writes of ~1,000 records each. Reads suffer the same way: assembling a user's working set is N+1 lookups.

Figure 1 · The naive path: every event is a round-trip

event user_001 event user_002 event user_001 event user_003 event user_001 event user_002 datastore primary pool saturated ⚠ 100,000 individual round-trips / sec duplicate keys re-written 3× each, no coalescing anywhere

Six events, six round-trips, three of them redundant. At 100K TPS this is 100K round-trips against one node.

Why the obvious fixes fail

“Just batch inside the consumer.” Consumers are stateless and horizontally scaled. Two workers holding events for the same key cannot see each other, so cross-consumer coalescing is impossible without a shared store, which is exactly the thing we are trying to protect. Worse, in-memory batching loses everything in the buffer the moment a pod dies.

“Put a cache in front.” A cache has the wrong semantics. Caches are read-optimised; their TTL is a staleness budget; a miss means “go ask the database”; and eviction under pressure silently destroys data. None of that is what a write-absorbing layer needs.

Traditional cache sluice Redis journal
Optimised for Reads; avoids re-computation Writes; absorbs velocity, then serves reads off the absorbed state
TTL means Staleness budget for reads Residency after the store confirms a write. Unflushed state has no TTL at all
On miss Go to the database Read the Source, then hydrate the journal, but only if it is still a miss
Under pressure Eviction silently loses data Runs with noeviction: a full Redis refuses writes loudly instead of dropping state
The insight. Decouple the ingest rate from the persistence rate using a store that is fast enough to acknowledge every event individually (Redis) and structured enough to replay its contents in bulk later (a journal, not a cache).

Figure 2 · The sluice path: absorb, coalesce, drain

SQS / Kafka / APIs
100K events/sec
Redis state journal
HSET + PERSIST + ZADD · 1 atomic RT · sub-ms ACK
flush engine
16 bands · 4 triggers
datastore
~100–130 bulk writes/sec

100,000 writes/sec in, ~100–130 bulk writes/sec out: a ~1,000× reduction in datastore I/O. Duplicate keys collapse to one dirty entry; the store only ever sees final state.

Section 03

The write path

The write path has three load-bearing ideas: an atomic journal write, band partitioning that makes the whole thing cluster-safe and parallel, and a multi-trigger flush engine whose commits are conditional on a per-key sequence. Everything else (dedup, idempotency, dead-letters, the hot regime) hangs off those three.

3.1 · The atomic journal write

Every Write() executes a single pre-loaded Lua script that performs four Redis operations in one network round-trip: store the payload, bump its sequence, strip any TTL, and mark the key dirty. Because it is one script, there is no window in which the payload exists but the key is unmarked, or vice versa.

Figure 3 · One script, four operations, one round-trip

caller
Write(user, payload)

EVALSHA write · single round-trip

① HSET sl:ns:payload:{band}:user → p=payload, ts=now
② HINCRBY payload v 1 → per-key sequence
③ PERSIST payload → unflushed state never expires
④ ZADD sl:ns:dirty:{band} → score=now, member=user
return nil
< 1 ms · safe to ack

The ZADD score is the event timestamp in milliseconds, so the flush engine always drains oldest-first, giving a natural staleness bound equal to FlushWindow.

The payload hash carries four fields: p (opaque bytes; sluice never interprets them), ts (the score), v (the sequence, used by the conditional commit in §3.5) and, optionally, h (an xxHash64 content fingerprint when deduplication is on).

Why PERSIST, and what changed in 1.0.8. Up to 1.0.7, every write armed a KeyTTL (30 s) on the payload as a “crash-recovery net”, and the drain quietly skipped dirty keys whose payload had expired. A sink outage longer than 30 s therefore dropped acknowledged writes with no metric and no log. Now unflushed payloads are persistent, and a TTL is applied only after the sink confirms the write. Omitting EXPIRE alone would not be enough: HSET keeps whatever TTL a previously flushed version of the key had, so the script has to PERSIST explicitly.

Write returning nil means exactly one thing: the entry is in Redis and safe to acknowledge upstream. That holds in batched mode too (§3.6). On an error, don't ack.

3.2 · Coalescing: why wide traffic collapses

ZADD on an existing member only updates its score; it does not create a second entry. And HSET overwrites the payload in place. Together these two properties mean that N events for the same correlation key within one flush window collapse into one dirty-set entry holding the latest payload. The datastore only ever sees final state per window; intermediate churn never reaches it.

Figure 4 · Six events → three dirty keys → one bulk write

events arriving · 100K/s

user_001 · ev 1
user_002 · ev 1
user_001 · ev 2
user_003 · ev 1
user_001 · ev 3
user_002 · ev 2

dirty set after 250 ms

user_001 · v=3 · latest ts
user_002 · v=2 · latest ts
user_003 · v=1 · ts

3 entries, not 6

datastore

1 bulk write
BulkWrite · BatchWriteItem · multi-row INSERT

partial success reported per key

Coalescing is free: it falls out of ZSET/HSET semantics. No locks, no coordination, no consumer-side state.

3.3 · Bands, hash tags, and cluster safety

The dirty queue is not one sorted set but sixteen (configurable), called bands. A correlation key's band is FNV-32a(key) % bandCount, and each band is drained by its own goroutine. This gives parallelism without coordination: bands never share state.

Bands also solve the Redis Cluster problem. Every per-key and per-band key embeds the band as a {band} hash tag, so the payload hash, dirty set, hot marker, index keys and idempotency guard for a given key all land on the same cluster slot. That is what makes the Lua scripts, the HMGET pipelines and the SINTER queries legal under cluster mode, and on Valkey clusters, which enforce the same rule.

Figure 5 · The hash-tag contract

band 0{0} slot
band 1{1} slot
band 2{2} slot
band 3{3} slot
…
1 goroutineper band
sl:ns:payload:{7}:user_42 ← payload hash (p · ts · v · h)
sl:ns:dirty:{7} ← dirty ZSET
sl:ns:hot:{7}:user_42 ← hot marker
sl:ns:idx:{7}:channel:push ← equality index
sl:ns:ridx:{7}:priority ← range index
sl:ns:idxv:{7}:user_42 ← the key's current index values
sl:ns:idxexp:{7} ← index expiry queue
sl:ns:idem:{7}:msg_88 ← idempotency guard
sl:ns:dlq:{7} ← dead-letter ZSET
all share {7} → one slot → Lua, pipelines & SINTER are cluster-legal
sl:ns:bcast ← L1 broadcast stream: one per namespace, not per band (§4.4)

A namespace containing “{” or “}” is rejected at Build(); it would hijack cluster hash-tag parsing.

3.4 · The flush engine: four triggers

One goroutine per band sleeps until any of four independent triggers fires. The set of triggers is the engine's entire policy: each defends against a different failure mode, and together they bound latency, memory and backlog at once. The engine starts only when both a sink and a WriteContract are configured.

Figure 6 · Trigger → drain → commit cycle

⏰ TimeFlushWindow elapsed · caps store staleness
📊 Volumedepth ≥ MaxBatchSize · caps batch size & Redis memory
⏳ Backlogoldest dirty entry waited ~KeyTTL · caps flush latency
🔥 HotWrite() on a hot key · keeps store current
ZRANGEBYSCOREoldest N dirty keys
pipeline HMGETp · ts · v, 1 RTT
WriteContractcaller domain logic
sink.BulkWriteunordered, per-key errors
CommitFlushedif v unchanged · then TTL

The backlog check runs every KeyTTL/2. Before 1.0.8 this was the “pre-eviction” trigger, racing a TTL on unflushed data; now nothing unflushed has a TTL, so it only bounds how long a backlogged band can wait.

3.5 · Conditional commit and crash safety

The dirty set is the source of truth for “what still needs persisting”. Keys are removed from it only after the datastore confirms the write. If the process crashes between the bulk write and the commit, the next cycle re-flushes those keys, and because every sink operation is an upsert, the replay is harmless. That ordering rule is what makes the pipeline at-least-once with idempotent effect.

1.0.8 adds a second rule. Up to 1.0.7 the commit removed flushed keys from the dirty set by name, so a newer write to the same key that landed while the batch's bulk write was in flight lost its dirty entry and never reached the store. Now the drain reports each key's sequence (FlushRecord.Seq), and the engine commits through CommitFlushed: one atomic script per key that removes the dirty entry and applies the post-flush TTL only if v is unchanged. Dead-lettering is conditional the same way (DeadLetterIfUnchanged), so a failure on a superseded payload never dead-letters its replacement.

Figure 7 · A write that races an in-flight flush

caller flush engine Redis datastore drain user · reads v=7 BulkWrite(user=v7, …) Write(user) mid-flush → v=8, ZADD confirmed CommitFlushed(user, v=7) v is 8, not 7 → dirty entry kept, no TTL applied next batch flushes v=8; nothing is lost crash after confirm, before commit key is still dirty → re-flushed → upsert replay is safe

Entries written before 1.0.8 have no sequence and commit as before.

The engine never infers success. Each bulk write result is handled per key:

Sink result Engine action
top-level errorCommit nothing; the whole batch stays dirty and is retried (network, timeout, write-concern failure)
per-key error, no keyCommit nothing; sink.ErrUnattributedSinkError goes to OnFlush and the whole batch is retried
per-key, transientThat key stays dirty and is retried
per-key, permanentThat key is dead-lettered as permanent_sink_error
no error for a keyThe key is committed (conditionally, as above)

3.6 · Write-path resilience: dedup, idempotency, batching, dead-letters, degraded mode

Content deduplication. High-velocity streams re-send unchanged payloads constantly: heartbeats, periodic full-state refreshes, at-least-once redeliveries. With WithContentDedup(true), each payload is fingerprinted with xxHash64 and compared against the stored h field inside the same Lua script. On a match the write skips the dirty set, index maintenance and the flush entirely; the datastore never sees a write it already has.

Figure 8 · Dedup decision inside the atomic script

Write(user, payload)
h = xxhash64(payload)
h == stored h ?
yes
no dirty entry · if already flushed, extend TTL only · return 0
no
HSET p,ts,h · HINCRBY v · PERSIST · ZADD · return 1

A duplicate never adds a TTL to an unflushed payload, and only ever extends a flushed one, so a hot key's longer TTL is never shortened. Off by default: it costs one extra hash field per key.

Idempotent writes. Upstream queues redeliver. WriteIdempotent(ctx, user, payload, msgID) guards the entrance with a SETNX EX on sl:ns:idem:{band}:msgID; a replay returns ErrDuplicateIdempotencyKey so the consumer can ack and move on without polluting the journal. The guard's TTL (IdempotencyTTL, default 4h) should match your upstream's redelivery window, not your retention needs.

Batched writes that ack honestly. WithBatchedWrites(size, window) lets concurrent writers share one Redis pipeline: ⌈N / size⌉ round-trips instead of N. Up to 1.0.7, Write() returned nil as soon as the entry was buffered, and a failed pipeline was only logged, after every caller in it had already acked upstream. Now each Write waits for its own entry and returns that entry's real error, so a failed batched write falls back to degraded mode or reaches the caller. The batcher also runs until DrainAndClose rather than until the Build context is cancelled.

Dead-letter queue. When a flush meets a permanent failure, retrying is futile and would wedge the band. Those keys move to a per-band dead-letter ZSET with their payload kept for seven days and the failure reason recorded. Each bundled sink isolates a permanent failure to the offending rows (§7.2), so one poison record never stalls its band; the rest of the batch commits.

Dead-letter reason Cause
contract_violationWriteContract returned an error
permanent_sink_errorThe sink classified the key's error as permanent
payload_missing_before_flushThe key was dirty but its payload was gone. Also logged at error level, reported as ErrPayloadMissing and counted by RecordUnflushedExpiry: this is data loss and should page

Figure 9 · DLQ recovery strategies

DLQIgnore

Log each record, remove it. For expected, safely discardable failures.

DLQUpsert

Re-run the WriteContract and force an upsert. Pairs with the payload-healing pattern: set a flag, and the contract repairs bad fields at recovery time.

DLQReInsert

Re-enqueue under a mutated key (WithKeyMutator; a timestamp suffix by default), keeping both documents.

ProcessDLQ is one-shot across all bands; WithDLQAutoProcess(interval, strategy) runs it on a background ticker. A sink error with no correlation key aborts the commit in DLQ replay too.

Order-safe degraded mode. If a Redis write fails, WithDegradedModeDirect(true) (the default) can write straight to the datastore. Up to 1.0.7 it always did, even when an older version of the same key was still pending in Redis; that older version's later flush then overwrote the newer data. Now degraded mode first checks whether anything is pending for the key (the dirty set and the DLQ, both readable even under noeviction OOM) and writes directly only when nothing is. Otherwise, including when Redis is unreachable and pending versions cannot be ruled out, Write returns ErrDegradedWriteUnsafe without persisting anything. The caller retries, and the write goes through Redis in order.

Behaviour change. During a full Redis outage, degraded-mode writes now return errors instead of going direct. Callers must not ack those upstream; they are counted as op="degraded_refused".

Script-cache recovery. After a Redis restart, failover or SCRIPT FLUSH, a pre-loaded script SHA is gone. Every Lua call site now reloads and retries once on NOSCRIPT, where some paths previously failed until the process restarted.

3.7 · The full system view

Figure 10 · Everything, in one picture

STREAMS · asynchronous ingestSQS / Kafka → stateless consumer workers → Write
APIS · synchronousHTTP / gRPC → Write · Read · ReadBulk · Query
L1 local journal (optional) · in-process LRU per pod · sub-µswrite-through · converges via the sl:ns:bcast stream

L2 Redis state journal · cluster-safe via {band}

payload HASHp · ts · v · h
dirty ZSET16 bands
hot markerTTL 4h
indexesSET · ZSET · expiry queue
DLQ ZSETpayloads 7 days
bcast STREAMMAXLEN ~ N

Flush engine · 16 goroutines · 4 triggers

drain band
WriteContract
bulk write
conditional commit + TTL
L3 SYSTEM OF RECORDsink.FlushSink · DocumentDB · DynamoDB · PostgreSQL · yours
COLD READS & PRE-WARMINGsource.Source · Read on a miss · ReadBulk for working sets

The write side and the read side share one journal. That shared surface is the subject of §4.

Section 04 · The centrepiece

The read path: hot & cold

Here is the observation that turns sluice from a write buffer into a data platform: a wide-breadth stream is not uniformly wide. At any instant, a small subset of correlation keys is alive: a user is logged in, a session is open, an HTTP handler is about to read back the key it just wrote. The rest is background churn that only the datastore cares about. Treating those two populations identically wastes the journal's best property: it already holds the freshest possible copy of exactly the keys people are asking about.

sluice therefore runs two regimes over one journal. Cold keys are pure transit: absorbed, coalesced, flushed, then expired shortly after. Hot keys are promoted to resident state: warmed from the datastore on login, served in sub-millisecond (or, with L1, sub-microsecond) time for the length of the session, and kept fresh by the very traffic that touches them.

4.1 · Anatomy of the two regimes

Figure 11 · Cold vs hot, side by side

❄️ COLD correlation key

Definitionno hot marker; payload resident only while in transit
Read() → journal miss → Source via ReadContractone store read · 5–50 ms · then hydrated in the background
Write() → coalesces; flushed on time / volume / backloglatency ≈ FlushWindow (250 ms)
Residency → no TTL until flushed, then KeyTTL (30 s)marker: none

🔥 HOT correlation key

Definitionpayload resident + live hot marker
Read() → L1 (sub-µs) or L2 HGET + PTTL (sub-ms)lazy, extend-only TTL refresh
Write() → coalesces AND signals an immediate flushlatency < 10 ms
Residency → ActivityWindow (4 h) after each flushmarker: sl:ns:hot:{band}:user

Same Write() API, same journal. The regime is a property of the key's state, not of the call.

Dimension Cold Hot
Promotion — HotLoad() (fire-and-forget), typically on login
Read latency 5–50 ms (datastore), then journal-served once hydrated < 1 ms (L2) · sub-µs (L1)
Write→store latency ≤ FlushWindow < 10 ms (hot trigger)
Journal TTL none while unflushed; KeyTTL (30 s) after none while unflushed; ActivityWindow (4 h) after, extended by reads
Demotion — silence: marker and payload TTLs expire, no explicit eviction

4.2 · Tiered reads: each tier heals the one above it

A read falls through three tiers. L1 is an optional in-process LRU. L2 is the Redis journal: the authoritative live state and the write buffer. L3 is your datastore, reached through a Source and a ReadContract. A hit at any tier fills the tiers above it.

Figure 12 · Read(key) through L1 → L2 → L3

Read(key)
L1 hit?in-process · sub-µs · may be up to LocalTTL stale
return payload
↓ miss
L2: pipelined HGET + PTTLone round-trip · sub-ms
hit → fill L1refresh TTL if in last 20%
return payload
↓ journal miss
L3: ReadContract → Source.Readbytes or ErrRecordNotFound
return payload now
async hydrationL2 (miss-only) + L1 + indexes

Cold reads never wait for hydration. Hydration failures are recorded via RecordRedisOp and never surface on the read path.

Method Behaviour
Read(ctx, key)L1 → L2 → L3. With L1 on, may be up to LocalTTL stale.
ReadFresh(ctx, key)L2 → L3, bypassing L1. Use for checkout, payments and compliance reads.
HotLoad(ctx, key)Marks the key hot synchronously and hydrates it from the store in the background (§4.3).
IsHot(ctx, key)Whether the key has a payload resident in the journal.
Hydration never lies. Read-through, HotLoad and ReadBulk hydration go through a Lua primitive that seeds the journal only on a miss. Every write reaches the journal before the store, so an existing entry (pending, flushed or dead-lettered) is always at least as new as a store read; it wins and only its TTL is extended. Hydrated data is never added to the dirty set, so store data is never flushed back to the store and reader-only pods never build a backlog. Up to 1.0.7, hydration used the regular write path and did both of those things.

Lazy TTL refresh. The PTTL fetched with every L2 hit is not telemetry; it drives the refresh policy. When the remaining TTL falls below 20% of ActivityWindow, the read schedules a short, bounded refresh of the payload and marker off the read path. Steady read traffic therefore keeps a key hot indefinitely; silence lets it age out and demote itself. Refreshes are extend-only and skip unflushed payloads, so a read can never put a TTL on data that has not reached the store.

Figure 13 · The TTL timeline and the 20% refresh zone

safe zone · reads return as-is
refresh zone
flush · TTL = 4h3h12m remaining< 48m → refresh0 · demote
Read() hits L2HGET + PTTL · 1 RTT
PTTL < 20% of window?one comparison
extend marker + payloadkey stays hot

The check gates the refresh, so the common case does no extra work. Each flush of a hot key re-arms ActivityWindow as a second refresher.

4.3 · Promotion: fire-and-forget HotLoad

Promotion is explicit and cheap. In 1.0.8, HotLoad(ctx, user) returns only an error: it sets the hot marker synchronously and returns, then hydrates the payload, the L1 cache and the indexes in the background. A login handler is never blocked on a cold store read. If a caller needs the payload immediately, it calls Read afterwards, which is served from whichever tier has it.

Figure 14 · One session, three phases

application sluice (+ L1) Redis journal datastore phase 1 · login: promote to hot, never block HotLoad(user) SET hot marker (4h) nil, immediately background: ReadContract → Source.Read hydrate on miss + indexes + L1 + seed bcast phase 2 · session: the store is never read Write(user, payload) atomic write · hot → flush now Read(user) L1 hit (sub-µs), or L2 HGET + PTTL (sub-ms) phase 3 · cold key: transparent fallback Read(coldKey) L1 + L2 miss → Source.Read bytes returned now · L2 + L1 + indexes hydrated in the background

Dependencies are checked at call time: HotLoad returns ErrMissingSource or ErrMissingReadContract if the read path is not configured. A kind=seed broadcast goes out only when the payload was actually hydrated.

Writes to hot keys raise the hot trigger, pulling that band's flush forward from 250 ms to under 10 ms, which is what makes “write, then immediately read your own write” from another service behave correctly. With WithHotAwareFlush(true) (the default), a committed key that still has a live hot marker gets ActivityWindow instead of KeyTTL, so a flush can never evict a live session.

4.4 · The L1 local journal and cross-pod convergence

An optional, sharded in-process LRU (256 shards) sits in front of the journal. Writes go through to the local L1, so a same-pod Read() after Write() returns in sub-microseconds. They are also broadcast to peer pods on a Redis Stream, sl:{ns}:bcast. The XADD piggy-backs on the journal write's pipeline, so the broadcast costs no extra round-trip, and peer pods converge within milliseconds.

Figure 15 · Push-pull convergence across pods

Pod A · writer

Write(user, payload)
L1 A.Put(v = ts)write-through
journal pipelinewrite script + XADD bcast

Redis

payload HASH + dirty ZSET
sl:ns:bcast STREAMMAXLEN ~ Retention · one slot

Pod B · peer

subscriber XREAD BLOCKBlockMS, default 50 ms
version gateapply only if v ≥ local v
L1 B updatednext Read is sub-µs

The version gate is timestamp-based, so an out-of-order replay can never regress newer state. It uses >=, so same-millisecond writes apply last-writer-wins.

sl, _ := sluice.New("nudge_inventory").
    // ...
    WithLocalCache(localjournal.LocalCacheConfig{
        Mode:       localjournal.LocalCachePushPull, // Off (default) · Lazy · PushPull
        MaxEntries: 200_000,                         // global LRU cap across 256 shards
        LocalTTL:   60 * time.Second,                // staleness bound
        Broadcast:  shield.BroadcastPayload,         // or BroadcastInvalidation (~40B/msg, peers refetch)
        Retention:  200_000,                         // stream MAXLEN ~ N
    }).
    Build(ctx)
Mode Behaviour
LocalCacheOffDefault. No L1; reads behave exactly as in 1.0.7
LocalCacheLazyFilled on demand from L2, bounded by LocalTTL; no broadcast
LocalCachePushPullLazy fill, plus a stream subscriber that applies peer writes

L1 trades a bounded amount of staleness (LocalTTL) for latency. Reads that cannot tolerate any, such as checkout or compliance lookups, use ReadFresh, which skips L1 entirely. LocalCacheConfig and the broadcast-mode constants currently live in internal/ packages, so for now they can be named only from inside the module, as the bundled examples do.

4.5 · The journal as a queryable store

Because hot keys, bulk-loaded sets and in-flight writes are already resident, the journal can answer questions about live state without touching the datastore. An optional IndexContract projects fields out of each payload as it lands (and an IndexBulkContract does the same for ReadBulk results). sluice maintains the indexes through a Go-side pipeline, with no Lua and no cjson, so the path is safe on Valkey as well as Redis.

Figure 16 · Index types and the Query() pipeline

string value → equality SETsl:ns:idx:{band}:channel:push · members = matching keys
float64 / int64 → range ZSETsl:ns:ridx:{band}:priority · score = the value itself
Query{Equality, RangeMin, RangeMax}
per band: SINTERsame {band} → slot-legal
range filterper candidate
pipeline HGEThydrate payloads

At least one equality filter is required. Index maintenance is best-effort and never fails the primary write.

Indexes follow their payloads. Up to 1.0.7, index entries of cold keys lingered for up to ActivityWindow after their 30 s post-flush payload had expired, until a full sweep (a ~4 minute pass) reached them, so Redis memory grew without bound under sustained write load. Now, whenever a payload gets or extends a TTL, it is also scored into a per-band index expiry queue (sl:ns:idxexp:{band}). A pruner drains it every second and removes index entries within about a second of their payload expiring. Its cost is proportional to what expires, not to index size, and it re-checks liveness, so a live or re-written key is never pruned. The full sweep (WithIndexSweepInterval, default 15 s per band) remains as a safety net.

4.6 · Memory economics

Redis memory tracks two things: your active-key count and your in-flight backlog, not your total key space. Each class of key has exactly one rule:

Key state Residency Governed by
unflushed (any key)no TTL until committedwrite rate × store availability; size Redis for the worst-case backlog
flushed, coldKeyTTL (30 s)recent write breadth
flushed, hotActivityWindow (4 h), re-armed per flush, extended by readsconcurrent active sessions
hydrated / bulk-loadedActivityWindowworking sets you chose to load
index entriespruned within ~1 s of their payloadthe payloads above
Fixed in 1.0.8. Up to 1.0.7, hot-aware flush extended every flushed key's TTL to ActivityWindow, not only hot ones, inflating Redis memory by orders of magnitude for write-heavy services. Now cold keys get KeyTTL after flush and only keys with a live hot marker get ActivityWindow. The TTL and hot-marker refresh run as three pipelines per flush batch rather than per-key round-trips.

Demotion needs no machinery: a hot key that goes quiet stops being refreshed, its marker and payload expire, its index entries are pruned, and the next Read() falls back to the Source. The regime is self-balancing; memory tracks activity, not history.

Section 05 · New in 1.0.8

Pre-warming working sets

Many access patterns are set-shaped: “all active campaigns for this user”, “the last 50 transactions on this account”. Assembling them key by key is the N+1 problem on the read side. ReadBulk runs one set-based query for a lookup key, then hydrates every returned item into L2, the secondary indexes and L1. After that, per-key Read and Query never touch the store.

Figure 17 · One query in, a whole working set resident

ReadBulk(ctx, "user_123")
ReadBulkContractlookup key → native bulk plan
Source.ReadBulk1 query · Projector → []BulkReadResult
3 pipelineshydrate journal · update indexes · get TTLs
map[key][]byte+ mirrored into L1

One Redis round-trip per pipeline, regardless of result-set size. An empty result returns empty maps without touching Redis.

sl, _ := sluice.New("campaigns").
    WithRedis(sluice.RedisConfig{Addrs: redisAddrs}).
    WithSource(pgsource.NewSourceWithPool(pool)).
    WithReadBulkContract(func(userID string) (*source.BulkReadModel, error) {
        return &source.BulkReadModel{
            Query: pgsource.PostgresBulkReadModel{
                Query: `SELECT id, json_build_object('id', id, 'status', status, 'priority', priority)
                        FROM campaigns WHERE user_id = $1 LIMIT 50`,
                Args:      []any{userID},
                Projector: projectCampaigns, // pgx.Rows → []source.BulkReadResult
            },
        }, nil
    }).
    WithIndexBulkContract(campaignIndexes). // optional: makes bulk-loaded items queryable
    Build(ctx)

payloads, err := sl.ReadBulk(ctx, "user_123")              // map[key][]byte
payloads, ttls, err := sl.ReadBulkWithTTL(ctx, "user_123") // + remaining journal TTL (ms)
Adapter Native bulk plan Projector input
source/postgresPostgresBulkReadModel{Query, Args}pgx.Rows
source/docdbDocDBBulkReadModel{Filter, FindOptions} (sort, limit, projection)*mongo.Cursor
source/dynamodbDynamoBulkReadModel{QueryInput} (single page on a partition key)[]map[string]types.AttributeValue

Read-your-writes. Bulk hydration uses the same miss-only primitive as read-through. For a key already in the journal (for example, a pending Write), ReadBulk returns and mirrors into L1 the journal payload, not the store's, so stale store data never masks a newer write. The hydration timestamp is captured before the source query and used as the L1 version.

Bulk-hydrated items live for ActivityWindow. sluice does not cap projector output, so bound your queries with LIMIT, SetLimit or QueryInput.Limit. A natural deployment is a bulk pre-warmer job that loads active users' working sets ahead of peak traffic (§7.3).

Section 06 · Hardened in 1.0.8

The durability model

A velocity platform is only useful if acknowledged data is never silently lost. The 1.0.8 release audited every path between Write returning nil and the datastore confirming the record, and adopted one rule throughout: prefer a loud failure to a quiet drop.

Figure 18 · The life of a payload's TTL

Writenil = journaled · ack
unflushedPERSIST · no TTL · dirty
store confirmsper key, attributed
commit if v unchangedTTL = KeyTTL or ActivityWindow
expiryindexes pruned ~1 s later

The only way out of the unflushed state is a confirmed, attributed commit, or the DLQ.

Guarantee How
Ack means journaledWrite returns nil only after its entry is in Redis, in batched mode too: each caller gets its own entry's result.
Unflushed never expiresPayloads are persistent until the sink confirms them. TTLs apply only after a commit, and every TTL refresh is extend-only.
Commits can't lose writesEvery write bumps a per-key sequence; commit and dead-lettering are conditional on it. A write that races an in-flight flush stays dirty.
No commit without attributionA sink error with no correlation key aborts the commit for the whole batch, in the flush engine and in DLQ replay. Nothing is committed just because no error named it.
Retry vs dead-letter is explicitEvery bundled sink classifies each error as transient or permanent (§7.2). A concurrent-upsert race between pods is retried, not dead-lettered.
At-least-once, idempotentA crash between bulk write and commit re-flushes the batch; upsert semantics make that safe.
Losses are loudA dirty key whose payload is gone at flush time gets ErrPayloadMissing (via OnFlush), an error log, a RecordUnflushedExpiry count and a DLQ entry. Any non-zero count should page.
Degraded mode keeps orderDirect writes happen only when nothing older is pending for the key; otherwise ErrDegradedWriteUnsafe. Retry it; don't ack it.
Survives script-cache lossEvery Lua call site reloads and retries once on NOSCRIPT.
No crash on sink outageOnFlush receives an empty, non-nil result alongside the error when a sink fails outright; up to 1.0.7 this dereferenced nil and crashed the flush goroutine.
Run the journal on durable Redis. Use maxmemory-policy noeviction (eviction would drop unflushed state) plus AOF and replicas, or MemoryDB. ElastiCache alone does not persist unflushed writes across node loss. The bundled docker-compose.yml now runs Redis with noeviction and appendfsync everysec on a dedicated volume, so a local crash loses at most ~1 s of unflushed writes.

What remains is the class of loss no in-Redis mechanism can detect: losing Redis itself (node loss, failover to a lagging replica, FLUSHDB) after the ack. That is the subject of the proposed event ledger on the roadmap (§12).

Section 07 · New in 1.0.8

Datastores & deployment topologies

sluice never parses your data and never creates tables or emits DDL. Your contracts define the data shape and your migrations own the schema. That is what lets the same journal sit in front of three very different stores, each with a different bottleneck to remove.

7.1 · Adapters

Store Sink (write) Source (read) Bottleneck removed
DocumentDB / MongoDB sink/docdb: unordered BulkWrite source/docdb: FindOne; Find for bulk Per-write index I/O on a single primary; connection caps
DynamoDB sink/dynamodb: BatchWriteItem in 25-item chunks, UnprocessedItems mapped back to their keys and retried with backoff source/dynamodb: GetItem with ConsistentRead: true; Query for bulk WCU spend: bursts flatten to a low, steady provisioned baseline; lookups use Redis indexes instead of GSIs; idempotency uses SETNX instead of TransactWriteItems
PostgreSQL sink/postgres: multi-row INSERT … ON CONFLICT DO UPDATE (or DO NOTHING) over a bounded pgxpool source/postgres: parameterised query + Projector, which supports joins and aggregations Connection saturation, per-row transaction overhead, WAL/MVCC churn from repeated updates

Bring your own store by implementing two small interfaces. In 1.0.8 the Source interface gained ReadBulk:

// write side
type FlushSink interface {
    BulkWrite(ctx, models) (*BulkWriteResult, error)
    Write(ctx, model) error      // degraded mode
    Ping(ctx) error
    Close(ctx) error
}
// read side, symmetric by design
type Source interface {
    Read(ctx, model) ([]byte, error)
    ReadBulk(ctx, model) ([]BulkReadResult, error) // new
    Ping(ctx) error
    Close(ctx) error
}

NewSourceWithClient / NewSourceWithPool let the sink and source share one connection pool. source.ErrRecordNotFound is translated to the public sluice.ErrRecordNotFound, so callers never import the source package for error handling.

7.2 · Error classification

The engine never infers success, so every sink must say, per key, whether a failure is worth retrying. How each bundled sink classifies failures:

Sink Transient (retried) Permanent (dead-lettered) Whole batch retried
sink/docdb 11000 on _id_ for an upsert (a race with another pod) Any other write error, including 11000 on a business unique index Write-concern error, network or context error
sink/dynamodb UnprocessedItems, context cancel/deadline Bad Update type, missing PK/SK, marshal failure, duplicate key in the batch, per-item PutItem failure after a ValidationException fallback An unprocessed item that can't be mapped to a key; any other API error
sink/postgres Any other SQLSTATE 23xxx, 42P01, 42703, 21000; a row whose columns differ from the batch's first row; a duplicate conflict key in the batch A non-Postgres error, e.g. a connection failure

On a permanent multi-row error, sink/postgres retries the batch row by row, and on a batch-wide ValidationException, sink/dynamodb falls back to per-item calls, so only the bad rows are dead-lettered. A custom sink reports per-key failures the same way:

res.Errors = append(res.Errors, sink.SinkError{
    CorrelationKey: m.CorrelationKey,     // empty → whole batch aborted (ErrUnattributedSinkError)
    Code:           code,                 // store-specific; optional
    Class:          sink.ClassPermanent,  // or sink.ClassTransient
    Err:            err,
})

ClassUnknown (the zero value) keeps the legacy rule: dead-lettered if Code == 11000, otherwise retried. SinkError.IsPermanent() implements the rule, and sink.CheckAttribution(models, result) is the same guard the engine runs.

7.3 · Composable deployment topologies

In 1.0.8, Build() requires only a namespace and Redis. Every other component is optional, and each operation checks its own dependencies when it is called. The same binary can therefore run in four shapes, all sharing one journal:

Figure 19 · Four topologies, one journal

Full pod

Sink + WriteContract + Source + ReadContract

Stream ingestion and read APIs in one service.

Reader-only gateway

Source + read contracts, no sink

Stateless API pods reading what full pods wrote; they hydrate on a miss but never write to the store.

Bulk pre-warmer

Source + ReadBulkContract + IndexBulkContract

A job that loads working sets ahead of peak traffic.

Write-only ingester

Sink + WriteContract, no source

High-velocity consumers that never serve reads.

The flush engine starts only where both a sink and a WriteContract are configured. DrainAndClose is safe on every topology.

Operation Requires When missing
Write · WriteIdempotent · ProcessDLQSink + WriteContractErrMissingSink / ErrMissingWriteContract
Read · ReadFreshRedis; Source + ReadContract for the cold pathErrRecordNotFound on a full miss
HotLoadSource + ReadContractErrMissingSource / ErrMissingReadContract
ReadBulk · ReadBulkWithTTLSource + ReadBulkContracterror
QueryIndexContract and/or IndexBulkContractempty result

Section 08 · New in 1.0.8

Observability

metrics/prometheus is a ready-made MetricsRecorder with counters, gauges and histograms named sluice_<namespace>_<metric>:

import sluiceprom "github.com/hussainpithawala/sluice-go/metrics/prometheus"

rec := sluiceprom.NewRecorder("nudge_inventory") // registers on prometheus.DefaultRegisterer
s, _ := sluice.New("nudge_inventory"). /* ... */ WithMetrics(rec).Build(ctx)

mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
go http.ListenAndServe(":2112", mux)
Area Metrics
Write pathwrite_total, degraded_write_total{error}, redis_op_duration_seconds{op,error}
Flush engineflush_duration_seconds{band,error}, flush_batch_size{band}, dirty_queue_depth{band}
Read pathread_duration_seconds{is_hot,error}, warmup_duration_seconds{error}, hot_set_size
L1 / broadcastlocal_cache_hit_total, local_cache_miss_total{reason}, local_set_size, broadcast_lag_seconds
Failurescontract_error_total, dead_letter_total{band}, dlq_process_total{strategy,outcome}
Durabilityunflushed_expiry_total{band}: data loss, must stay 0

Signals worth watching. A falling is_hot="true" share of reads means sessions age out before their traffic ends, so raise ActivityWindow. The L1 hit ratio tells you how to size MaxEntries and LocalTTL. op="degraded_refused" counts writes refused to preserve ordering. hot_set_size is your Redis memory forecast; a background sampler emits it (SCAN, every 30 s by default) along with local_set_size, but only when a non-noop recorder is configured.

Grafana dashboarddashboards/sluice-overview.json: write path, flush engine, hot/cold, L1, DLQ, durability
Alert rulesmonitoring/prometheus/rules/sluice.rules.yml: unflushed loss (critical), degraded refusals, flush latency, backlog, L1 hit ratio, broadcast lag, DLQ inflow
Local stackmake docker-up provisions Prometheus (:9090) and Grafana (:3000)

For Datadog, CloudWatch or anything else, implement MetricsRecorder yourself. It has sixteen methods; 1.0.8 added the four L1 hooks (RecordLocalCacheHit, RecordLocalCacheMiss, RecordLocalSetSize, RecordBroadcastLag) and RecordUnflushedExpiry. Two read-side metric bugs were also fixed: the tiered Read() now records every read, and the L1 hit-ratio query now matches.

Section 09

The library APIs

The public surface is deliberately small: a builder, five contracts and a dozen verbs. Everything else lives behind interfaces you implement (FlushSink, Source, MetricsRecorder).

9.1 · Construction and lifecycle

// Only the namespace and Redis are required; everything else enables a capability.
s, err := sluice.New("nudge_inventory").
    WithRedis(sluice.RedisConfig{Addrs: []string{"redis:6379"}}).
    WithSink(sk).                      // write side: Sink + WriteContract start the engine
    WithWriteContract(contract).
    WithSource(src).                   // read side: cold Read, HotLoad
    WithReadContract(readContract).
    WithReadBulkContract(bulkContract).  // enables ReadBulk
    WithIndexContract(indexContract).  // enables Query()
    Build(ctx)
defer s.DrainAndClose(ctx)          // stop batcher, drain engine, stop DLQ ticker, close sink

9.2 · Write path

Method Semantics
Write(ctx, user, payload) Journals the event; nil means durably journaled and safe to ack. On a hot key, also raises the hot flush trigger. When Redis fails, writes direct only if order-safe, else ErrDegradedWriteUnsafe.
WriteIdempotent(ctx, user, payload, msgID) Write guarded by SETNX EX. Replays return ErrDuplicateIdempotencyKey so consumers can ack without re-journalling.
OnFlush(callback) Invoked after every bulk write attempt, success or failure, with the keys, a non-nil result and the error (including ErrPayloadMissing).

9.3 · Read path & regime

Method Semantics
Read(ctx, user) L1 → L2 (with lazy refresh) → Source, hydrating on the way back. Absent everywhere → ErrRecordNotFound.
ReadFresh(ctx, user) L2 → Source, bypassing L1. For strict-consistency reads.
HotLoad(ctx, user) error Marks the key hot synchronously; hydrates payload, L1 and indexes in the background. Call Read afterwards if you need the payload.
ReadBulk(ctx, lookupKey) One set-based query; hydrates every result. Returns map[string][]byte.
ReadBulkWithTTL(ctx, lookupKey) As above, plus each key's remaining journal TTL in ms.
IsHot(ctx, user) Whether the key has a payload resident in the journal.
Query(ctx, Query) Compound lookup over resident state. Returns []QueryResult{CorrelationKey, Payload}.
// The hot regime in application code
_ = s.HotLoad(ctx, user)                     // user logs in: never blocks on the store
payload, err := s.Read(ctx, user)          // sync HTTP: sub-µs in L1, sub-ms in L2
payload, err  = s.ReadFresh(ctx, user)     // checkout: skip L1
set, err     := s.ReadBulk(ctx, user)      // whole working set, one query
res, err     := s.Query(ctx, sluice.Query{  // live-state compound lookup
    Equality: map[string]string{"channel": "push"},
    RangeMin: map[string]float64{"priority": 3},
})

9.4 · Dead-letter operations

result, err := s.ProcessDLQ(ctx, sluice.DLQUpsert,
    sluice.WithDLQBatchSize(500),
    sluice.WithKeyMutator(func(k string) string { return k + ":retry" }), // DLQReInsert
    sluice.WithDLQLogger(slog.Default()),
)
// result.Processed / .Succeeded / .Failed
// or let sluice own the cadence:
//   WithDLQAutoProcess(2*time.Minute, sluice.DLQUpsert)

9.5 · The five contracts

Contract Signature Enables
WriteContract(key, payload) → *WriteModelThe flush engine and Write. Called once per key per flush, never on the Write() hot path
ReadContract(key) → *source.ReadModelCold Read, HotLoad
IndexContract(key, payload) → map[field]valueSecondary indexes, Query
ReadBulkContract(lookupKey) → *source.BulkReadModelReadBulk
IndexBulkContract([]BulkReadResult) → map[key]map[field]valueIndexes for bulk-loaded items

Contracts return datastore-native plans (a Mongo filter, a DynamoDB QueryInput, a SQL query and projector); the adapter executes them, so sluice itself stays datastore-agnostic.

9.6 · Sentinel errors

Sentinel error Raised by Meaning
ErrRecordNotFoundRead, ReadFreshAbsent from journal and source alike
ErrDuplicateIdempotencyKeyWriteIdempotentGuard already consumed: ack and move on
ErrRedisUnavailableWriteRedis failed and degraded mode is off
ErrDegradedWriteUnsafeWriteRedis failed and a direct write could be reordered (wraps ErrRedisUnavailable); retry, don't ack
ErrContractViolationdegraded WriteWriteContract rejected the payload
ErrPayloadMissingOnFlush callbackA dirty key's payload was gone at flush time; dead-lettered
ErrMissingSink · ErrMissingWriteContractwrite-path methodsWrite path not configured on this instance
ErrMissingSource · ErrMissingReadContractHotLoadRead path not configured
ErrEmptyCorrelationKeyWrite, WriteIdempotentEmpty correlation or idempotency key
ErrLibraryClosedevery methodCalled after DrainAndClose
ErrMissingNamespace · ErrMissingRedisBuildRequired builder option not set

Section 10

Configuration

Every knob is a builder method with a production-safe default; nothing is required except a namespace and Redis. The tables pair each knob with what it controls.

10.1 · Write path

Builder method Default What it controls
WithSink(s) · WithWriteContract(fn)nilBoth required to start the flush engine
WithFlushWindow(d)250 msTime trigger; caps datastore staleness
WithMaxBatchSize(n)1000Keys per bulk write; volume-trigger threshold
WithBandCount(n)16Parallel flush goroutines / dirty-set partitions
WithKeyTTL(d)30 sChanged: post-flush TTL for cold payloads and the backlog-trigger threshold. No longer a TTL on unflushed writes
WithDegradedModeDirect(b)trueOrder-safe direct writes when Redis fails
WithBatchedWrites(size, win)offPipeline concurrent Writes: ⌈N/size⌉ round-trips instead of N. Worth it above ~10K writes/sec with many writers
WithContentDedup(b)falsexxHash64 fingerprinting; skip unchanged payloads
WithIdempotencyTTL(d)4 hRetention of WriteIdempotent guards; size to upstream redelivery
OnFlush(cb)nilPer-batch result callback

10.2 · Read path, L1 & indexes

Builder method Default What it controls
WithSource(s)nilRead-side datastore; checked when the read path is used, not at Build
WithReadContract(fn)nilEnables cold Read and HotLoad
WithReadBulkContract(fn)nilEnables ReadBulk
WithActivityWindow(d)4 hResidency of hot and hydrated keys; lazy refresh fires in its last 20%
WithHotAwareFlush(b)trueFlushed hot keys keep ActivityWindow; writes to hot keys flush immediately
WithLocalCache(cfg)offL1 local journal: Mode, MaxEntries, LocalTTL, Broadcast, Retention (§4.4)
WithIndexContract(fn) · WithIndexBulkContract(fn)nilEnable Query for written / bulk-loaded keys
WithIndexSweepInterval(d)15 sFull index sweep cadence; -1 disables the sweep only, not the expiry-queue pruner

10.3 · Operations & Redis connectivity

Knob Default Notes
WithMetrics(m)noopMetricsRecorder, e.g. metrics/prometheus
WithDLQAutoProcess(i, strat)offBackground ProcessDLQ ticker; stopped by DrainAndClose
WithHotSetSampleInterval(d)30 shot_set_size sampling (uses SCAN); negative disables it
RedisConfig.ClusterModefalseMust be explicit, never inferred from address count. ElastiCache CME uses ONE config endpoint
RedisConfig.Username—Forwarded explicitly; omitting it silently AUTHs as the default ACL user
RedisConfig.DB0Must stay 0 under cluster mode; validated at construction

10.4 · Four reference profiles

// ① Write-only ingester: no read path.
sluice.New(ns).WithRedis(rc).WithSink(sk).WithWriteContract(wc).
    WithHotAwareFlush(false).                     // no hot keys to protect
    WithBatchedWrites(200, 5*time.Millisecond).
    WithContentDedup(true).
    Build(ctx)
// ② Full pod: the defaults are already this profile.
sluice.New(ns).WithRedis(rc).WithSink(sk).WithWriteContract(wc).
    WithSource(src).WithReadContract(rc2).WithIndexContract(ic).
    WithMetrics(sluiceprom.NewRecorder(ns)).
    Build(ctx)                                     // 4h window, hot-aware flush on
// ③ Reader-only gateway: stateless API pods with an L1 in front.
sluice.New(ns).WithRedis(rc).
    WithSource(src).WithReadContract(rc2).
    WithLocalCache(localjournal.LocalCacheConfig{Mode: localjournal.LocalCachePushPull, MaxEntries: 200_000, LocalTTL: 60 * time.Second}).
    Build(ctx)                                     // no sink → no engine; Write returns ErrMissingSink
// ④ Bulk pre-warmer: load working sets before peak.
sluice.New(ns).WithRedis(rc).
    WithSource(src).WithReadBulkContract(bc).WithIndexBulkContract(ibc).
    Build(ctx)
Tuning heuristics.
  • Set FlushWindow to the staleness your readers tolerate; nothing else bounds it.
  • Size Redis for the worst-case backlog, not the steady state: unflushed state never expires, and under noeviction a full Redis refuses writes.
  • Set ActivityWindow from session length (p95 login-to-logout), not from memory fear; watch hot_set_size instead.
  • Size L1 from its hit ratio, and use ReadFresh rather than a tiny LocalTTL for reads that need strict consistency.
  • Enable WithBatchedWrites only when per-write Redis latency, not the datastore, is the bottleneck.
  • Page on any non-zero unflushed_expiry_total.

Section 11

Upgrading from 1.0.7

1.0.8 contains breaking changes. Check each of these before you upgrade:

Change What to do
HotLoad returns only errorIt now hydrates in the background. Call Read after HotLoad if you need the payload right away
Source gains ReadBulkAdd ReadBulk to custom Source implementations
MetricsRecorder gains methodsAdd RecordUnflushedExpiry and the four L1 hooks to custom recorders; alert on any non-zero unflushed-expiry count
ErrMissingContract renamedIt is now ErrMissingWriteContract; update errors.Is checks
Build() validates lessIt no longer requires a sink or write contract, or checks that a ReadContract has a Source. Handle ErrMissingSink / ErrMissingWriteContract from write-path methods
Degraded mode refuses unsafe writesRetry ErrDegradedWriteUnsafe, including during a full Redis outage, and don't ack it upstream
KeyTTL semanticsIt is now the post-flush TTL for cold payloads. Unflushed writes no longer expire, so size Redis for your worst-case backlog and run it with noeviction
Examples movedNow under examples/<scenario>/<adapter>/; update any paths or scripts

ReadOld is deprecated: use Read, or ReadFresh for strict consistency. DocumentDB adapter error messages now use the sluice/documentdb: / documentdb: prefixes; import paths are unchanged. The full list is in the changelog.

Section 12

Closing

sluice is best understood as four decisions stacked on each other. First, that Redis should be used as a journal rather than a cache, which buys atomic absorption and free coalescing. Second, that band partitioning with hash tags makes the journal parallel and cluster-legal by construction rather than by care. Third, that the journal's contents are worth serving back, through an in-process tier, a hot/cold regime and set-based pre-warming, turning a write-optimised buffer into the fastest read path in the system for exactly the keys that matter right now. And fourth, the one 1.0.8 made explicit: an acknowledged write is never dropped quietly. It reaches the store, the DLQ, or an alert.

The result is a library where the caller contributes a few small functions and receives, in exchange, a crash-safe, deduplicating, idempotent, cluster-aware, self-healing data plane for DocumentDB, DynamoDB, PostgreSQL or a store of their own, validated end-to-end against real Redis, Valkey cluster, MongoDB, DynamoDB Local, PostgreSQL, Kafka and LocalStack.

What's next

  • Event ledger and reconciliation (RFP #17, proposed): an opt-in record of acknowledged writes kept outside Redis, in an embedded Pebble store backed by object storage, plus a Reconcile job that finds and repairs keys whose datastore state is behind what was acknowledged, for example after losing Redis. By default it never affects Write's result.
  • Strict mode (RFP #19, proposed): payment-grade namespaces with durable acknowledgement (WAIT/WAITAOF or a durable store such as MemoryDB), conditional writes (WriteIf) and a store-side version guard that stops an older flush from overwriting a newer version.
🌊

go get github.com/hussainpithawala/sluice-go@v1.0.8

MIT licensed · Redis & Valkey compatible · DocumentDB / MongoDB, DynamoDB and PostgreSQL adapters in the box