Kafka Architecture and Exactly-Once Batched Trade Aggregation

Hard · System Design · Software Engineer · Onsite

Prompt

Design a post-trade risk aggregation pipeline that reads execution events from a high-throughput Apache Kafka topic, computes bulk risk exposure summaries over 1-minute windows, and stores the aggregated rows in a downstream database.

Core requirements:

  1. Per-symbol ordering: Every execution sharing a ticker_id must be processed strictly in the sequence it sits inside its Kafka partition.
  2. Dual-trigger micro-batching: Flush accumulated calculations whenever a partition reaches 1,000 records or 5 seconds elapse, whichever condition triggers first.
  3. Downstream backpressure: Absorb database slowdowns cleanly without crashing consumer instances, running out of memory, or dropping events.
  4. Crash recovery: When a worker node terminates unexpectedly, resume processing cleanly from the last durably committed offset.
  5. Exactly-once aggregation: Guarantee that persisted trade summaries never double-apply records across worker crashes, network timeouts, or partition reassignments.

Illustrative batching and failover trace:

Suppose Partition 7 carries "NVDA" (BUY 40 @ 135.00 at offset 50, SELL 15 @ 136.50 at offset 52) and "SPY" (BUY 30 @ 580.00 at offset 51) inside the 14:05 minute bucket: folding in exact offset order yields "NVDA" net_qty = +25 and last_price = 136.50, commits alongside next_offset = 53, and if the worker crashes after reading offset 53 into memory, the replacement worker resumes from offset 53 without dropping or double-counting any trade.

Scale & latency constraints:

  • Event rate: 50,000 trade events per second distributed across 20 Kafka partitions.
  • Database write latency: Varies between 10 ms and 500 ms.

Scope & Expectations

  • Explain the core Kafka primitives your design relies on and specify the consumer-group, partitioning, and rebalance configuration that preserves per-ticker_id order.
  • Detail the in-memory micro-batching buffer (1,000 records or 5 seconds) and how 1-minute event-time windows fold and close.
  • Define how database transactions and offset checkpoints coordinate to enforce end-to-end exactly-once aggregation.
  • Show how backpressure keeps consumers healthy when database latency stretches from 10 ms to 500 ms or stalls during an outage.

