CapstoneVol. 19 · Part XIX
0 / 0

Trails / Capstone

CP·211E

The Event Layer

TiffinBox's asynchronous backbone built to the capstone's list: Kafka topics, partitions and keys chosen for ordering, events designed as versioned facts with schemas and compatibility rules, the transactional outbox, idempotent consumers, retries that don't block a partition, dead-letter queues with redrive, and replay to rebuild or create projections without resending side effects; with a lab that appends 200,000 events across a schema change, replays them through an upcaster, and compares blocking on a poison event with dead-lettering it.

19 topics · ~11 min read · 16-question quiz
Updated Suggest a correction

Start here: what events are for

Some work in TiffinBox must happen because something else happened, but nobody should wait for it: when an order goes out for delivery, the customer gets a notification; when a menu changes, search is updated; when a kitchen uploads a document, the assistant ingests it; when a refund is issued, analytics records it. Events let the part that knows ("order out for delivery") announce it once, and any number of other parts react in their own time.

The capstone list for the distributed layer is a list of the problems events bring:

Requirement Problem it solves
Kafka a durable, ordered, replayable log many consumers can read independently
event schemas producers and consumers changing at different times without breaking each other
outbox the business change and the event being saved together, or not at all
idempotent consumers the same event delivered twice having the effect of once
retries transient failures recovering on their own
dead-letter queue (DLQ) one bad event not stopping everything behind it
replay rebuilding a broken projection, or starting a new one from history

Replay and a poison event, measured

The lab appended 200,000 order events to a stream, the first half in an old format (amount in rupees as a decimal), the second half in a new one (amount in integer paise with a currency), with one malformed event at position 150,000. Then it rebuilt "revenue per kitchen" from scratch, converting old events to the new format as it read them:

Policy for an event that fails 3 times Events processed Result
keep retrying it (block) 150,001 stuck: the projection stops at the bad event, missing 25% of the data
send it to a DLQ and continue all 200,000, at ~160,000 per second complete; 1 event in the DLQ for a human

A brand-new projection ("top kitchens by revenue") was then built from the same history in 1.2 seconds: history you keep is a feature you can add later.

How deep to go

Volume 17 defines six mastery levels. For the event layer:

Level What you can do
L1 Explain why TiffinBox uses events and what each requirement solves
L2 Publish via an outbox and consume with idempotent consumers
L3 Explain partitions, offsets, replication, delivery semantics and schema compatibility
L4 Debug lag, rebalances, duplicates, ordering bugs and poison events
L5 Design topics, keys, schemas, retry and replay strategies, and defend them
L6 Operate Kafka: capacity, upgrades, retention, incidents, cross-region

Volume 5 (chapters 66–68, 74) and Volume 12, chapters 128 and 131 teach the theory.

Kafka in TiffinBox

The roadmap's baseline is Kafka 4.x, which runs without ZooKeeper (metadata in KRaft controllers). Use a managed service unless operating Kafka is part of your learning goals.

Topics

Topic Key Producers Consumers Retention
orders.v1 order_id Ordering (outbox) notifications, analytics, delivery 30 days (+ archive)
subscriptions.v1 subscription_id Subscriptions notifications, analytics 30 days
payments.v1 payment_id Payments analytics, notifications, reconciliation 90 days
catalogue.v1 dish_id Catalogue search indexer, assistant ingestion compacted (latest per key)
documents.v1 document_id Catalogue assistant ingestion 30 days
*.dlq original key consumers operators, redrive tool 30 days

Settings that protect data

  • Replication factor 3, min.insync.replicas=2, producers with acks=all and idempotence enabled (on by default in current clients): a write survives one broker failure, and producer retries don't duplicate within a partition.
  • Partitions sized for consumer parallelism with headroom (e.g. 12), since adding partitions later changes which partition a key maps to.
  • Retention long enough for replay (30 days here) plus an archive to object storage for longer history; compacted topics for "current state per key" data such as the catalogue.

Designing events

Facts, with an envelope

