Stream processing with exactly-once
A stream processor runs one query forever: count events per key per minute. Tasks fail, workers are added, data arrives late. The results must still count each event once.
- 1Partition by key. One task owns all state of a key, and state is saved per key group so it can move.
- 2Barriers flow with the records. Each task saves its state when a barrier has come in on every input, so offsets and state describe one cut.
- 3Recovery restores the last complete checkpoint and replays. Output is exactly once only if the sink commits with the checkpoint or overwrites by key.
- 4Bounded buffers slow the sources when a task falls behind. A hot key limits what more tasks can do.
"Design a stream processor that aggregates events by key over windows, with results that stay exactly-once after failures."
| question | answer assumed |
|---|---|
| How many events? | 300,000 a second on average, 1,000,000 at peak. |
| How many keys? | 1,000,000 active in any minute. |
| Which windows? | Tumbling, 1 minute, by event time. |
| Where do results go? | A table that dashboards read. |
| What is exactly once? | Each event counts once in the table after any failure. |
| Failures? | Any task or worker can die at any time. |
| Task speed? | 50,000 events a second per task, from a benchmark of the job. |
I confirm the rate, the number of keys, the window and what exactly once must mean for the output.
| functional |
|---|
| Run a graph of keyed operators over a partitioned log. |
| Count per key per window; roll up per window. |
| Recover from a failure without losing or doubling a result. |
| Change the parallelism without losing state. |
| non-functional | target |
|---|---|
| Window end to result in the table | p99 < 15 s |
| Results lost or doubled | 0 |
| Back to live after a task failure | < 2 min |
| Checkpoint interval | 10 s |
I promise exactly once in the output table, not exactly-once delivery inside the job. Inside, a replay reads some events twice.
| quantity | arithmetic | result |
|---|---|---|
| Tasks | 1,000,000/s ÷ 50,000/s per task = 20 | 32, for headroom; 64 log partitions |
| Key groups | the default floor of 128 | 4 per task; rescale up to 128 tasks |
| Keyed state | 1,000,000 keys × 2 open windows × 64 B | 128 MB; 4 MB per task |
| Output rows | 1,000,000 rows a minute ÷ 60 | ≈ 17,000/s; 2 sink connections at 14,000/s each |
| Replay after a crash | 10 s interval × 1,000,000/s | up to 10 M events read again |
| Catch-up | (30 s down + 10 s) × 1,000,000/s ÷ (32 × 50,000 − 1,000,000)/s spare | ≈ 67 s |
Inputs are the answers in panel A. Sink speed measured in the lab at 1,000 rows per commit. The 128-group floor is the documented default of one stream processor. Method: R2.
At 1,000,000 events a second and 50,000 per task, I run 32 tasks. After a crash the job catches up in about 67 s with that headroom.
| call | for | success | errors |
|---|---|---|---|
| POST /v1/jobs {graph, parallelism} | deploy | 201 + job_id | 400 bad graph |
| POST /v1/jobs/{id}/savepoints | a checkpoint to keep | 202 + savepoint_id | 409 one running |
| POST /v1/jobs/{id}/rescale {parallelism} | stop with a savepoint, start wider | 202 | 400 above max |
| GET /v1/jobs/{id}/checkpoints | size, duration, last complete | 200 | 404 |
| DELETE /v1/jobs/{id}?savepoint=true | stop safely | 202 + savepoint_id | 404 |
job page_counts:
source events, partitions 64, event time from the record
key by page1
window tumbling 1 minute; count
key by window2
rollup per window: total and per page
sink output table, exactly once3
checkpoint every 10 s; max parallelism 1284- 1A shuffle: every record goes to the task that owns its page.
- 2A second shuffle, so one task sums each window over all pages.
- 3The sink commits with each checkpoint. Panel J shows the other choices.
- 4The number of key groups. It is fixed for the life of the state.
The job is a graph declared in code. The control calls deploy it, take savepoints and change the parallelism from a savepoint.
| store | key | holds |
|---|---|---|
| State backend | key group, page, window | The count and the count last sent |
| State backend | key group, window, page | The rollup: each page's count and the total |
| Checkpoints | checkpoint, operator, task | Offsets, watermarks, state files per key group |
-- The output of the keyed job: one row per key per window, read by a dashboard. A row keyed
-- "total" holds the window's total. The commits table holds the last checkpoint each job
-- committed, in the same transaction as its rows.
CREATE TABLE graph_out (
job text NOT NULL,
key text NOT NULL,
window_start int NOT NULL,
n int NOT NULL,
PRIMARY KEY (job, key, window_start)1
);
CREATE TABLE graph_commits (
job text PRIMARY KEY,
checkpoint int NOT NULL2
);- 1One row per key per window, so a result can be written again by key.
- 2Commits with the rows. After a restore it says which checkpoint the table already holds.
State is keyed by key group, key and window. The output table has one row per window and key, and a row that records the last committed checkpoint.
Step 1: Submit
- The coordinator turns the job into tasks: one per operator per parallel slot.
- It places tasks on workers and connects every keyed exchange all to all.
- With no checkpoint, sources start at the offsets the job names.
If it fails
A worker is missing: the coordinator waits for slots, or starts at a lower parallelism from the last checkpoint.
Sources read partitions, keyed tasks hold state, barriers cut a consistent checkpoint, and the sink commits when the checkpoint completes. Recovery and rescaling both start from a checkpoint.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Flink | keyBy, key groups, max parallelism | One owner per key; state that splits by group. Max parallelism has a floor of 128 by default. | Joins, sessions |
| Flink | State backends: heap or embedded RocksDB, incremental checkpoints | State larger than memory; checkpoints upload only changed files. | Large joins |
| Flink | Aligned and unaligned checkpoints | A consistent cut while the job runs. Unaligned ones pass full buffers. Checkpoints are off by default. | Savepoints |
| Flink | Two-phase-commit sinks | Output commits only when the checkpoint completes. | Files, Kafka, databases |
| Flink | Credit-based flow control, buffer debloating | Bounded buffers between tasks; a slow task slows its senders. | Any pipeline |
| Kafka | Offsets, retention | Restore seeks back to the saved offsets and reads again. | Backfills |
| Kafka | Transactions; consumers with isolation.level = read_committed | Output to a topic appears to readers only at the commit. The default level reads uncommitted data. | Read-process-write |
| Kafka Streams | State stores with changelog topics, standby replicas | State restored from a topic; a standby shortens the restore. Standbys are 0 by default. | Microservice aggregates |
| Postgres | A transaction over rows and a checkpoint marker | The lab's sink: rows and the checkpoint ID commit together. | Outbox, ledgers |
| Postgres | INSERT ... ON CONFLICT DO UPDATE | An idempotent sink: a replayed result writes the same value. | Upserts |
Flink gives me keyed state in key groups, barrier checkpoints and two-phase-commit sinks. Kafka gives me offsets to replay and transactions for output.
| method | status | why |
|---|---|---|
| Commit offsets, state in memory only | Not approved | A crash loses or repeats counts (B7). |
| Stop the world, save, resume | Small jobs only | Every task pauses on every checkpoint. |
| Aligned barriers | Approved | A consistent cut while records flow. |
| Unaligned barriers | Under backpressure | Fast, but in-flight records join the checkpoint. |
| Commit after every record | Not approved | 2,800 results a second in the lab, against 14,000 in batches of 1,000. |
- This is the Chandy-Lamport snapshot, applied to a graph with no cycles: the barrier is the marker.
- Saving a part is quick: the task copies a reference, and uploads in the background.
- A source's part is its offset and watermark, so the cut also says where to read again.
on item x from input i:
IF x is barrier n:
hold input i // its later records wait here1
IF every input has brought barrier n:
flush buffers; save keyed state as part n2
send barrier n on every output3
release every input; report part n saved
ELSE IF input i is not held: process x
coordinator, every INTERVAL:
inject barrier n into each source, which saves its offset4
when every part n is saved: checkpoint n is complete5- 1Records after the barrier belong to the next checkpoint. Processing them now would put them in this one.
- 2Anything buffered outside keyed state is sent first, so the saved part is complete.
- 3Downstream tasks align on it the same way.
- 4The source part. A restore seeks back here.
- 5Only now may sinks commit the output that came before barrier n.
Tested source Go: align and save
// alignID runs when barrier id has arrived on every input: save state, pass the barrier on.
func (r *Runner) alignID(ctx context.Context, c *Ctx, id int) error {
t := c.t
for j := range t.in.blocked {
t.in.blocked[j] = false
}
if t == r.sink {
if err := r.cfg.Sink.PreCommit(ctx, id); err != nil {
return fmt.Errorf("sink pre-commit %d: %w", id, err)
}
r.log("sink", fmt.Sprintf("barrier %d on every input: output since barrier %d staged, not committed", id, id-1), "save")
return r.ack(ctx, id)
}
t.op.Flush(c)
snap := r.partial[id]
if snap == nil {
return fmt.Errorf("barrier %d has no checkpoint", id)
}
n := 0
for g, m := range t.state.clone() {
snap.State[t.stage][g] = m
n += len(m)
}
r.broadcast(t.stage+1, t.index, item{kind: kBarrier, id: id})
r.log(t.name, fmt.Sprintf("barrier %d on every input: save %d state values, pass the barrier on", id, n), "save")
return r.ack(ctx, id)
}
Barriers mark a cut in every stream. A task with several inputs holds each input until the barrier arrives on all of them, then saves its state.
This tick
Items move one hop; nothing else happens.
Output table: 0 of 15 rows
| window | key | clicks |
|---|---|---|
| nothing committed yet | ||
Checkpoint 1 completed and its rows committed. The crash came with checkpoint 2 half saved and 1 result not committed; the restore replayed from checkpoint 1 and the table ended equal to a batch count.
| sink | tasks | replayed | clicks shown | status |
|---|---|---|---|---|
| add | 2 | 55 | 652 of 600 | 12 rows wrong |
| overwrite | 2 | 55 | 600 of 600 | Approved |
| two-phase commit | 2 | 55 | 600 of 600 | Approved |
| add | 4 | 67 | 652 of 600 | 12 rows wrong |
| overwrite | 4 | 67 | 600 of 600 | Approved |
| two-phase commit | 4 | 67 | 600 of 600 | Approved |
- Each run read 600 events from 4 partitions and crashed after the sink had received 12 results past the last checkpoint.
- Overwrite needs results that are absolute counts by key. Readers can see a count step back during the replay.
- Two-phase commit delays output by up to one interval. Its transaction must outlive the interval plus a recovery.
write(r): add r to the open set // not visible yet1
on barrier n: close the open set as part of n // phase 12
on complete n: BEGIN
write every row of n
mark (job, n) as committed3
COMMIT // phase 2
on restore: drop what no complete checkpoint covers4- 1Readers see nothing of this checkpoint until phase 2.
- 2The barrier splits the output: rows before it belong to checkpoint n.
- 3In the same transaction as the rows. A restore can tell which checkpoints the table holds.
- 4The replay produces those rows again.
Tested source Go: the sink · SQL: add, overwrite, mark
// Write sends a result. The two direct modes write at once; two-phase commit holds it.
func (s *PGSink) Write(ctx context.Context, r Rec) error {
switch s.Mode {
case SinkAdd:
return s.exec(ctx, gq["add"], r.Key, r.At, r.D)
case SinkPut:
return s.exec(ctx, gq["put"], r.Key, r.At, r.N)
case SinkTx:
s.open = append(s.open, r)
return nil
}
return fmt.Errorf("unknown sink mode %q", s.Mode)
}
// PreCommit is phase 1: the barrier reached the sink, so every result before it belongs to
// checkpoint id.
func (s *PGSink) PreCommit(_ context.Context, id int) error {
if s.Mode == SinkTx {
if s.staged == nil {
s.staged = map[int][]Rec{}
}
s.staged[id], s.open = s.open, nil
}
return nil
}
// Commit is phase 2: checkpoint id is complete, so its results commit in one transaction with
// the checkpoint id.
func (s *PGSink) Commit(ctx context.Context, id int) error {
if s.Mode != SinkTx {
return nil
}
var rows []Rec
for _, k := range slices.Sorted(maps.Keys(s.staged)) {
if k <= id {
rows = append(rows, s.staged[k]...)
delete(s.staged, k)
}
}
return s.commit(ctx, id, rows)
}
// Abort runs on a restore: results that no complete checkpoint covers are thrown away. The
// replay from the checkpoint's offsets produces them again.
func (s *PGSink) Abort(context.Context) error {
s.open, s.staged = nil, nil
return nil
}
-- At least once: add the change. A replayed result adds again.
INSERT INTO graph_out (job, key, window_start, n) VALUES ($1, $2, $3, $4)
ON CONFLICT (job, key, window_start) DO UPDATE SET n = graph_out.n + EXCLUDED.n;
-- Idempotent: write the absolute count. A replayed result writes the same value.
INSERT INTO graph_out (job, key, window_start, n) VALUES ($1, $2, $3, $4)
ON CONFLICT (job, key, window_start) DO UPDATE SET n = EXCLUDED.n;
-- Two-phase commit, phase 2: the rows of a checkpoint and its id commit together.
INSERT INTO graph_commits (job, checkpoint) VALUES ($1, $2)
ON CONFLICT (job) DO UPDATE SET checkpoint = EXCLUDED.checkpoint;With the same crash, a sink that adds showed 652 clicks for 600. A sink that overwrites by key, or commits with the checkpoint, showed exactly 600.
| method | status | why |
|---|---|---|
| hash(key) mod tasks, state per task | Not approved | A new task count rehashes every key; state must be split key by key. |
| Key groups, a range per task | Approved | Whole groups move; each task reads a few files. |
| Consistent hashing of keys to tasks | State moved key by key | Few keys move, but each must be found and copied. |
key_group(key) = hash(key) mod MAX_PARALLELISM1
task(group, p) = group * p / MAX_PARALLELISM // a range per task2
restore(checkpoint c, parallelism p):
each source seeks to c.offset and resends c.watermark3
FOR EACH task t of p:
load every key group g with task(g, p) = t // whole groups4
each sink drops output that c does not cover
run: records after c.offset are read again- 1Fixed for the life of the job. Choose it larger than any parallelism you will need.
- 2At 2 tasks: groups 0 to 3 and 4 to 7. At 4 tasks: two groups each.
- 3A replayed late record is judged against the same watermark as before the crash.
- 4The lab moved 15 saved values this way; every count stayed the same.
Tested source Go: key groups · Go: restore
// KeyGroup returns the key group of a key.
func KeyGroup(key string) int {
h := fnv.New32a()
h.Write([]byte(key)) // hash.Hash.Write never returns an error
return int(h.Sum32() % MaxParallelism)
}
// TaskOf returns the task that owns a key group: each task owns one contiguous range of groups.
func TaskOf(group, parallelism int) int { return group * parallelism / MaxParallelism }
// Restore starts a job from a complete checkpoint. The stage parallelism in cfg may differ from
// the job that took the checkpoint: each task loads the key groups it owns now. The sink drops
// output that no complete checkpoint covers.
func Restore(ctx context.Context, cfg GraphConfig, s *Snapshot) (*Runner, error) {
if s == nil {
return nil, errors.New("restore: no complete checkpoint")
}
if err := cfg.Sink.Abort(ctx); err != nil {
return nil, fmt.Errorf("restore: abort the sink: %w", err)
}
return start(cfg, s)
}
func start(cfg GraphConfig, s *Snapshot) (*Runner, error) {
if len(cfg.Log) == 0 || len(cfg.Stages) == 0 || cfg.Sink == nil || cfg.Cap < 1 || cfg.WMEvery < 1 {
return nil, fmt.Errorf("bad job config: %d partitions, %d stages, cap %d, watermark every %d", len(cfg.Log), len(cfg.Stages), cfg.Cap, cfg.WMEvery)
}
if cfg.Rate == 0 {
cfg.Rate = 1
}
r := &Runner{cfg: cfg, pending: map[int]int{}, partial: map[int]*Snapshot{}, Counters: map[string]int{}, nextID: 1}
for i := range cfg.Log {
src := &source{index: i, maxSeen: math.MinInt, wm: math.MinInt}
if s != nil {
src.off, src.maxSeen, src.wm = s.Offsets[i], s.MaxSeen[i], s.WM[i]
}
r.sources = append(r.sources, src)
}
inputsOf := len(cfg.Log)
for si, st := range cfg.Stages {
if st.Parallelism < 1 || st.Parallelism > MaxParallelism {
return nil, fmt.Errorf("stage %s: parallelism %d, want 1 to %d", st.Name, st.Parallelism, MaxParallelism)
}
var tasks []*task
for ti := range st.Parallelism {
t := &task{name: fmt.Sprintf("%s%d", st.Name, ti), stage: si, index: ti, op: st.New(), state: keyed{}, in: newInputs(inputsOf), wm: math.MinInt}
if s != nil {
for g, m := range s.State[si] {
if TaskOf(g, st.Parallelism) == ti {
t.state[g] = maps.Clone(m)
}
}
}
tasks = append(tasks, t)
}
r.stages = append(r.stages, tasks)
inputsOf = st.Parallelism
}
r.sink = &task{name: "sink", stage: len(cfg.Stages), in: newInputs(inputsOf), wm: math.MinInt}
if s != nil {
r.nextID = s.ID + 1
r.latest = s
// Each source sends its saved watermark before any record, so a replayed record is
// judged late or on time against the same watermark as before the crash.
for _, src := range r.sources {
if src.wm != math.MinInt {
r.broadcast(0, src.index, item{kind: kWM, wm: src.wm})
}
}
}
return r, nil
}
To rescale, I take a savepoint and restart at the new parallelism. Each task loads a range of key groups: 9 of 12 keys moved, and the output matched.
| tasks per stage | ticks | source ticks stalled | busiest task |
|---|---|---|---|
| 1 | 903 | 2,846 | 600 of 600 |
| 2 | 660 | 1,823 | 417 of 600 |
| 4 | 547 | 1,311 | 329 of 600 |
- Each task moves one item a tick, and a channel holds 4. A full channel stops its sender, back to the sources.
- Fix skew with partial counts per task before the shuffle (C15), or salt the hot key.
- Watch buffer use and checkpoint duration. Rising alignment time means backpressure.
More tasks helped less each time: one page is hot, and at 4 tasks one task got 55% of the records. A job runs at the speed of its busiest task.
| case | what to do |
|---|---|
| Watermark of a task | The smallest watermark of its inputs. |
| A partition goes quiet | Mark it idle after a timeout, so it does not hold the watermark. |
| A record behind the watermark | Update the window within the allowed lateness; else a side output. |
| A restore | Resend the saved watermark before the replay. |
| A rescale | Watermarks restart from the savepoint; windows stay in keyed state. |
Windows, delay and lateness, with a recorded run: B7.
Each task's watermark is the smallest of its inputs. A quiet partition holds every window back, so I mark idle sources.
| event | result | why it is safe | saved by |
|---|---|---|---|
| A task dies between checkpoints | The job restarts from the last complete checkpoint. | State, offsets and committed output all describe that checkpoint. | Checkpoint |
| A crash with a checkpoint half saved | That checkpoint is dropped. | Only complete checkpoints are restored; the sink never committed its rows. | Two-phase commit |
| The sink adds per result | 652 clicks shown for 600. | Not safe. Overwrite by key, or commit with the checkpoint. | Upsert |
| A transaction times out before its checkpoint completes | The broker aborts it. | Not safe: that output is lost. Set the timeout above interval plus recovery. | Timeout |
| A checkpoint takes longer than the interval | Checkpoints queue or fail. | The job keeps running; replays grow. Find the backpressure, or use unaligned checkpoints. | Unaligned |
| A worker is lost for good | Its tasks have nowhere to run. | Restore from the checkpoint at a lower parallelism; key groups spread over fewer tasks. | Key groups |
| One key gets most events | One task falls behind; sources stall. | Pre-aggregate per task, then combine. | Two-phase sum |
| The checkpoint store is down | Checkpoints fail. | The job runs on; a crash now replays from an older checkpoint. Alert on checkpoint age. | Alert |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | One consumer: counts in memory, saved with the offset in one transaction (B7). | About 14,000 results a second at 1,000 per commit, in the lab. | One process cannot keep up, or its state outgrows memory. |
| 2 | Partitions and keyed tasks, each with its own state. | Rate grows with tasks until one key dominates. The keyed logic ran 460,000 records a second here. | A crash in one task corrupts the others' view of progress. |
| 3 | Barrier checkpoints and a two-phase-commit sink. | Exactly-once output after any failure; replay up to one interval. | State no longer fits in memory, or checkpoints take too long to copy. |
| 4 | State on local disk with incremental checkpoints. | State far larger than memory; each checkpoint uploads changed files only. | Restores take minutes; checkpoints stall under backpressure. |
| 5 | Standby state and unaligned checkpoints. | Fast failover; checkpoints that pass full buffers. | Top of the ladder. |
Demand from panel C. Rates measured with one client on one 8-core laptop, Postgres 16, median of 3 runs; read them as orders of magnitude. The job logic number is the lab's engine on one goroutine, with no network and no serialization.
I start with one consumer and a transactional sink. When state or rate outgrows it, I move to a stream processor with keyed state and barrier checkpoints, then add standby state and unaligned checkpoints.
| question | answer | deeper |
|---|---|---|
| How do windows decide they are complete? | A watermark trails the newest event time; a window fires when the watermark passes its end. Late records update it within a bound. | B7 |
| How do you choose the number of partitions? | At least the largest parallelism you plan, since a partition is read by one task. More partitions later move keys. | B6 |
| Show it on a real prompt. | Ad clicks: a seen set per user, partial counts for the hot ad, and a batch recount that makes counts final. | C15 |
| The output feeds payments. Is this enough? | Write each result once with an idempotency key into a ledger, and reconcile against the source. | T9 |
| How is a two-phase commit here different from 2PC across services? | The coordinator and all participants are one job, and a participant never votes no after it pre-commits. Across services, a participant can refuse. | T7 |
| A key is far hotter than the rest. | Split the work with partial counts per task, or salt the key and sum the parts. | X2 |
| What do you alert on? | Consumer lag in seconds, checkpoint duration and age, alignment time, and restarts per hour. | O3 |
0 of 10 known
Why route keys through key groups, and not straight to hash(key) mod tasks?
A task has two inputs. Barrier 3 arrives on one. What does the task do?
The job crashes between checkpoints. What is read again?
The sink adds each result to a counter. What does a crash do?
An overwriting sink and a two-phase-commit sink both ended right. What differs?
Doubling the tasks from 2 to 4 did not halve the run time. Why?
Why do aligned checkpoints get slow under backpressure?
How long should the checkpoint interval be?
The output is a Kafka topic with transactions. What timeout matters?
After a restore, why must the sources resend their saved watermark?
- replay
- Up to one checkpoint interval: 55 of 600 records in the lab run.
- sinks
- Adding: 652 shown for 600. Overwrite or commit: exactly 600.
- commits
- 2,800 results a second at 1 per commit; 14,000 at 1,000.
- rescale
- 2 to 4 tasks: 9 of 12 keys moved; 0 rows wrong.
- skew
- One task got 55% of records at 4 tasks.
- key groups
- Max parallelism has a floor of 128 by default, and is fixed once state exists.
- defaults
- Checkpoints off; Kafka readers see uncommitted data; Kafka Streams has 0 standbys.
Lab engine on one goroutine and Postgres 16 on an 8-core laptop, median of 3 runs. Defaults from the Flink and Kafka documentation.