KatInterview

Designing a Batched Stream Aggregator with Exactly-Once DB Writes

System DesignModel answer
HardModel answerSystem Designkafkastream-processingexactly-once

Last 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

  1. Per-key ordering. Events for one ticker_id must be handled in the same order they were written to their partition.
  2. Flush policy. A batch is processed when it reaches 1,000 records or when 5 seconds have passed, whichever happens first.
  3. Slow-database tolerance. If the database slows down, the consumer must not crash, get evicted from its group, or drop data.
  4. Recovery. If a worker dies, another worker must resume from the last durably recorded position.
  5. 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?