jsonc
{
  "event_id": "01J9Z6M8Q2R4…",          // unique; consumers deduplicate on it
  "type": "OrderOutForDelivery",
  "schema_version": 2,
  "occurred_at": "2026-11-05T06:42:10Z",
  "producer": "tiffinbox-api/ordering",
  "key": "order-88412",
  "traceparent": "00-4bf92f…-00f067…-01",
  "data": { "order_id": 88412, "kitchen_id": 12, "rider_id": 301, "eta_minutes": 18 }
}
  • Past-tense names for facts; include what consumers need so they don't call back for details ("event-carried state"), but not entire aggregates.
  • No personal data you don't need: an event log is hard to scrub later. Use IDs; let consumers look up contact details at send time.

Schemas and compatibility

  • Define schemas (Avro, Protobuf or JSON Schema) in contracts/ and register them in a schema registry with backward compatibility enforced: new consumers can read old events.
  • Compatible changes: add optional fields with defaults. Incompatible changes (renames, type changes, the lab's rupees → paise) need a new version, and consumers upcast old versions on read (the lab's upcast function), or a new topic with a migration plan.
  • CI checks compatibility on every pull request, like the OpenAPI checks.

The outbox

Volume 18's Phase 8 lab measured the reason: writing to the database and then publishing lost an event on every crash between the two (29 of 29), while the outbox lost none.

  1. The use case inserts the business change and an outbox row (topic, key, payload, headers) in one transaction.
  2. A relay publishes outbox rows in order per key and marks them sent: either a poller (SELECT … FOR UPDATE SKIP LOCKED in batches) or CDC with Debezium's outbox event router reading the WAL.
  3. Sent rows are deleted or partitioned and dropped after a few days.
  4. Monitor outbox age (the oldest unsent row): it's the earliest sign the relay is stuck.

Idempotent consumers

