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 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 ingest | 10K events/sec |
| Peak spike | 100K 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 lag | 250 ms (configurable FlushWindow) |
L1 Read() (same pod) | sub-microsecond, in-process LRU |
L2 Read() | sub-millisecond, one pipelined round-trip |
| Cross-pod L1 convergence | milliseconds, via a Redis Streams broadcast |
| Working-set load | one set-based query per lookup key (ReadBulk) |
| Crash recovery | at-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
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
|
Figure 2 · The sluice path: absorb, coalesce, drain
100K events/sec
HSET + PERSIST + ZADD · 1 atomic RT · sub-ms ACK
16 bands · 4 triggers
~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
Write(user, payload)
EVALSHA write · single round-trip
< 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).
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
dirty set after 250 ms
3 entries, not 6
datastore
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
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
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
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 error | Commit nothing; the whole batch stays dirty and is retried (network, timeout, write-concern failure) |
| per-key error, no key | Commit nothing; sink.ErrUnattributedSinkError
goes to OnFlush and the whole batch is retried |
| per-key, transient | That key stays dirty and is retried |
| per-key, permanent | That key is dead-lettered as permanent_sink_error |
| no error for a key | The 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
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_violation | WriteContract returned an error |
| permanent_sink_error | The sink classified the key's error as permanent |
| payload_missing_before_flush | The 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.
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
L2 Redis state journal · cluster-safe via {band}
Flush engine · 16 goroutines · 4 triggers
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
🔥 HOT correlation key
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
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. |
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
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
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
Redis
Pod B · peer
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 |
|---|---|
| LocalCacheOff | Default. No L1; reads behave exactly as in 1.0.7 |
| LocalCacheLazy | Filled on demand from L2, bounded by LocalTTL;
no broadcast |
| LocalCachePushPull | Lazy 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
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 committed | write rate × store availability; size Redis for the worst-case backlog |
| flushed, cold | KeyTTL (30 s) | recent write breadth |
| flushed, hot | ActivityWindow (4 h), re-armed per flush,
extended by reads | concurrent active sessions |
| hydrated / bulk-loaded | ActivityWindow | working sets you chose to load |
| index entries | pruned within ~1 s of their payload | the payloads above |
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
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/postgres | PostgresBulkReadModel{Query, Args} | pgx.Rows |
| source/docdb | DocDBBulkReadModel{Filter, FindOptions}
(sort, limit, projection) | *mongo.Cursor |
| source/dynamodb | DynamoBulkReadModel{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
The only way out of the unflushed state is a confirmed, attributed commit, or the DLQ.
| Guarantee | How |
|---|---|
| Ack means journaled | Write returns nil only after its entry is in Redis, in batched mode too: each
caller gets its own entry's result. |
| Unflushed never expires | Payloads are persistent until the sink confirms them. TTLs apply only after a commit, and every TTL refresh is extend-only. |
| Commits can't lose writes | Every 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 attribution | A 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 explicit | Every 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, idempotent | A crash between bulk write and commit re-flushes the batch; upsert semantics make that safe. |
| Losses are loud | A 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 order | Direct writes happen only when nothing older is pending
for the key; otherwise ErrDegradedWriteUnsafe. Retry it; don't
ack it. |
| Survives script-cache loss | Every Lua call site reloads and retries once on
NOSCRIPT. |
| No crash on sink outage | OnFlush 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. |
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 · ProcessDLQ | Sink + WriteContract | ErrMissingSink / ErrMissingWriteContract |
| Read · ReadFresh | Redis; Source + ReadContract for the cold path | ErrRecordNotFound on a full miss |
| HotLoad | Source + ReadContract | ErrMissingSource
/ ErrMissingReadContract |
| ReadBulk · ReadBulkWithTTL | Source + ReadBulkContract | error |
| Query | IndexContract and/or IndexBulkContract | empty 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 path | write_total, degraded_write_total{error},
redis_op_duration_seconds{op,error} |
| Flush engine | flush_duration_seconds{band,error}, flush_batch_size{band}, dirty_queue_depth{band}
|
| Read path | read_duration_seconds{is_hot,error}, warmup_duration_seconds{error}, hot_set_size
|
| L1 / broadcast | local_cache_hit_total, local_cache_miss_total{reason},
local_set_size, broadcast_lag_seconds
|
| Failures | contract_error_total, dead_letter_total{band},
dlq_process_total{strategy,outcome} |
| Durability | unflushed_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.
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) → *WriteModel | The
flush engine and Write. Called once per key per flush, never on
the Write() hot path |
| ReadContract | (key) → *source.ReadModel | Cold
Read, HotLoad |
| IndexContract | (key, payload) → map[field]value | Secondary
indexes, Query |
| ReadBulkContract | (lookupKey) → *source.BulkReadModel | ReadBulk |
| IndexBulkContract | ([]BulkReadResult) → map[key]map[field]value | Indexes 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 |
|---|---|---|
| ErrRecordNotFound | Read, ReadFresh | Absent from journal and source alike |
| ErrDuplicateIdempotencyKey | WriteIdempotent | Guard already consumed: ack and move on |
| ErrRedisUnavailable | Write | Redis failed and degraded mode is off |
| ErrDegradedWriteUnsafe | Write | Redis failed and a direct write could be reordered (wraps ErrRedisUnavailable); retry, don't ack |
| ErrContractViolation | degraded Write | WriteContract rejected the payload |
| ErrPayloadMissing | OnFlush callback | A dirty key's payload was gone at flush time; dead-lettered |
| ErrMissingSink · ErrMissingWriteContract | write-path methods | Write path not configured on this instance |
| ErrMissingSource · ErrMissingReadContract | HotLoad | Read path not configured |
| ErrEmptyCorrelationKey | Write, WriteIdempotent | Empty correlation or idempotency key |
| ErrLibraryClosed | every method | Called after DrainAndClose |
| ErrMissingNamespace · ErrMissingRedis | Build | Required 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) | nil | Both required to start the flush engine |
| WithFlushWindow(d) | 250 ms | Time trigger; caps datastore staleness |
| WithMaxBatchSize(n) | 1000 | Keys per bulk write; volume-trigger threshold |
| WithBandCount(n) | 16 | Parallel flush goroutines / dirty-set partitions |
| WithKeyTTL(d) | 30 s | Changed: post-flush TTL for cold payloads and the backlog-trigger threshold. No longer a TTL on unflushed writes |
| WithDegradedModeDirect(b) | true | Order-safe direct writes when Redis fails |
| WithBatchedWrites(size, win) | off | Pipeline concurrent Writes: ⌈N/size⌉ round-trips instead of N. Worth it above ~10K writes/sec with many writers |
| WithContentDedup(b) | false | xxHash64 fingerprinting; skip unchanged payloads |
| WithIdempotencyTTL(d) | 4 h | Retention of WriteIdempotent guards; size to upstream redelivery |
| OnFlush(cb) | nil | Per-batch result callback |
10.2 · Read path, L1 & indexes
| Builder method | Default | What it controls |
|---|---|---|
| WithSource(s) | nil | Read-side datastore; checked when the read path is used, not at Build |
| WithReadContract(fn) | nil | Enables cold Read and HotLoad |
| WithReadBulkContract(fn) | nil | Enables ReadBulk |
| WithActivityWindow(d) | 4 h | Residency of hot and hydrated keys; lazy refresh fires in its last 20% |
| WithHotAwareFlush(b) | true | Flushed hot keys keep ActivityWindow; writes to hot keys flush immediately |
| WithLocalCache(cfg) | off | L1 local journal: Mode, MaxEntries, LocalTTL, Broadcast, Retention (§4.4) |
| WithIndexContract(fn) · WithIndexBulkContract(fn) | nil | Enable Query for written / bulk-loaded keys |
| WithIndexSweepInterval(d) | 15 s | Full index sweep cadence; -1 disables the sweep only, not the expiry-queue pruner |
10.3 · Operations & Redis connectivity
| Knob | Default | Notes |
|---|---|---|
| WithMetrics(m) | noop | MetricsRecorder, e.g. metrics/prometheus |
| WithDLQAutoProcess(i, strat) | off | Background ProcessDLQ ticker; stopped by DrainAndClose |
| WithHotSetSampleInterval(d) | 30 s | hot_set_size sampling (uses SCAN); negative disables it |
| RedisConfig.ClusterMode | false | Must 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.DB | 0 | Must 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)
- Set
FlushWindowto 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
noevictiona full Redis refuses writes. - Set
ActivityWindowfrom session length (p95 login-to-logout), not from memory fear; watchhot_set_sizeinstead. - Size L1 from its hit ratio, and use
ReadFreshrather than a tinyLocalTTLfor reads that need strict consistency. - Enable
WithBatchedWritesonly 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 error | It now hydrates in the background. Call
Read after HotLoad if you need the
payload right away |
| Source gains ReadBulk | Add ReadBulk to custom
Source implementations |
| MetricsRecorder gains methods | Add RecordUnflushedExpiry
and the four L1 hooks to custom recorders; alert on any non-zero unflushed-expiry count
|
| ErrMissingContract renamed | It is now ErrMissingWriteContract;
update errors.Is checks |
| Build() validates less | It 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 writes | Retry ErrDegradedWriteUnsafe,
including during a full Redis outage, and don't ack it upstream |
| KeyTTL semantics | It 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 moved | Now 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
Reconcilejob that finds and repairs keys whose datastore state is behind what was acknowledged, for example after losing Redis. By default it never affectsWrite's result. - Strict mode (RFP #19, proposed): payment-grade namespaces with durable
acknowledgement (
WAIT/WAITAOFor 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