Step-by-step walkthrough

  1. Clarify requirements and state assumptions

    Before sketching boxes, pin down the ambiguities in the specification. Every assumption below directly shapes one part of the architecture.

    • Producer partitioning: Upstream execution venues publish to the trades topic using ticker_id as the partition key (the value hashed to pick which partition stores a record), with Kafka's idempotent producer setting enabled (a built-in sequence-number check so network retries never duplicate or reorder trades inside a partition). If upstream producers sprayed one ticker across random partitions, no consumer design could recover true per-ticker order without introducing a sorting delay.
    • Event payload (~200 bytes): {trade_id, ticker_id, book_id, side, qty, price, event_time} encoded in Protobuf or Avro, using exact decimal representation for price rather than binary floating point.
    • What we aggregate (and why order matters): Per (ticker_id, 1-minute window), we maintain net_qty, gross_notional, trade_count, and last_price (or peak intraday position / realized PnL). Pure sums are order-independent, but fields like last_price and realized cost basis depend on the exact sequence of trades — which is why strict partition-order processing is non-negotiable.
    • Windowing clock: Windows use event time (the timestamp when the trade actually matched, floor(event_time / 60s)), not processing time (when our server happened to read it), so replaying historical records after a crash produces identical 1-minute buckets.
    • Batching rule: Per partition, flush when the open buffer reaches 1,000 records or when 5 seconds have elapsed since the first record entered that buffer (so an idle partition never fires empty database transactions).
    • Sink and freshness: Downstream storage is a transactional relational database (PostgreSQL). When healthy, dashboards see updates within 1–5 seconds; during database slowdowns (up to 500 ms or temporary outages), freshness may lag, but zero trades may be lost or double-counted.
  2. Kafka core concepts in plain English

    Our design relies on a few specific guarantees of Apache Kafka (a distributed, append-only event log). Let's state each term in one plain sentence so every piece of the pipeline is crystal clear:

    Producer --hash(ticker_id) mod 20--> Topic "trades" (20 Partitions)
                                           P0: [offset 0][offset 1][offset 2]...  --> Consumer 1
                                           P1: [offset 0][offset 1]...            --> Consumer 1
                                           ...
                                           P19:[offset 0][offset 1][offset 2]...  --> Consumer 5
    
    • Topic and partition: A topic is a named stream of events split into numbered partitions (here 20); each partition is an ordered, immutable log on disk where every record receives an increasing integer offset (0, 1, 2, ...).
    • Ordering scope: Kafka guarantees strict order within a single partition, never across different partitions. Because hash(ticker_id) mod 20 always sends "NVDA" to the same partition, all "NVDA" trades sit in exact order.
    • Broker, replication factor, and ISR: A broker is a Kafka server; with a replication factor (RF) of 3, each partition has 1 leader broker and 2 follower brokers copying it, and the ISR (In-Sync Replicas) is the subset of replicas completely caught up with the leader.
    • Durable acknowledgement (acks=all): Setting acks=all with min.insync.replicas=2 means the leader only confirms a trade write after at least 2 in-sync brokers hold it, so a single server crash loses zero acknowledged trades.
    • Retention and consumer groups: Kafka keeps records on disk for a configured retention period (say 7 days) even after they are read, allowing replay. A consumer group is a team of worker processes sharing a group.id so that each partition is assigned to at most one active worker at a time; reassigning partitions when workers join or fail is called a rebalance.

    Why delivery guarantees come down to offset timing: - At-most-once (save the next offset first, then write to the database): if the worker crashes before the database write finishes, those records are skipped forever. - At-least-once (write to the database first, then save the next offset): if the worker crashes before saving the offset, the next worker replays the batch and double-counts the trades. - Exactly-once in effect: either make every database write idempotent (repeating the write produces the exact same database state), or save the Kafka offset inside the very same atomic database transaction as the aggregated numbers. Note that Kafka's own transaction API only makes Kafka-to-Kafka pipelines atomic — it cannot roll back an external PostgreSQL table, so putting our offset table inside PostgreSQL is the cleanest path.

  3. Back-of-the-envelope numbers

    Let's verify bandwidth, memory, transaction rates, and where the 500 ms database latency hurts:

    Ingress data rate       50,000 events/s x 200 B = 10 MB/s  (~864 GB/day)
    7-day Kafka retention   864 GB/day x 7 days     = ~6.05 TB logical (~18.1 TB across 3 replicas)
    Per-partition rate      50,000 / 20 partitions  = 2,500 events/s average (up to ~7,500/s if skewed)
    1,000-record trigger    1,000 / 2,500 events/s  = 0.4 s (fires first under normal traffic)
    5-second trigger        fires only when a partition drops below 1,000 / 5 s = 200 events/s
    Healthy DB flush rate   50,000 / 1,000          = 50 transactions/s total (2.5 tx/s per partition)
    Rows per flush          ~10,000 active tickers / 20 partitions = ~500 distinct tickers per partition
                            -> each flush upserts ~300-500 summary rows (up to ~1,000 across a minute edge)
    Daily DB table growth   10,000 tickers x 1,440 minutes/day = 14.4M rows/day (~1.5 GB/day with indexes)
    

    Why 500 ms database latency breaks naive fixed batching: To preserve per-ticker order (such as last_price), one partition can only have one database transaction in flight at a time. Look at what happens when latency jumps from 10 ms to 500 ms:

    DB latency = 10 ms   -> max 100 sequential tx/s per partition -> 2.5 tx/s needed -> plenty of headroom
    DB latency = 500 ms  -> max   2 sequential tx/s per partition -> if capped at 1,000 records/tx,
                            max throughput = 2 x 1,000 = 2,000 records/s < 2,500 arriving!
                            The partition falls behind by 500 records every single second.
    

    That simple calculation reveals a critical design requirement: while one transaction is waiting on a slow database, newly arriving records must keep folding into the next in-memory batch (batch coalescing). Even if 5,000 trades fold together during a slowdown, they still collapse into the same ~500 (ticker_id, window) summary rows, so the database query size barely grows while throughput scales right past the latency bottleneck!

  4. API and database data model

    Input trade event (Kafka topic trades, partitioned by ticker_id):

    trade_id      string    globally unique trade identifier (used for auditing and dead-letter logs)
    ticker_id     string    partition key (e.g., "NVDA")
    book_id       string    trading desk / portfolio identifier
    side          enum      "BUY" | "SELL"
    qty           int64     number of shares
    price         decimal   exact decimal price (never IEEE-754 float, which introduces rounding drift)
    event_time    int64     trade execution timestamp in epoch milliseconds
    

    PostgreSQL schema: We store the risk aggregates and the consumer's partition offsets in the same database so a single BEGIN ... COMMIT updates both atomically:

    CREATE TABLE exposure_1m (
        ticker_id       TEXT        NOT NULL,
        window_start    TIMESTAMPTZ NOT NULL,
        net_qty         BIGINT      NOT NULL,
        gross_notional  NUMERIC     NOT NULL,
        trade_count     BIGINT      NOT NULL,
        last_price      NUMERIC     NOT NULL,
        revision        INT         NOT NULL DEFAULT 0,   -- incremented if a late trade updates a closed window
        is_final        BOOLEAN     NOT NULL DEFAULT FALSE,
        PRIMARY KEY (ticker_id, window_start)
    );
    
    CREATE TABLE consumer_offsets (
        group_id      TEXT    NOT NULL,
        topic         TEXT    NOT NULL,
        partition_id  INT     NOT NULL,
        next_offset   BIGINT  NOT NULL,   -- first Kafka offset NOT yet included in exposure_1m
        owner_epoch   BIGINT  NOT NULL,   -- monotonically increasing fencing token per partition assignment
        PRIMARY KEY (group_id, topic, partition_id)
    );
    

    Single-writer row rule: Because each ticker_id hashes to exactly one partition, no two partitions ever update the same (ticker_id, window_start) row. That eliminates cross-worker row-lock contention and deadlocks. (If we also needed per-book_id totals where one book trades tickers across all 20 partitions, we would key the table by (book_id, window_start, partition_id) so each partition writes its own partial row, and sum the 20 partials at read time.)

    Operational API on each worker: GET /health exposing per-partition lag in records and seconds, paused partitions, and flush latency; plus POST /admin/partitions/{id}/pause|resume for incident response.

  5. High-level architecture

    With 20 partitions, we run 5 consumer instances (4 partitions per instance, ~10,000 events/s per process, leaving room to scale horizontally up to 20 instances). Inside each process, we strictly separate polling Kafka from talking to PostgreSQL:

     Trading Producers (key = ticker_id, acks=all, enable.idempotence=true)
            |
            v
     +--------------------------------------------------------------------+
     | Kafka Topic "trades" (20 partitions, RF=3, min.insync.replicas=2)  |
     +--------------------------------------------------------------------+
            |  consumer group "risk-agg" (5 instances x 4 partitions)
            v
     +-------------------------- Worker Instance -------------------------+
     |                                                                    |
     |  Poll Thread (sole owner of KafkaConsumer; NEVER blocks on DB)     |
     |    1. poll(100 ms) -> fold records into PartitionBuffer[p]         |
     |    2. if >= 1,000 records or >= 5 s (and no DB write in flight):   |
     |         swap open buffer into bounded 1-slot handoff for p         |
     |    3. if PartitionBuffer[p] > 50,000 records -> consumer.pause(p)  |
     |       when drained below 10,000 records      -> consumer.resume(p) |
     |            |                                          ^            |
     |            | sealed batch (or init request)           | completion |
     |            v                                          | queue      |
     |  Writer Thread Pool (at most ONE in-flight DB tx per partition) ---+
     |    BEGIN -> fence & advance consumer_offsets -> upsert exposure_1m |
     +--------------------------------------------------------------------+
            |
            v
     PostgreSQL Primary (exposure_1m + consumer_offsets) ---> Read Replica ---> Risk Dashboards
    

    Why decoupling the poll thread from the database is essential: 1. Kafka requires consumers to call poll() at least once within max.poll.interval.ms (default 5 minutes) to prove the process is not stuck. Because our poll thread only decodes bytes and updates an in-memory dictionary (taking microseconds) and hands batches off through a non-blocking queue (a queue where putting or checking items returns immediately without waiting), it calls poll(100 ms) like clockwork even during a total database outage. 2. Kafka's client object (KafkaConsumer) is not thread-safe. Keeping all poll, pause, resume, and seek calls on the poll thread — while writer threads communicate results back through a thread-safe completion queue — prevents race conditions cleanly.

  6. Deep dive 1: Per-ticker ordering, partitioning, and safe rebalancing

    How per-ticker ordering holds end to end: Order holds because four links form an unbroken chain: 1. Producer hashes ticker_id -> every trade for "NVDA" lands in the same partition p in arrival order. 2. Consumer group assigns partition p to -> at most one active consumer instance. 3. Poll thread folds records of p sequentially -> PartitionBuffer[p] updates last_price and totals in exact offset order. 4. Writer pool allows -> at most one in-flight transaction for p at a time, so batch k always commits before batch k + 1 starts.

    Consumer configuration:

    enable.auto.commit = false                         -- we commit offsets inside PostgreSQL, never on a timer
    auto.offset.reset = none                           -- fail loudly if a stored offset expired past retention
    partition.assignment.strategy = CooperativeStickyAssignor  -- move only revoked partitions; keep others running
    group.instance.id = risk-agg-<hostname>            -- static membership: quick restarts skip rebalancing
    session.timeout.ms = 30000                         -- heartbeat failure detection window (30 s)
    isolation.level = read_committed                   -- ignore any aborted producer transactions
    

    Here, cooperative sticky assignment means a rebalance only pauses the specific partitions moving between hosts instead of stopping all 20 partitions ("stop-the-world"), and static membership gives each host a stable identity so a quick rolling restart reclaims its 4 partitions without triggering reassignments.

    Non-blocking rebalance lifecycle: Even during partition assignment, the poll thread must never block on PostgreSQL:

    1. onPartitionsAssigned(p) [runs on Poll Thread]:
         call consumer.pause([p]) immediately; mark p as INITIALIZING;
         enqueue InitPartition(p) to Writer Pool.
    
    2. Writer Thread executes on PostgreSQL:
         UPDATE consumer_offsets
            SET owner_epoch = owner_epoch + 1
          WHERE group_id = 'risk-agg' AND topic = 'trades' AND partition_id = :p
         RETURNING next_offset, owner_epoch;
         -> posts InitDone(p, next_offset, owner_epoch) to completion queue.
    
    3. Poll Thread drains completion queue on next 100 ms tick:
         stores owner_epoch for p;
         calls consumer.seek(p, next_offset) and consumer.resume([p]).
    
    4. onPartitionsRevoked(p) / onPartitionsLost(p):
         discard p's unflushed in-memory buffer; any late DB write from this old owner
         will automatically be rejected by the new owner's higher owner_epoch!
    

    Notice a huge benefit of storing incremental totals in PostgreSQL: when partition p moves to a new worker, zero in-memory window state needs to migrate. The database already holds all committed trades up to next_offset, so the new worker simply seeks to next_offset and continues adding deltas.

  7. Deep dive 2: The batch buffer and event-time windowing

    Instead of keeping thousands of raw trade objects in RAM, each partition's open buffer folds incoming trades immediately into per-(ticker_id, window_start) deltas:

    from decimal import Decimal
    import time
    
    WINDOW_MS = 60_000
    MAX_RECORDS = 1000
    MAX_WAIT_S = 5.0
    
    
    class WindowDelta:
        """In-memory accumulator for one (ticker_id, 1-minute window) inside an open batch."""
    
        def __init__(self):
            self.net_qty = 0
            self.gross_notional = Decimal("0")
            self.trade_count = 0
            self.last_price = Decimal("0")
    
    
    class PartitionBuffer:
        """Folds ordered trades from one Kafka partition until a batch flush is triggered."""
    
        def __init__(self, start_offset: int):
            self.start_offset = start_offset  # first Kafka offset not yet committed to DB
            self.end_offset = start_offset    # exclusive upper offset bound (last offset + 1)
            self.record_count = 0
            self.opened_at = None             # monotonic clock timestamp of first buffered record
            self.deltas = {}                  # (ticker_id, window_start_ms) -> WindowDelta
    
        def add_trade(self, offset: int, trade: dict) -> None:
            if self.record_count == 0:
                self.opened_at = time.monotonic()
    
            # Bucket by event_time (when the trade happened), not wall-clock arrival time
            window_start = (trade["event_time"] // WINDOW_MS) * WINDOW_MS
            key = (trade["ticker_id"], window_start)
    
            delta = self.deltas.get(key)
            if delta is None:
                delta = WindowDelta()
                self.deltas[key] = delta
    
            qty = trade["qty"]
            price = trade["price"]  # Decimal
            if trade["side"] == "BUY":
                delta.net_qty += qty
            else:
                delta.net_qty -= qty
            delta.gross_notional += qty * price
            delta.trade_count += 1
            # Because records arrive in strict partition order, overwriting keeps the true latest price
            delta.last_price = price
    
            # Use offset + 1 (never start_offset + record_count) because Kafka offsets can have gaps
            self.end_offset = offset + 1
            self.record_count += 1
    
        def should_flush(self, now: float) -> bool:
            if self.record_count == 0:
                return False
            return self.record_count >= MAX_RECORDS or (now - self.opened_at) >= MAX_WAIT_S
    

    Mini-trace of how folding preserves order and bounds memory:

    Incoming on Partition 7 (start_offset = 400):
      offset 400: NVDA BUY  40 @ 135.00 (14:05:02) -> (NVDA, 14:05): net=+40, notional=5400.0,  cnt=1, last=135.00
      offset 401: SPY  BUY  30 @ 580.00 (14:05:03) -> (SPY,  14:05): net=+30, notional=17400.0, cnt=1, last=580.00
      offset 403: NVDA SELL 15 @ 136.50 (14:05:04) -> (NVDA, 14:05): net=+25, notional=7447.5,  cnt=2, last=136.50
      (Note offset 402 was a Kafka control marker -> skipped cleanly; end_offset = 403 + 1 = 404!)
    

    Closing windows and handling late trades: Each partition tracks a watermark (a moving timestamp defined as max(event_time seen) - allowed_lateness, e.g., 10 seconds, representing the point before which we expect no more normal events). Once the watermark passes 14:06:00, the next flush marks 14:05 rows is_final = TRUE. In finance we never silently drop a late trade: if a delayed trade for 14:05 arrives later, the upsert still applies its delta and increments revision so downstream consumers know a finalized minute was amended.

  8. Deep dive 3: Exactly-once writes and multi-layer backpressure

    Part A — Atomic SQL transaction with epoch fencing: When the writer thread flushes a batch covering [start_offset, end_offset), it executes one SQL transaction:

    BEGIN;
    
    -- Step 1: Verify we still own this partition (fencing) AND advance next_offset atomically.
    UPDATE consumer_offsets
       SET next_offset = :end_offset
     WHERE group_id = 'risk-agg'
       AND topic = 'trades'
       AND partition_id = :partition_id
       AND owner_epoch = :my_epoch
       AND next_offset = :start_offset;
    -- If updated_rows == 0: ROLLBACK immediately! Another worker took over this partition.
    
    -- Step 2: Sort keys by (ticker_id, window_start) and upsert all deltas in one multi-row statement.
    INSERT INTO exposure_1m (ticker_id, window_start, net_qty, gross_notional, trade_count, last_price)
    VALUES (:t1, :w1, :q1, :n1, :c1, :p1),
           (:t2, :w2, :q2, :n2, :c2, :p2)
    ON CONFLICT (ticker_id, window_start) DO UPDATE
       SET net_qty        = exposure_1m.net_qty        + EXCLUDED.net_qty,
           gross_notional = exposure_1m.gross_notional + EXCLUDED.gross_notional,
           trade_count    = exposure_1m.trade_count    + EXCLUDED.trade_count,
           last_price     = EXCLUDED.last_price,
           revision       = exposure_1m.revision + CASE WHEN exposure_1m.is_final THEN 1 ELSE 0 END;
    
    COMMIT;
    

    Why this survives every failure mode without duplicates: - Worker crashes before COMMIT: PostgreSQL rolls back both exposure_1m and consumer_offsets. The next worker reads the unchanged next_offset and replays from Kafka cleanly. - Network drops during COMMIT (ambiguous outcome): Before retrying, the writer queries consumer_offsets. If next_offset == end_offset under my_epoch, the transaction already succeeded; if still start_offset, it safely retries the exact same batch. - Zombie worker (long garbage-collection pause): Suppose Worker A freezes for 40 seconds, Kafka reassigns partition p to Worker B (which bumps owner_epoch from 7 to 8), and Worker A wakes up trying to commit its old batch with my_epoch = 7. Step 1 matches 0 rows (owner_epoch is now 8!), so Worker A rolls back harmlessly. Here owner_epoch acts as a fencing token (a monotonically increasing number that locks out stale workers). - Alternative (idempotent full-window writes): If our sink were a NoSQL store without multi-table transactions, we would hold each 1-minute window's complete total in memory and overwrite SET net_qty = :full_total rather than adding deltas (+ EXCLUDED.net_qty), checkpointing offsets after each write. Overwriting the same final total twice is idempotent, at the cost of rebuilding the full minute from Kafka after every rebalance.

    Part B — Three layers of backpressure when the database slows down:

    Layer 1: Batch Coalescing (10 ms -> 500 ms DB latency)
      Tx #1 (1,000 records) is in flight for 500 ms.
      Meanwhile, 1,250 new trades arrive -> Poll Thread folds all 1,250 into ONE open PartitionBuffer.
      Tx #1 finishes -> Tx #2 sends all 1,250 trades (~500 ticker rows) in a single DB round trip!
    
    Layer 2: Pause Kafka Fetching (sustained overload / DB outage)
      Open PartitionBuffer reaches high-water mark (50,000 folded records, ~5 MB RAM).
      Poll Thread calls consumer.pause([p]) -> poll(100 ms) keeps sending heartbeats (zero rebalances!),
      while unread trades wait safely on Kafka's replicated broker disks (7 days of capacity).
      Once DB recovers and buffer drains below 10,000 records -> consumer.resume([p]).
    
    Layer 3: Exponential Backoff + Circuit Breaker (protecting a struggling DB)
      Repeated timeouts open a circuit breaker (pausing all partitions and probing with 1 tx)
      so 20 writer threads do not stampede an overloaded PostgreSQL primary.
    

    Catch-up math after an outage: A 30-minute database outage leaves 1,800 s × 50,000/s = 90M trades sitting safely in Kafka. On recovery, coalescing say 25,000 trades per transaction lets the 5 workers fold ~250,000 trades/s while writing the same ~500 summary rows per partition per flush, draining the 30-minute backlog in 90M / (250k - 50k) = 450 seconds (~7.5 minutes).

  9. Scaling, bottlenecks, and failure handling

    Scaling and bottlenecks: - Consumer parallelism ceiling: Because Kafka assigns at most 1 consumer per partition, 20 partitions cap the group at 20 active worker processes. Never increase partition count in place on a live keyed topic (hash(ticker_id) mod N would remap tickers to new partitions while older trades still sit in old partitions, breaking order!). Provision headroom up front (e.g., 60 partitions) or migrate via a new topic after draining the old one. - Database write throughput: ~15,000–25,000 row upserts/s across 50 multi-row statements/s is well within a tuned PostgreSQL primary when exposure_1m is range-partitioned by day (keeping active B-tree indexes small in RAM and letting old days drop via DROP TABLE instead of VACUUM-heavy DELETEs). - Read isolation: Risk dashboards query a streaming read replica (or a short-TTL cache), never competing with writer transactions on the primary.

    Failure modes and observability: - Worker crash: Detected after session.timeout.ms (30 s); surviving workers bump owner_epoch, seek to next_offset from PostgreSQL, and replay the ~0.4–5 s of unflushed trades. - Broker crash: With RF = 3, min.insync.replicas = 2, and acks = all, another in-sync broker takes leadership with zero data loss. - Key metrics to alert on: Per-partition lag in seconds (now - event_time of oldest uncommitted trade, reported as 0 when caught up), flush latency p50/p99, batch coalescing size (records per transaction), paused-partition count, fenced-commit count, and dead-letter count.

  10. Summary of trade-offs

    • Storing offsets in PostgreSQL vs. in Kafka: Putting consumer_offsets inside the SQL transaction gives true atomic exactly-once semantics with incremental deltas, at the cost of custom seek logic during rebalances. (We still mirror offsets asynchronously to Kafka purely so standard monitoring dashboards can display lag.)
    • Incremental delta upserts vs. final-window overwrites: Incremental deltas expose fresh numbers every 0.4–5 s and require zero state migration on rebalance, whereas final-window overwrites are naturally idempotent without offset transactions but hide intra-minute updates and require replaying the whole window on failover.
    • Batch coalescing vs. rigid 1,000-record caps: Coalescing turns the rule into "flush at 1,000 records when healthy, or all accumulated records once the previous write finishes," allowing a single partition to sustain 2,500+ events/s even at 500 ms database latency.
    • consumer.pause() vs. unbounded in-memory queues: Pausing partitions pushes backpressure onto Kafka's multi-terabyte replicated disks while keeping consumer RAM tiny and poll heartbeats alive; unbounded queues crash workers with out-of-memory errors.
    • Static membership vs. instant crash failover: Static membership (group.instance.id) avoids disruptive rebalances during routine deployments, trading away a 30-second detection wait when a machine genuinely dies.

Intuition & how it works

Think of this system like 20 dedicated bank teller lanes (Kafka partitions, which are ordered, append-only logs on disk) processing deposit and withdrawal slips (trade events). Every slip for the same stock symbol (ticker_id) is always routed to the exact same lane so "NVDA" trades are never processed out of order. Instead of walking to the vault (PostgreSQL) after every single slip, each teller tallies slips on a notepad (an in-memory batch buffer) until hitting 1,000 slips or 5 seconds, and then updates both the vault ledger and a "next slip number" bookmark inside one locked envelope (a single atomic database transaction, meaning either both changes save together or neither saves).

Why does the obvious approach fail? Writing to the database one trade at a time requires 50,000 network round trips per second, which collapses immediately when database latency spikes to 500 ms. Batching in memory and saving Kafka progress separately from the database write either loses trades (if you save progress first and crash) or double-counts trades (if you write to the database first and crash). And waiting on a slow database directly inside the Kafka consumer thread freezes its heartbeat loop, causing Kafka to kick the worker out of the group and trigger a cascading rebalance storm.

Here is a tiny 4-trade trace on Partition 7 showing normal batching, a crash, and exact recovery:

Initial DB state: consumer_offsets(partition=7, next_offset=50, owner_epoch=1), NVDA net_qty=0

1. Poll thread reads offsets 50, 51, 52 and folds them in memory (microseconds, no DB wait):
     offset 50: NVDA BUY  40 @ 135.00 -> buffer[(NVDA, 14:05)]: net=+40, last=135.00
     offset 51: SPY  BUY  30 @ 580.00 -> buffer[(SPY,  14:05)]: net=+30, last=580.00
     offset 52: NVDA SELL 15 @ 136.50 -> buffer[(NVDA, 14:05)]: net=+25, last=136.50

2. Flush triggers -> Writer thread runs ONE SQL transaction:
     UPDATE consumer_offsets SET next_offset = 53 WHERE partition=7 AND owner_epoch=1 AND next_offset=50;
     UPSERT exposure_1m: NVDA=(+25, last=136.50), SPY=(+30, last=580.00);
     COMMIT;  --> DB now atomically reflects offsets [50, 51, 52] and next_offset = 53.

3. Poll thread reads offset 53 (NVDA BUY 10 @ 137.00) into a new buffer, then WORKER CRASHES!

4. Replacement worker is assigned Partition 7:
     Bumps owner_epoch to 2 (blocking any stale writes from Worker 1), reads next_offset = 53,
     calls consumer.seek(7, 53), and processes offset 53 cleanly -> zero lost or doubled trades!

Key trade-offs

  • Offsets in the database transaction vs. Kafka offset commits. Saving next_offset in PostgreSQL inside the same BEGIN ... COMMIT block as exposure_1m guarantees exactly-once semantics (every trade affects the stored totals once and only once) using standard SQL, at the cost of custom seek() logic on startup and rebalance. Committing offsets to Kafka before or after the database write is simpler to wire up, but inevitably gives at-most-once (possible data loss) or at-least-once (possible double-counting) on crashes.
  • Epoch fencing vs. trusting group membership. Checking an owner_epoch (a monotonically increasing fencing token incremented every time a partition changes owner) inside every UPDATE consumer_offsets prevents a frozen "zombie" worker from waking up after a pause and double-applying an old batch, at the cost of one extra integer check per transaction.
  • Incremental delta upserts vs. idempotent full-window overwrites. Adding batch deltas (net_qty + EXCLUDED.net_qty) makes fresh risk numbers visible every 0.4–5 seconds and requires zero in-memory state transfer during rebalances, but relies on the transactional offset check because addition is not idempotent (safe to repeat without changing the result). Holding whole 1-minute windows in memory and overwriting final values is naturally idempotent without offset transactions, but delays visibility or requires replaying the entire minute after every rebalance.
  • Batch coalescing vs. strict 1,000-record batches. With one sequential transaction per partition, 500 ms database latency limits a partition to 2 transactions/s (2,000 records/s at 1,000 records each, below the 2,500 records/s arriving). Coalescing — folding all records that arrive while the previous write is in flight into the next single transaction — lets throughput keep up because 5,000 trades still fold into the same ~500 (ticker_id, window) summary rows.
  • consumer.pause() backpressure vs. in-memory queuing. Calling consumer.pause(partition) when an in-memory buffer crosses a high-water mark uses Kafka's multi-terabyte replicated disks as the shock absorber while keeping poll() heartbeats alive; growing an unbounded in-memory queue crashes workers with out-of-memory errors.
  • Event-time vs. processing-time windows. Bucketing by event time (when the trade matched) guarantees reproducible numbers during replays, whereas processing time (when the consumer read the record) shifts trades into wrong minutes after any outage. The trade-off is tracking a watermark (a progress timestamp behind the newest event time) and bumping a revision counter when late trades arrive.

Common mistakes

  • Leaving enable.auto.commit=true. Kafka's background timer commits read offsets every few seconds regardless of whether PostgreSQL persisted the batch, silently losing data on a crash.
  • Assuming Kafka transactions make external database writes atomic. Kafka's transactional producer/consumer feature only coordinates writes back into Kafka topics; it cannot roll back or commit rows in PostgreSQL.
  • Blocking the poll() thread on slow database queries. If PostgreSQL stalls and delays poll() past max.poll.interval.ms — including inside rebalance callbacks like onPartitionsAssigned — Kafka evicts the worker and triggers repeated rebalances across an already stressed system.
  • Parallelizing one partition across multiple writer threads. Allowing two concurrent transactions on the same partition breaks per-ticker ordering (corrupting fields like last_price) and breaks sequential next_offset checks.
  • Computing end_offset as start_offset + count. Compacted segments or Kafka transaction control markers leave gaps between record offsets; always advance to last_record.offset + 1.
  • Sharing database rows across partitions. Updating a table keyed only by book_id from all 20 partitions causes row-lock waits and deadlocks; keep every database row owned by a single partition (and sum per-partition partials on read if cross-ticker totals are needed).
  • Using binary float for financial notional values. Accumulating millions of IEEE-754 floats introduces cent-level drift; always use Decimal (or integer minor units) in code and NUMERIC in SQL.

Follow-up questions

  • What strategy prevents a malformed or corrupt trade record from trapping a consumer instance in an endless crash-restart loop? Separate transient infrastructure failures (such as database connection timeouts, retried with backoff) from deterministic payload defects (corrupt binary serialization or invalid field values that will never succeed). Whenever a single record fails validation or decoding, publish its raw bytes, partition, offset, and failure reason to a dead-letter queue (DLQ) (a dedicated quarantine Kafka topic trades.dlq), and record the skipped offset in a skipped_records SQL table inside the same atomic transaction that advances next_offset, marking that symbol's minute row incomplete and alerting on-call engineers. If a pathological record crashes the entire JVM/Python process before try/except catches it, persist an attempt counter keyed by (partition, next_offset) in PostgreSQL so that after 3 consecutive crashes at the same next_offset, the worker switches to single-record stepping mode to isolate, quarantine, and step past the exact offending offset.
  • Suppose a calculation bug requires recomputing the past 24 hours of trade history. How would you execute that backfill without degrading live risk updates? Replaying 24 hours at 50,000 events/s spans 4.32 billion trades (~864 GB), so spin up a separate backfill worker pool under a distinct group.id (risk-agg-backfill) writing into a shadow table (exposure_1m_v2) with isolated offset rows. Protect live consumers and brokers by enforcing Kafka broker byte-rate quotas on the backfill client ID (since reading day-old log segments bypasses the OS page cache and hits broker disks) and coalescing much larger batches (for example, 100,000 trades per SQL transaction, since nobody queries the shadow table mid-backfill), cutting database upserts ~100-fold and finishing in ~2.5–6 hours at 200k–500k events/s. Once the shadow table catches up past a clean minute boundary T0 where live workers already run the patched logic, cut readers over atomically via a SQL view (WHERE window_start < T0 from v1 UNION ALL >= T0 from v2).
  • How do topic replication factor, In-Sync Replicas (ISR), and producer acknowledgment settings interact to prevent trade loss when a Kafka broker goes down? A topic configured with replication factor RF = 3 maintains 1 leader replica and 2 follower replicas per partition, while the ISR tracks the subset of replicas caught up with the leader's log end. When producers publish with acks = all and brokers enforce min.insync.replicas = 2 alongside unclean.leader.election.enable = false (never promoting a lagging out-of-sync replica to leader), every acknowledged trade sits on at least 2 brokers before the producer receives success, and consumers only read up to the high-watermark replicated across the ISR. Losing any 1 broker therefore loses zero acknowledged trades and keeps the partition writable, whereas losing 2 of 3 replicas rejects new writes (NotEnoughReplicas—trading brief write availability to preserve zero data loss) until a replica rejoins the ISR.

Follow-up questions

Similar questions

More Balyasny interview questions

All 4 Balyasny questions →