Every consumer assumes it will see some events twice:

  • Record processed events in the consumer's own database, in the same transaction as the effect: INSERT INTO processed_events(event_id) … ON CONFLICT DO NOTHING, and only apply the effect if the insert happened.
  • Or make the effect naturally idempotent: upserts keyed by business ID (search documents by dish_id), state machines that ignore transitions already made ("delivered" can't be applied twice), set-based updates rather than increments.
  • External side effects (emails, push notifications, payments) need their own idempotency: pass the event_id as the provider's idempotency key, or record "notification sent for event X" before sending and check it.
  • Commit offsets after processing, not before; a crash then means reprocessing (safe), not loss.

Retries and the DLQ

Failure Handling
transient (timeout, 503 from a dependency) retry in place a few times with backoff, bounded to seconds
still failing, likely to recover later publish to a retry topic with a delay (e.g. 1 min, 10 min), continue with the next event
permanent (malformed, violates a rule, fails every time) publish to the DLQ with error, stack trace, source topic/partition/offset, attempt count; continue
  • Never block a partition indefinitely (the lab's "stuck"): one poison event would stop every later event with keys on that partition.
  • Retry topics break strict ordering for that key; if order matters (an order's status), either stop that key only (park it) or design consumers to handle out-of-order events (ignore older statuses using a version number).
  • Alert on DLQ growth, give every DLQ a redrive tool (fix the code or the data, then republish the events to the original topic), and make dead-lettering idempotent too: in the lab, running the replay twice put the same poison event in the DLQ twice.

Replay

Replay is reading history again, from a chosen offset or from the beginning:

  • Rebuild a projection: a bug corrupted search or analytics; fix the bug, reset the consumer group (or start a new group) to the earliest offset, and rebuild into a new table or index, then swap.
  • Create a new projection: a new feature (top kitchens by revenue) starts from history, not from today (the lab: 1.2 s for 200,000 events).
  • Disable side effects during replay: run replay consumers in a mode that writes projections only, or rely on side-effect idempotency (already notified for event X).
  • Make sure history exists: retention or archives must cover the period you'll need, and old versions must still be readable (upcasters kept as long as old events exist).

Done when

  • Topics, keys, partitions and retention are documented, created by infrastructure code, with RF 3 and min.insync.replicas=2.
  • Schemas are registered; CI rejects incompatible changes; old versions are upcast.
  • Every event leaves through the outbox; outbox age is monitored.
  • Every consumer is idempotent; duplicate-delivery tests pass (deliver each event twice, compare results).
  • Poison events go to a DLQ with an alert and a working redrive; no partition can be blocked indefinitely.
  • A projection can be rebuilt by replay, with side effects off, in a documented procedure.

Common traps

  • Commands disguised as events, coupling producers to one consumer.
  • Keys chosen for spread, not order, scrambling an order's lifecycle.
  • Retrying forever on a poison event.
  • Replays that resend emails.
  • Personal data in events that can't be erased later.

Lab: replay, schema change and a poison event

Setup. Redis 7 Streams on the lab machine, standing in for a Kafka topic: an append-only log with IDs, read sequentially from any position. (The lab machine can't download Kafka; the behaviour tested here, sequential reading, replay from the start, and what to do with a bad record, is the same.) A Python script:

  1. Appends 200,000 OrderPlaced events for 50 kitchens. The first 100,000 use version 1 (amount in rupees as a decimal); after a "schema change", the rest use version 2 (amount_paise as an integer, plus currency). Event 150,000 is poison: kitchen: "K-??", amount_paise: "lots".
  2. Replays the whole stream to rebuild a projection, revenue and order count per kitchen, upcasting v1 events to v2 on read. A failing event gets 3 attempts, then either: - block: stop (what "retry until it works" amounts to), or - DLQ: write it to a dead-letter stream with the error and its source ID, and continue.
  3. Builds a second, new projection (top kitchens by revenue) from the same history.

Results

Step Result
append 200,000 events 1.7 s (pipelined); stream holds 200,000 entries, 22.4 MB
replay, block policy read 150,001 events in 0.94 s, then stuck at the poison event; projection covers 75% of history (₹3,59,61,960)
replay, DLQ policy read all 200,000 in 1.24 s (~161,000 per second); 1 event dead-lettered; projection complete (₹4,79,81,758)
new projection from history 1.22 s; top kitchens: 13 (4,111 orders, ₹9,88,820), 41 (4,109, ₹9,87,691), 22 (4,059, ₹9,85,646)
DLQ length after the second replay 2: the same poison event, dead-lettered once per replay

What it shows

  • A poison event plus "retry until success" is an outage for everything behind it. Here, a quarter of the history; in a live consumer, every new event on that partition.
  • Upcasting keeps old history useful. One small function let a single consumer read both versions; without it, the schema change would have split history in two.
  • Replay is fast compared with almost any other way of rebuilding derived data: 200,000 events per ~1.2 s in a single Python process. Real consumers with database writes are slower, but the point stands: retained history turns "we need a new report" into a replay rather than a data-migration project.
  • Dead-lettering needs idempotency too. The second replay added a duplicate DLQ entry. Key DLQ records by their source ID (or check before adding) so operators see each problem once.

Try it yourself

  1. Make the DLQ idempotent (use the source ID as a unique key) and rerun both replays.
  2. Add a redrive step: fix the poison event's data, republish it, and confirm the projection's total changes by exactly that order's amount.
  3. Write the projection to PostgreSQL with a processed_events table and deliver every event twice: does the total stay correct?
  4. Run the same experiment against a real Kafka cluster with a consumer group, resetting offsets with kafka-consumer-groups --reset-offsets --to-earliest.

Revision sheet: the event layer

Key ideas

  • Events are facts; keys choose ordering; partitions give parallelism.
  • RF 3, min.insync.replicas=2, acks=all, idempotent producers; retention covering replay.
  • Envelope with event ID, type, version, time, key and trace context; schemas in a registry with backward compatibility; upcasters for old versions.
  • Outbox (poller or CDC) with outbox-age monitoring.
  • Idempotent consumers: processed-event records in the same transaction, natural idempotency, idempotent side effects; commit offsets after processing.
  • Bounded in-place retries, retry topics, DLQ with alerts and redrive; never block a partition.
  • Replay to rebuild or create projections, with side effects off.

Numbers to remember

  • Lab: block policy stuck at 150,001 of 200,000; DLQ policy processed all at ~161k/s; new projection in 1.2 s; duplicate DLQ entry on a second replay.

Pitfalls

  • Disguised commands; keys that scramble order; infinite retries; replays with side effects; personal data in events.

Glossary

  • Partition: an ordered, append-only log; the unit of parallelism.
  • Consumer group: consumers sharing a topic's partitions, each partition read by one member.
  • Offset: a consumer's position in a partition.
  • Compacted topic: keeps the latest value per key.
  • Upcaster: code converting an old event version to the current one.