Designing a Batched Stream Aggregator with Exactly-Once DB Writes
System DesignModel answerLast updated
Design a Kafka consumer pipeline that batches trade events, preserves per-key order, survives crashes and slow databases, and never double-writes aggregates.
Context
A trading platform publishes trade events to a Kafka topic. You need to build a service that reads these events, computes risk aggregates per ticker over 1-minute windows, and stores the results in a relational database.
Requirements
- Per-key ordering. Events for one
ticker_idmust be handled in the same order they were written to their partition. - Flush policy. A batch is processed when it reaches 1,000 records or when 5 seconds have passed, whichever happens first.
- Slow-database tolerance. If the database slows down, the consumer must not crash, get evicted from its group, or drop data.
- Recovery. If a worker dies, another worker must resume from the last durably recorded position.
- No duplicate aggregates. Even with crashes and restarts, a trade must never be counted twice in the stored results.
Load assumptions
- 50,000 events per second in total.
- 20 partitions.
- Database write latency varies between 10 ms and 500 ms.
What to deliver
Explain how Kafka works in a few sentences, then present a design that covers:
- Consumer group setup: keying, partition assignment and rebalancing behavior.
- The in-memory buffering and windowing approach.
- How database transactions and offset tracking are coordinated.
- How the system applies backpressure when database throughput falls.
Back your design with quick capacity numbers, and call out the trade-offs and failure cases you considered.
Hints
Hint 1
Compute events per partition per second, and compare it with how many records one partition can flush per second if each database transaction takes 500 ms and handles a fixed 1,000 records.
Hint 2
Kafka's own exactly-once support covers Kafka-to-Kafka pipelines. For a database sink, ask where the consumer position should live so that results and position change atomically.
Hint 3
Do not stop calling poll() when the database is slow. Look at pausing and resuming individual partitions, bounded buffers, and letting the batch size grow when latency rises.
Hint 4
Think about a stale consumer that lost its partition during a long pause but still tries to commit. How can the database reject its write?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Kafka in brief
Kafka is a replicated, append-only log. A topic is split into partitions, and each record in a partition has a sequential offset. Producers pick a partition by hashing the record key. Within a consumer group, each partition is owned by exactly one consumer at a time. Ordering is guaranteed only inside a partition, so the design hinges on keying by ticker_id and processing each partition sequentially.
2. Capacity numbers
- Per partition: 50,000 / 20 = 2,500 events/s. A 1,000-record batch fills in about 400 ms, so the count trigger dominates and the 5 s timer matters only for quiet partitions.
- At roughly 200 B per event, ingest is about 10 MB/s, which is trivial for Kafka.
- The key issue is the database. With one in-flight transaction per partition and 500 ms latency, a partition can flush 2 batches/s, or 2,000 records/s. That is below 2,500/s, so fixed 1,000-record batches will fall behind in the worst case. Batch size must adapt.
- A 24-hour replay is about 4.3 billion events, so catch-up speed matters and larger batches help.
3. Architecture
Producers (key = ticker_id, acks=all, idempotent)
-> topic "trades": 20 partitions, RF=3, min.insync.replicas=2
-> consumer group (e.g. 5 pods x 4 partitions)
poll loop -> bounded per-partition buffer -> per-partition worker
worker: fold into deltas -> ONE DB transaction (aggregates + offset)
-> relational database
Ordering. Keying by ticker puts all of a ticker's trades in one partition. One sequential worker per partition keeps that order. Scale comes from the 20 partitions, not from threads within a partition.
Consumer settings.
enable.auto.commit=false, since progress is stored in the database.max.poll.recordsaround 1,000-2,000.max.poll.interval.mscomfortably above the worst realistic flush time.isolation.level=read_committedif producers use transactions.
Rebalancing. Use the cooperative sticky assignor so a rebalance moves only the affected partitions. Use static membership (group.instance.id) with a session timeout that tolerates a rolling restart, which avoids rebalance storms.
4. Buffering and windowing
Separate two ideas:
- Window: the logical 1-minute bucket keyed by
(ticker_id, minute(event_time)). - Flush trigger: 1,000 records or 5 s, per partition.
On flush, the worker folds buffered trades into deltas per (ticker, window_start). A 1,000-trade batch often collapses to a few dozen rows. These are applied with an additive upsert:
INSERT INTO risk_aggregates (ticker_id, window_start, net_qty, gross_notional, trade_count)
VALUES (...)
ON CONFLICT (ticker_id, window_start)
DO UPDATE SET net_qty = risk_aggregates.net_qty + EXCLUDED.net_qty,
gross_notional = risk_aggregates.gross_notional + EXCLUDED.gross_notional,
trade_count = risk_aggregates.trade_count + EXCLUDED.trade_count;
Additive upserts are not idempotent on their own. They are safe only because of the atomic offset commit below.
Late data. Keep a per-partition watermark: max event time seen minus an allowed lateness (say 10 s). Once the watermark passes a window, mark it final. Later arrivals go to a corrections path instead of silently changing closed windows.
5. Exactly-once into the database
Kafka transactions do not extend to an external database, so make the database the owner of consumer positions:
BEGIN;
-- apply aggregate deltas
UPDATE consumer_offsets
SET next_offset = :last + 1, generation = :gen
WHERE group_id = :g AND topic = :t AND partition = :p
AND generation <= :gen;
-- if 0 rows updated: ROLLBACK
COMMIT;
On partition assignment, read next_offset from the table and seek() to it.
Why it works. Results and position commit together or not at all, so stored state always equals "every record before next_offset, applied exactly once."
- Crash before commit: nothing persisted, the next owner replays from the old offset.
- Crash after commit: the next owner seeks past the applied records.
Zombie fencing. A consumer stalled by a GC pause may have lost its partition. Increment generation on each assignment; the stale owner's update then matches 0 rows and its transaction aborts. On revocation, discard the uncommitted buffer, since it will be replayed.
Alternatives and why they are weaker.
- Commit to Kafka before the write: at-most-once, data loss on crash.
- Commit to Kafka after the write: at-least-once, double counting on crash.
- Idempotent writes keyed by
(partition, offset range), or recomputing whole windows from raw events, also work but are more complex than storing offsets transactionally.
6. Backpressure
Goal: slow intake without ever leaving the poll loop, because exceeding max.poll.interval.ms gets the consumer evicted and triggers a rebalance.
while running:
records = consumer.poll(timeout_ms=100) # always keep polling
for tp, recs in records.items():
buffers[tp].extend(recs)
if len(buffers[tp]) >= HIGH:
consumer.pause([tp])
for tp in consumer.paused():
if len(buffers[tp]) <= LOW:
consumer.resume([tp])
dispatch_ready_batches(buffers)
- Bounded per-partition buffers with high and low watermarks cap memory.
- Pausing a partition stops fetches for it while heartbeats and polls continue; unfetched data safely stays in Kafka.
- Adaptive batch size: when the previous transaction is slow, let the next batch grow (for example up to 5,000 records). Because deltas compress, a larger batch costs little extra write volume and amortizes the 500 ms round trip. At 5,000 records per flush and 2 flushes/s, a partition can sustain 10,000 records/s, comfortably above 2,500/s.
- Cap in-flight transactions per partition at one to preserve order, and bound total database connections across workers with a pool.
- Use timeouts and bounded retries with backoff on the write; if the database is down, keep partitions paused and alert on consumer lag rather than dropping data.
7. Failure scenarios
| Failure | Behavior |
|---|---|
| Worker crash mid-batch | Uncommitted work lost, replay from stored offset |
| Crash right after commit | New owner seeks to stored next_offset, no duplicates |
| Rebalance during flush | Generation check aborts stale transaction |
| Database slowdown | Pause partitions, grow batches, lag rises but no loss |
| Poison record | Route to a dead-letter topic after bounded retries, then advance past it |
8. Common mistakes
- Assuming Kafka's exactly-once covers database sinks.
- Blocking the poll thread on the database call.
- Using threads within a partition and breaking ordering.
- Using processing time for windows without stating it.
- Committing offsets to Kafka and the database separately.
- Ignoring zombie consumers after a rebalance.
9. Monitoring
Track consumer lag per partition, flush latency percentiles, batch size, paused-partition count, transaction abort rate from fencing, and watermark delay.