Chapter 27 — Log-Based Streaming & Event-Driven Architecture (Kafka)
Part V · Distributed Systems, Messaging & Scale | Prerequisites: Ch 25–Ch 26 | Builds: a Kafka activity-event log feeding Pulsely's chart timeline & population analytics
Earlier you moved slow, fan-out work off the request path and into a queue, and you closed the dual-write hole with the transactional outbox. That chapter ended on a deliberate cliffhanger: a queue is destructive. The broker tracks who has dealt with each message, and the instant a consumer acknowledges one, the message is gone. That property is exactly right for jobs — you post a payment once, you send one appointment reminder once, you want the work to leave the system when it's done. But it is exactly wrong for a different shape of problem, and this chapter is about that shape.
This chapter introduces a primitive that is not a faster queue, even though it ships inside a thing called a "message broker" and people will tell you it is one. The log is an append-only, ordered, non-destructive record of what happened, that any number of independent readers consume at their own pace, and that you can rewind and replay. Get the queue-vs-log distinction solid and most of "should I use Kafka here?" answers itself. We'll build Pulsely a pulsely.clinical.events log feeding two unrelated consumers, choose a partition key on purpose, and — at the end — adopt CQRS and event sourcing only where the arithmetic actually pays for itself, because the most senior thing in this chapter is knowing when not to reach for the shiny abstraction.
1. The problem: a queue forgets, and you needed it to remember
Let me give you four pains, because they all point at the same missing primitive, and seeing them converge is the whole "why."
Pulsely's chart-timeline service consumes an activity queue: encounter-signed, vital-recorded, lab-resulted, med-prescribed. It works. Then the quality team asks for a population dashboard — "abnormal vitals per patient per hour, encounters per provider this week" — and they write a second consumer on the same queue. The next morning the timeline is missing half its entries and analytics is missing the other half. Of course it is: a queue has competing consumers. Each message is delivered to one member of the consumer set and then deleted. Timeline and analytics aren't cooperating to drain a work queue; they each want every event, independently. You can bolt on a fan-out exchange that copies each message into two queues, then a third when the clinical-search indexer wants in, then a fourth — and now you maintain a brittle wiring diagram whose only job is to undo the queue's defining behavior.
Second pain. A timeline bug shipped last Tuesday corrupted a week of denormalized chart-timeline entries. You'd love to replay last week's activity events and rebuild the timeline from clean code. With a queue: impossible. Those messages were ACKed and deleted the moment they were processed. The history that would let you recover is gone, consumed by the very mechanism that's supposed to be reliable.
Third pain. At the evening charting rush the critical-value alert consumer falls behind. With a queue you can see depth — "12,400 messages waiting" — but depth conflates two different consumers and tells you nothing about position. You can't answer the only question that matters during an incident: "how far behind is this specific consumer — the one that pages a clinician about a dangerous potassium level — and is the gap growing or shrinking?"
Fourth pain. Two events for the same lab result — result.preliminary then result.final — land on two different queue workers and get processed out of order. The chart now shows the final value still flagged "preliminary," so a clinician second-guesses a real critical result. The queue made no promise about order across workers, and you assumed one.
Strip these to bone. You don't want a mailbox that hands each letter to one clerk and shreds it. You want a durable, ordered, re-readable record of what happened, that many independent readers consume at their own pace, where each reader remembers its own place. That is a log. It is a genuinely different data structure from a queue, and conflating the two is the single most common Kafka mistake.
🚫 A framing this book rejects. "Kafka is just a faster, more scalable queue, so use it everywhere instead of RabbitMQ." This is wrong in a way that will hurt you. A queue and a log have opposite ownership of progress: the queue's broker tracks delivery and deletes on ACK; the log tracks nothing about you and never deletes on your behalf. Choosing Kafka for a simple, single-consumer, fire-and-forget job (generate one visit-summary PDF) buys you partition management, offset bookkeeping, and rebalance pain you didn't need. The question is never "which is faster." It's "do I want competing consumers and destructive reads, or independent readers and replayable history?"
2. The mental model: a cursor over an append-only file
Hold one picture for the whole chapter.
A log is an append-only, ordered file of immutable records. Writers append to the end. Readers hold a cursor — an integer offset — and read forward at whatever speed they like. The log does not know or care how far any reader has gotten. It is, almost literally, a file with a write-head and many independent read-heads.
offset: 0 1 2 3 4 5 6 7 8 ── append here ─▶
┌────┬────┬────┬────┬────┬────┬────┬────┬────┐
log: │ e0 │ e1 │ e2 │ e3 │ e4 │ e5 │ e6 │ e7 │ e8 │
└────┴────┴────┴────┴────┴────┴────┴────┴────┘
▲ ▲
timeline cursor analytics cursor
(committed: 3) (committed: 6)
Two consumers, two cursors, same data, no interference. Timeline is at offset 3, analytics at 6. Neither steals from the other because reading is non-destructive — consuming a record doesn't remove it. This single drawing dissolves all four pains in §1: independent readers (pains 1, 3), replay by rewinding a cursor (pain 2), and — once we add partitions — per-key order (pain 4).
🧭 Mental model. A queue is a mailbox: the broker holds your mail, hands each letter to one recipient, and throws it away once accepted. A log is a ledger: the writer appends entries forever, and each reader keeps their own bookmark. In a queue, the broker owns "who has dealt with this." In a log, the reader owns "how far I've read." Move that one responsibility — progress tracking — from broker to reader, and almost everything else about Kafka follows.
A few more pieces snap onto that frame.
Partitions are the log sharded for parallelism. A topic isn't one file; it's N independent append-only logs (partitions). The whole topic has no total order — but each partition is a strictly ordered sub-log. Ordering is a per-partition property, and you buy it with a partition key: records with the same key always land on the same partition, so they're ordered relative to each other.
A consumer group is one logical reader spread across many instances. Kafka assigns each partition to exactly one consumer in the group, so parallelism is capped by partition count, not by how many consumers you start. Five consumers on a four-partition topic means one consumer sits idle.
And the inversion that makes event-driven architecture click: the database is a cache of the log. Flip the usual model. The immutable event stream is the source of truth; your chart-timeline cache, analytics tables, and clinical search index are projections — derived, disposable, rebuildable by replaying the log. We'll hold this lightly (with skepticism, in §7), but it's the seed of CQRS and event sourcing.
One last distinction that prevents a category error all chapter: events vs commands. An event is a fact that already happened — ClaimSubmitted, past tense, owned by the producer, broadcast to whoever cares. A command is a request for intent — SubmitClaim, imperative, owned by a specific target, addressed to one handler. Events go on a log; commands go to a queue. Confuse them and you leak coupling: a producer that emits "events" which secretly mean "and you, consumer X, must do this specific thing" has built a command in event's clothing, and now the producer knows about the consumer it claimed not to.
3. Theory & invariants: ordering, offsets, retention, durability
A mental model tells you how to picture the log. Invariants tell you what stays true under load, failure, and replay. These are the load-bearing rules.
First, vocabulary — Kafka has a lot of it, and the words are load-bearing. But meeting twelve terms in one breath is like a React newcomer meeting props, state, context, refs, keys, portals, and fibers in a single sentence: technically complete, practically useless. So here are only the four you need to hold the whole chapter. The durability-specific terms (high-watermark, ISR, leader/follower) we'll meet in the durability discussion below, where they're first actually used.
| Term | One-line meaning | Where it bites you |
|---|---|---|
| topic | a named log | the unit you produce to and subscribe to |
| partition | one ordered shard of a topic | ordering and parallelism are both per-partition |
| offset | a record's position in a partition | it's your cursor; committing it is delivery semantics |
| consumer group | a set of cooperating readers sharing a topic's partitions | parallelism caps at partition count |
Three more you'll meet by name as we go, defined where they matter: retention (how long records live — later this section), rebalance (partitions reassigned when group membership changes — §4), and tombstone (a null-valued record that marks a key for deletion under compaction — the compaction invariant below). The durability terms — log-end-offset, high-watermark, ISR, group coordinator, leader/follower replica — land in the durability invariant, glossed there.
🔑 The ordering invariant. Kafka guarantees order only within a partition — never across a topic. Records with the same partition key go to the same partition and are therefore strictly ordered relative to each other; records with different keys may interleave arbitrarily. This makes your partition key your ordering boundary. If
result.preliminaryandresult.finalfor one patient must be processed in order, they must share a key (so, key bypatient_id). The price you pay: every record for a hot key piles onto one partition (the skew risk in §6) — a patient on a continuously-streaming monitor floods their partition. Ordering and skew are two faces of the same key choice — you cannot tune one without affecting the other.
🔑 The offset invariant. Offsets are per-partition, monotonically increasing, and committed by the consumer, not the broker. The crucial gap: a committed offset means "I told the broker I'm past here," which is not the same as "I successfully processed this." That gap is the entire source of delivery semantics. Commit the offset before you process and a crash loses the record (at-most-once). Commit after you process and a crash reprocesses it (at-least-once). There is no third option that the network can give you for free.
This is the same trilemma you've already met, now in Kafka's vocabulary. At-most-once (commit before process) silently drops on crash — for a critical-value alert that's a patient-safety event, not a rounding error. At-least-once (process, then commit) is the sane default — it demands idempotent consumers, which you already know how to build. "Exactly-once" exists only as a transactional produce-plus-commit within Kafka's own boundary, at real throughput cost, and it evaporates the moment your consumer writes to an external Postgres. We'll be precise about that in §4.
📎 Borrowed on credit: idempotent consumers. Because the only honest delivery default is at-least-once, every consumer in this chapter must converge under redelivery — process the same event twice, same final state. In healthcare that "twice" is not hypothetical: a home device re-POSTs a reading storm after a flaky cellular link, a webhook partner retries, an offset resets. The full machinery (dedup tables, natural keys like a claim control number,
INSERT ... ON CONFLICT, fencing tokens) is the whole of Ch 25. Here, just hold the assertion: at-least-once delivery + idempotent effect = effectively-once processing, and you manufacture the "once" at the handler, never at the broker.
🔑 The retention invariant. Retention is time- or size-based and independent of consumption. A record is deleted when it ages past
retention.msor the partition exceedsretention.bytes— whether or not anyone read it, and whether or not everyone read it long ago. Retention is not an ACK. This is what decouples a consumer's liveness from the data's lifetime: a slow consumer doesn't extend retention (it can fall off the end and miss data), and a fast consumer doesn't shorten it (the data stays for the next reader and for replay). Set retention by how long you might need to replay — and, for anything touching PHI, by how long you're legally required to keep the audit trail — not by how long until "everyone's done."
A second cleanup policy changes the game entirely:
🔑 The compaction invariant. For a topic with
cleanup.policy=compact, Kafka guarantees it retains at least the latest value per key, forever, even as it discards older values for the same key. This turns a log of events into a durable, replayable changelog — a key→latest-value snapshot you can replay to reconstruct current state. Atombstone(a record with a null value) marks a key for eventual removal. Compaction is how a log doubles as a materialized table; it is a different retention model from time-based deletion, and choosing the wrong one is a classic footgun (a HIPAA audit consumer on a compacted topic silently loses history — §6).
🔑 The durability invariant. A record is "committed" — readable, surviving failures — once it's replicated to all in-sync replicas (ISR). Now the deferred vocabulary, glossed where it finally matters:
- leader/follower replica: per partition, one broker is the leader (takes all writes); the others are followers that copy it.
- ISR (in-sync replicas): the followers currently caught up to the leader.
- log-end-offset: the tail — the next offset to be written.
- high-watermark: the highest offset replicated to all ISR members, i.e. the last committed record consumers are allowed to read.
Two producer settings define the contract:
acks(how many replicas must confirm before the producer'ssendreturns —0= fire-and-forget,1= leader only,all= every ISR member) andmin.insync.replicas(how many ISR members must exist for anacks=allwrite to be accepted at all). The durable default is replication factor 3 withmin.insync.replicas=2andacks=all: a write isn't acknowledged until at least two replicas hold it, so a single broker death loses nothing. This is the quorum reasoning you've already met, wearing Kafka's clothes —acks=allover an ISR is the producer half of "a majority must agree before we call it true."
Finally, the single most important operational number in the whole chapter:
🔑 Consumer lag. For each partition, lag = log-end-offset − committed-offset: how many records the writer is ahead of this consumer. Lag that's bounded or falling means healthy; lag rising monotonically means the consumer is under-provisioned or stuck. It is the one metric that tells you whether your event pipeline is keeping its promises — and whether that critical-value alert is arriving in seconds or in hours. (How to alert on it is observability work we'll get to; here, just internalize that it's the heartbeat.)
4. Under the hood: segments, the producer path, and the rebalance trap
Let's kill the magic. Kafka feels like a database, but its core is embarrassingly simple, and the simplicity is why it's fast.
Storage. Each partition is a directory of segment files plus index files. An append is a sequential write to the end of the active segment — the cheapest operation a spinning or solid-state disk can do, because there's no seeking and no in-place mutation. Reads are served from the OS page cache and shipped to the network with zero-copy sendfile. In plain terms: the OS already keeps recently-written data in RAM (that RAM buffer is the page cache), and Kafka hands those bytes straight from that RAM to the network card (the NIC) without first copying them into its own Java memory (its "heap") — one fewer wasteful copy, so it's fast. If you've watched the browser serve an image from its HTTP cache instead of re-downloading and re-decoding it, this is the same move: skip the redundant work, hand over what you already have. Retention doesn't tediously delete individual records; it drops whole aged-out segment files. That's the entire performance story: append-only sequential I/O, page cache, zero-copy. Kafka is fast on cheap disks precisely because it refuses to behave like a random-access database.
topic "pulsely.clinical.events", partition 0, on disk:
00000000000.log 00000000000.index ← old segment (deletable as a unit)
00000017404.log 00000017404.index ← active segment, appends land here ─▶
The producer path (KafkaJS, Node/TS). A producer batches records (waiting up to linger.ms to fill a batch — throughput vs latency), runs each through a partitioner (default: murmur2(key) mod partitionCount, so equal keys → equal partition), and sends with a chosen acks level.
import { Kafka, Partitioners } from 'kafkajs';
const kafka = new Kafka({ clientId: 'pulsely-api', brokers: ['kafka:9092'] });
const producer = kafka.producer({
idempotent: true, // PID + sequence numbers dedupe broker-side retries
createPartitioner: Partitioners.DefaultPartitioner, // murmur2(key) → partition
maxInFlightRequests: 5,
});
await producer.connect();
// An EVENT: a fact that happened, past tense, keyed by the entity whose order we must preserve.
await producer.send({
topic: 'pulsely.clinical.events',
acks: -1, // 'all' — wait for every in-sync replica; pairs with min.insync.replicas=2
messages: [{
key: patientId, // partition key → ordering boundary for this patient's timeline
value: JSON.stringify({
eventType: 'VitalRecorded',
version: 1, // schema version travels in the envelope
patientId, deviceId, loinc: '8867-4', value: 112, unit: 'bpm',
at: new Date().toISOString(),
}),
}],
});
That idempotent: true is worth a sentence: it gives the producer a producer ID and per-partition sequence numbers, so if a network blip makes the producer retry a send, the broker recognizes the duplicate and writes it once. This is Kafka's producer-side dedup, and it's the honest core of what "exactly-once" markets. It's also what makes the maxInFlightRequests: 5 above safe. Here is the failure it prevents, step by step:
- Say requests A then B are both in flight.
- A fails and is retried; meanwhile B has already landed on the partition.
- The retry of A now writes after B — the partition is now out of order.
Without idempotence, the only way to prevent that is maxInFlightRequests: 1 (one request at a time — you give up pipelined throughput to keep order). With it, each record carries a sequence number, so the broker spots the out-of-order retry and rejects it. That's why you keep both the per-partition ordering §3 leaned on and five pipelined requests in flight — you don't have to choose.
The consumer path. A consumer in a group subscribes, then processes records. For at-least-once, you turn off auto-commit and commit after the handler succeeds:
const consumer = kafka.consumer({
groupId: 'chart-timeline', // the consumer GROUP — its own set of committed offsets
sessionTimeout: 30_000, // miss heartbeats this long → coordinator evicts you
maxWaitTimeInMs: 500,
});
await consumer.connect();
await consumer.subscribe({ topic: 'pulsely.clinical.events', fromBeginning: false });
await consumer.run({
autoCommitInterval: undefined, // we commit manually, after processing
eachMessage: async ({ topic, partition, message, heartbeat }) => {
await applyToTimelineProjection(message); // idempotent UPSERT — at-least-once means expect redelivery
await heartbeat(); // tell the coordinator we're alive on long work
await consumer.commitOffsets([
{ topic, partition, offset: (Number(message.offset) + 1).toString() },
]);
},
});
Consumer groups and rebalancing. The group coordinator (a broker) assigns partitions to group members. When membership changes — a consumer joins, leaves, crashes, or misses its poll deadline — the group rebalances: partitions are reassigned, and during the reassignment the group briefly stops processing ("stop-the-world" for that group). Sticky/cooperative assignors reduce how many partitions move; static membership (group.instance.id) lets a consumer keep its partitions across a rolling restart instead of triggering a rebalance.
Here is the bug you will hit, named so you recognize it on sight:
healthy: consumer polls ──▶ processes ──▶ polls ──▶ processes ... (heartbeats flow)
the trap: consumer polls ──▶ handler runs 6 min ──X── poll deadline (max.poll.interval.ms) missed
│
coordinator: "this member is dead" ──▶ REBALANCE ──▶ partitions reassigned
│
evicted consumer wakes, tries to commit ──▶ rejected (not a member) ──▶ in-flight work
reprocessed by the new owner = DUPLICATES
A handler slower than max.poll.interval.ms makes the coordinator conclude the consumer is dead, evict it, and reassign its partitions — so the work in flight gets reprocessed elsewhere, and the evicted consumer rejoins, triggering another rebalance, and you spiral. "My consumer keeps rebalancing and reprocessing" is almost always this. Fixes: shrink the batch, raise max.poll.interval.ms honestly, call heartbeat() during long work, and lean on idempotent handlers so the duplicates that do slip through are harmless.
🛑 What we deliberately did not explain. How Kafka's replication protocol elects a partition leader and manages ISR membership under a network partition — that's the consensus machinery of Ch 24, and Kafka's older ZooKeeper (ZAB) and newer KRaft (Raft) controllers are two consensus engines solving it. We also won't open the byte-level wire protocol, the fetch-session machinery, or how the JVM broker tunes its page-cache interaction. We located these on the map; we didn't furnish them. The transferable lesson from Ch 24 is enough: you almost never write consensus — you depend on someone who did, and
acks/min.insync.replicasare the knobs that expose it.
A JVM aside (skip if you don't write Java — keep the payoff). The canonical Java KafkaConsumer is a single-threaded poll loop by deliberate design: call poll(), process, poll() again, and that's the whole contract. Spring Kafka layers @KafkaListener with per-partition concurrency over it, and Kafka Streams adds a genuine stream-processing runtime. The transferable payoff, no Java required: hand-rolled Node consumers give you map/filter/route cheaply, but the moment you need stateful stream processing (next paragraph), you're rebuilding a slice of Kafka Streams — and you should know that before you start.
Stream processing, kept concrete. First, what does stateful even mean here? Anchor it in something you already own:
- Stateless = transform each event on its own, remembering nothing between events — exactly
Array.map/Array.filter. Normalize a raw reading, drop events you don't care about, route one topic to another. Trivial in a Node consumer: read, transform, produce. - Stateful = you must remember something across events — e.g. "abnormal readings per patient in the last hour," which means keeping a live running counter. The hard part: that counter has to survive the consumer crashing and restarting on another machine.
That memory-that-survives-a-crash is what a real stream processor gives you: local state plus a compacted changelog topic, so a restarted consumer rebuilds its counters from the changelog instead of from zero. (RocksDB is just Kafka Streams' local on-disk store for those counters.) Windowing (tumbling / hopping / session windows) and the late-event problem (an event arrives after its window closed — do you drop it, or reopen the window?) are real and deep; name them, reach for Kafka Streams or Flink when you genuinely need them, and don't hand-roll windowed state over a raw consumer unless you enjoy debugging it.
5. In production: topic design, the outbox, idempotent projections, and replay
The toy works on your laptop. Production adds six concerns, and each maps to a config you actually set.
Topic design. Name topics for the domain, not the consumer: pulsely.clinical.events, pulsely.claim.events — the consumer set will change; the events won't. Choose partition count for peak parallelism plus headroom, and over-provision deliberately, because adding partitions later breaks the key → partition mapping (murmur2(key) mod N changes when N changes), so a key that used to land on partition 2 suddenly lands on partition 5, and per-key ordering breaks across the change. Pick a number you won't outgrow. Replication factor 3 with min.insync.replicas=2 is the durable default; in dev, RF1 is fine.
Schema discipline. An event topic is a contract read by consumers you don't control and haven't met yet — sometimes literally external partners speaking X12, HL7v2, or FHIR. Use a schema registry (Avro, Protobuf, or JSON Schema) with backward-compatible evolution rules: you may add optional fields; you may never change a field's meaning or remove one a consumer relies on. Carry an eventType and a version in the envelope so consumers can branch on schema generation. The discipline is the same as the API-versioning discipline you've already met: once it's published, someone depends on it.
The outbox, carried straight from last chapter. Producing to Kafka and committing to Postgres are not one transaction — Kafka isn't in your DB's transaction. So the dual-write hole is back: commit the claim, crash before the producer.send, and the claim exists in your DB with no event — it never reaches the clearinghouse, and you've silently dropped a bill. The fix is identical to before: write the event into an outbox table in the same DB transaction as the business change, then a relay (a poller, or CDC via Debezium reading the WAL) ships outbox rows to Kafka and marks them sent. The relay's publish is at-least-once; your idempotent consumers already absorb that.
// One transaction: the business fact and the intent-to-publish commit together or not at all.
await db.transaction(async (tx) => {
const claim = await tx.claims.insert({ /* ... 837 claim ... */ });
await tx.outbox.insert({
topic: 'pulsely.claim.events',
key: claim.controlNumber, // partition key = claim control number (also the idempotency key)
payload: { eventType: 'ClaimSubmitted', version: 1, claimId: claim.id, controlNumber: claim.controlNumber /* ... */ },
});
}); // a separate relay reads outbox → producer.send(...) → marks row sent
The claim control number doing double duty as the partition key and the idempotency key is the whole game in RCM: submit the same claim twice and you double-bill a payer — a compliance problem, not a cosmetic one.
Idempotent projections. Because delivery is at-least-once, every consumer must dedup or be naturally idempotent. Two tools: a processed_events table keyed by event ID (skip if seen), or set-based projections that are idempotent by construction — UPSERT timeline_entry, not INSERT; UPDATE ... WHERE status='pending', not blind mutation. Reprocessing the same event must converge, because under a rebalance or a replay it will be reprocessed.
Consumer lag, operated. Export per-partition lag to metrics (kafka-exporter, Burrow, or KafkaJS instrumentation events), dashboard it per partition (not just per topic — a single hot partition hides in the topic average), and alert on both rising lag and stalled offsets. The alerting design itself is observability work; the point here is that lag is the number you watch — and on the critical-value pipeline it's a patient-safety number.
Retention and compaction, the configs you actually set. retention.ms / retention.bytes for time/size deletion; cleanup.policy=delete (default), compact (keep latest-per-key), or compact,delete (keep latest-per-key and age out); min.cleanable.dirty.ratio for how aggressively compaction runs; tombstones (null value) to delete a key from a compacted topic. Match the policy to the use: pulsely.clinical.events for analytics/audit wants delete with a generous window (and PHI audit trails often have a legally mandated multi-year minimum); a "latest patient-summary state" changelog wants compact.
Replay. To rebuild the corrupted chart-timeline from §1: reset the chart-timeline consumer group's offsets to a timestamp or to earliest, and let it re-consume. The analytics group's offsets are untouched, so analytics is completely unaffected — independent cursors, exactly as promised. The discipline that makes replay safe: consumers must be idempotent and side-effect-careful. Replaying a year of ClaimSubmitted events must not re-submit a year of claims to the clearinghouse, or re-fire a year of appointment reminders — so either projections are pure DB upserts, or you gate external side effects behind a "this is a replay" flag.
🏭 The replay footgun. Replay is the log's superpower and its sharpest edge. Resetting offsets re-fires every event from that point. To an internal projection (a DB upsert) that's harmless and idempotent. To an external system — a clearinghouse, an e-Rx gateway, a lab interface, an SMS reminder provider — replay is a self-inflicted DDoS: you re-submit millions of claims (double-billing every payer), or re-blast a year of reminders. The rule: an event consumer with external side effects must be replay-aware, and the safest design keeps external-effect consumers separate from rebuild-from-history projections, so you can replay the projections without ever touching the side-effecting consumer.
6. Common pitfalls
Each is written as signature → fix: the symptom you'll observe, then the principle that resolves it.
Rising consumer lag under a spike.
Signature: the lag dashboard climbs on all partitions during peak; the consumer can't keep up and the gap grows monotonically.
Fix: scale consumers up to the partition count first (that's free parallelism you already provisioned), then add partitions, then tune eachBatch and push slow I/O (external calls, big writes) out of the hot loop. The ceiling is partition count — you can't parallelize past it.
A single hot partition.
Signature: one partition's lag climbs while the others sit idle; one consumer is pinned at 100% CPU and the rest are bored.
Fix: your partition key is skewed — low cardinality, or one high-volume value dominating (keying by patient_id when one continuously-streaming home monitor produces 80% of the topic's events). Re-key to a higher-cardinality field, or salt the hot key (patient_id:bucket) to spread it, accepting that you've now given up strict per-patient order for that key.
Rebalance storms.
Signature: logs repeat "group rebalancing," throughput collapses, and records get reprocessed.
Fix: the handler exceeds max.poll.interval.ms, so the coordinator evicts and reassigns (the §4 trap). Shrink the batch, raise the interval honestly, heartbeat() during long work, and adopt a cooperative assignor plus static membership so rolling restarts don't churn the group.
Reordering despite "Kafka is ordered."
Signature: two events for one entity are processed out of order — result.final before result.preliminary, so the chart shows a final value flagged preliminary.
Fix: those events weren't on the same partition, because they didn't share a key. Order is per-partition only. Key by the entity whose ordering you must preserve (patient_id), and accept that this is also what concentrates that entity's load onto one partition.
Duplicate side effects.
Signature: a patient is double-notified, or a claim is double-submitted, after a rebalance or restart.
Fix: at-least-once is the default — expect redelivery. Add an idempotency key (the claim control number, or device_id + timestamp) and dedup, or make the effect a set-based upsert. Do not chase fragile exactly-once to avoid building idempotent handlers.
Lost events on producer crash.
Signature: the DB row exists but no event reached Kafka.
Fix: either you used acks=1 and the leader died before replicating, or you did a dual-write with no outbox. Set acks=all + min.insync.replicas=2 for durability, and use the outbox so the publish is atomic with the DB commit.
Compaction surprise.
Signature: a HIPAA audit consumer finds old events have silently vanished from the topic.
Fix: the topic is cleanup.policy=compact, which keeps only the latest value per key. Audit needs history — every prior state — so it needs a delete-retention topic with a long window, never a compacted one. Compaction is a changelog, not an audit log.
"Just add a partition" breaks ordering.
Signature: after scaling partitions, a key that used to be ordered suddenly interleaves.
Fix: partition count is part of your keying contract — murmur2(key) mod N moves keys when N changes. Size partitions up front with headroom; treat repartitioning as a deliberate, planned migration, not a routine scale-up.
7. Tradeoffs
Senior engineering is naming the spectrum and saying why you're standing where you stand. This section is also where the two Pulsely ADRs live.
Queue vs log for Pulsely clinical activity (ADR decision 1). A queue wins for single-consumer, work-distribution, fire-and-forget jobs: it's simpler, the broker tracks state for you, and there's no offset or partition bookkeeping. A log wins when you have multiple independent consumers, need replay, or need an audit/history. Pulsely's clinical-activity stream has a chart-timeline consumer, a population-analytics consumer, and a near-certain future clinical-search indexer — three independent readers wanting every event, plus the replay requirement from §1's timeline-rebuild, plus a standing HIPAA need for an immutable history. That's a log. You'd reverse this if only one consumer ever needed activity and replay were worthless — then a queue is strictly less operational weight, and reaching for Kafka would be cargo-culting.
Partition-key choice for pulsely.clinical.events (ADR decision 2).
Three candidates. patient_id preserves per-patient ordering (natural for a chart timeline, which is a per-patient sequence) but risks a hot partition when one high-volume monitored patient dominates. encounter_id preserves per-encounter ordering and spreads load more evenly across many encounters, but a patient's cross-encounter timeline loses order. Random/round-robin gives maximum balance but zero ordering — fine for pure analytics counters that don't care about sequence. The decision rule: key by the entity whose ordering you must preserve; if none, key for balance. For pulsely.clinical.events, key by patient_id (the timeline's per-patient order is the strongest clinical requirement — a preliminary → final result flip is a safety bug), and salt the rare high-volume device key to defuse the hot partition — accepting a documented, bounded loss of strict order for those salted keys.
More partitions vs fewer. More partitions buy parallelism but cost more open file handles, longer rebalances, higher end-to-end latency variance, and they never buy global order. Don't over-shard "to be safe."
acks=all + RF3 vs acks=1. Durability vs latency/throughput, pick per topic by data value. claim and critical-value events earn acks=all; a high-volume, low-stakes telemetry stream might accept acks=1.
Exactly-once vs idempotent at-least-once. Kafka's EOS (transactions) has real throughput and complexity cost and only spans Kafka→Kafka cleanly. The instant you write to an external Postgres, the guarantee ends at the broker edge and you need an idempotent sink anyway. For Kafka→DB, idempotent consumers are simpler and almost always sufficient. Don't pay for EOS to avoid the idempotency you'll need regardless.
CQRS and event sourcing — taught with skepticism. This is where teams hurt themselves chasing modernity, so be blunt. Event sourcing stores state as an append-only log of events and derives current state by replaying them; CQRS splits the write model from one or more read models. They genuinely pay off when you need temporal queries / audit ("what was this claim's exact state at 14:32, and who touched it?"), multiple divergent read models from one write stream, or rebuild-from-history. They charge you, in return: eventual-consistency UX (the read model lags the write), the misery of versioning and replaying old events as your schema evolves, and the maddening "where's the current state?" debugging session where the answer is "replay 40,000 events." For Pulsely: event-source the claim lifecycle — Drafted → Submitted → Accepted → Adjudicated → Paid / Denied → Appealed is a state machine where audit and temporal queries are hard RCM and compliance requirements, so the cost buys something real. Do not event-source patient demographics — a demographics record is a CRUD row; event-sourcing it is pure ceremony with no payoff. You'd reverse toward CRUD for any young feature with one read model and no audit need. The senior signal is the no, not the yes.
Choreography vs orchestration for distributed workflows. When ClaimSubmitted must trigger clearinghouse-scrub, payer-adjudicate, then post-remittance, two shapes exist. Choreography: each service subscribes to events and reacts, emitting its own events — loose coupling, no central bottleneck, but the end-to-end flow is emergent and hard to trace ("why hasn't this claim paid?" becomes archaeology across five services' logs). Orchestration: a central saga coordinator drives the steps explicitly, issuing commands and awaiting events — the workflow is visible, testable, and centrally logged, at the cost of a central component and tighter coupling. Sagas are how you get distributed-transaction-like behavior without a distributed transaction: a sequence of local transactions, each with a compensating action that undoes it if a later step fails (the payer denies the claim → reverse the expected-payment you optimistically posted to A/R and open a denial-rework task; you don't roll back, you compensate forward). Reverse toward orchestration as a flow's failure handling and compensation logic grow complex — choreography's looseness becomes a liability exactly when the failure paths multiply, and in RCM they multiply fast (rejections, partial pays, takebacks, appeals).
Choreography (events, reactive): Orchestration (saga, commanded):
ClaimSubmitted ─▶ [Clearinghouse] ─emits─▶ ┌──────────────────┐
ClaimAccepted ─▶ [Payer] ─emits─▶ │ Saga coordinator│
Adjudicated ─▶ [Remit posting] └──────────────────┘
│ scrub 837 ──▶ ok
(each service knows only events; │ adjudicate ──▶ DENIED
flow is emergent, no owner) │ COMPENSATE: reverse A/R, open appeal
(one place owns the flow)
8. Security & scale notes
Security and scale are properties of the whole system, so we weave them in rather than quarantine them.
A topic is a shared contract — guard read access. Anyone subscribed to pulsely.clinical.events sees every field of every event. In healthcare that's not "a PII leak" — it's PHI, and one patient's data reaching a consumer with no treatment relationship is a reportable HIPAA breach. Use per-topic ACLs, TLS in transit between clients and brokers (the TLS machinery you've already met), and keep PHI out of event payloads — reference entities by ID (patient MRN, encounter ID) and let consumers fetch what they're authorized for, or encrypt sensitive fields so the topic carries ciphertext.
Tenant and minimum-necessary isolation lives at the consumer, not just the broker. Events carry patient_id / clinic / org context, and a mis-scoped or over-subscribed consumer can read another clinic's activity. Authorize at the consumer — re-derive what this consumer is allowed to project, server-side, from the authenticated principal, honoring minimum-necessary — the same trust-boundary discipline you've already met. A subscription is not an entitlement. (Emergency break-glass access still belongs in the read path, logged and justified — it is never a reason to widen a topic ACL.)
Poison messages can wedge a whole partition. A single unparseable or deterministically-failing record, retried forever, freezes its partition: lag on that partition explodes while the others flow — and if that partition carries critical-value events, alerts stop arriving. Apply bounded retries, route the bad record to a dead-letter topic, alert on it, and keep moving. The forward-progress invariant from last chapter carries over directly — never block the partition on one bad record.
Backpressure and the scale ceiling. Producers buffer and then block or throw when brokers can't keep up; consumers fall behind and lag grows. The scale path is a fixed ladder: add consumer instances up to partition count → add partitions → tune batching → push slow I/O out of the handler. Know that the hard ceiling is partition count, and that adding partitions has its own cost (§6). The reliability patterns that keep this from cascading — circuit breakers, load shedding — are reliability-engineering patterns we'll get to.
📎 Borrowed on credit: consumer-lag alerting. Lag is the heartbeat (§3), but turning it into a paging alert — thresholds, rate-of-change, stalled-offset detection, dashboards per partition — is observability work. We name it here and build it in Ch 34. For now: instrument lag from day one; a critical-value pipeline without a lag dashboard is flying blind.
Retention vs the right to erasure. An immutable log fights a patient's data-deletion request head-on: how do you delete a person from an append-only history? Three strategies. Compaction + tombstones: write a null-valued record for the key so compaction eventually removes it. Crypto-shredding: encrypt per-patient data with a per-patient key, then delete the key — the ciphertext remains but is permanently unreadable. Short retention + durable derived store: keep the log's window short and hold the authoritative, erasable state in a normal database. Healthcare adds a genuine tension the social-app version never had: medical-record-retention law often requires you to keep clinical records for years, so "erase everything" and "retain the legal record" collide — crypto-shredding, scoped to the fields you may lawfully drop, is usually the honest answer. Pick consciously; "we have an immutable log so we can't comply" is not an answer a regulator accepts.
Scale of replay, restated as a threat. From §5: replay re-fires every event. At scale, an offset reset pointed at a side-effecting consumer is a self-inflicted denial-of-service against your own patients (and possibly your clearinghouse's reputation, and a payer's fraud heuristics flagging you for duplicate claims). Treat "who can reset offsets, and which consumers have external side effects" as a security boundary, not just an ops convenience.
9. Interview lens & exercises
Interview questions
Backend interviews probe whether you reason about systems or recite them. Same question, different level.
"Queue vs log — when do you reach for each?"
- Junior answer: "Kafka is just a faster, more scalable queue."
- Senior answer: frames it as competing consumers + destructive read (queue) vs independent readers + non-destructive, replayable cursors (log), and names the deciders — multiple independent consumers, replay, and audit/history push you to a log; single-consumer fire-and-forget jobs stay a queue. Names that the difference is who owns progress.
"How does Kafka guarantee ordering?"
- Junior: "Kafka keeps messages in order." (Wrong globally.)
- Senior: "Only within a partition, never across a topic. Same key → same partition → ordered. So the partition key is your ordering boundary, which is also your skew risk — order by
patient_idand you've concentrated that patient's monitoring load onto one partition." Ties ordering and hot-keying to the same decision.
"Your consumer keeps rebalancing and reprocessing — why?"
- Junior: "add more consumers."
- Senior: "the handler exceeds
max.poll.interval.ms, so the coordinator thinks it's dead, evicts it, and reassigns its partitions — the in-flight work reprocesses, and the rejoin triggers another rebalance. Fix with smaller batches, an honest interval, heartbeats during long work, cooperative assignor + static membership, and idempotent handlers so the duplicates that slip through are harmless."
"Would you event-source Pulsely?"
- Junior: "event sourcing everywhere, it's the modern way."
- Senior: "Yes for the claim lifecycle — it's a state machine with real audit and temporal-query needs (what was this claim's state at 14:32, and who touched it?), so the cost buys something. No for patient demographics — that's a CRUD row, and event-sourcing it is ceremony with no payoff. The costs are eventual-consistency UX, event versioning/replay pain, and 'where's the current state' debugging." The judgment is in the no.
"Producer wrote to the DB but the event was lost — how do you prevent it?"
- Junior: "wrap both in a try/catch."
- Senior: "that's the dual-write problem — Kafka isn't in the DB transaction. Write the event to an outbox table in the same DB tx, relay it via a poller or CDC, and set
acks=allwithmin.insync.replicas=2so an unreplicated write isn't silently lost." Names both the atomicity gap and the durability gap.
Exercises & the Pulsely increment
Do these in code — the bugs only teach when you watch them happen.
-
Stand up the log and prove independent readers. Run Kafka locally, create
pulsely.clinical.events(RF1 dev, ≥4 partitions). Produce clinical events with KafkaJS. Run two consumer groups —chart-timelineandpopulation-analytics— and prove both see every event independently, each with its own committed offsets. This is §1's first pain, dissolved. -
Pick and justify a partition key (ADR fuel). Run a load script keyed by
patient_idwith one "high-volume monitored patient" (a continuous device) producing 80% of events. Watch one partition's lag explode while others idle. Re-key (or salt the hot key) and watch it balance. Capture both observations and the decision in ADR decision 2 —patient_idvsencounter_idvs random, with the ordering/skew consequence of each. -
Force a rebalance storm, then fix it. Put a
sleepin the handler longer thanmax.poll.interval.ms. Observe the eviction, the reassignment, and the duplicate processing. Fix it two ways: manual commit-after-process plus an idempotent UPSERT into the timeline projection (so duplicates are harmless), and a smaller batch / longer interval / heartbeat (so they don't happen). Watch the storm stop. -
Replay to rebuild, and prove isolation. Corrupt the chart-timeline cache on purpose. Reset only the
chart-timelinegroup's offsets to earliest and rebuild the timeline from the log. Prove two things: the rebuild is idempotent (running it twice yields the same timeline), and thepopulation-analyticsgroup is completely unaffected (its offsets never moved). This is the log's superpower, demonstrated. -
Write both ADRs. (1) Kafka log vs a queue for clinical activity — context (chart-timeline + analytics + future search all want every event, plus the replay and HIPAA-history requirements), options, decision (log), rejected (queue: less weight but no fan-out or replay), reversal trigger (drop to a queue if only one consumer ever needs activity and replay becomes worthless). (2) Partition key for
pulsely.clinical.events— the three candidates, the decision (patient_id, salt high-volume device keys), and the documented ordering tradeoff.
Key takeaways
- A queue forgets, a log remembers. A queue has competing consumers and destructive reads (the broker owns "who dealt with this"); a log has independent readers and non-destructive, replayable cursors (the reader owns "how far I've read"). Choose by ownership of progress, never by "which is faster" — Kafka is not just a scalable queue.
- A topic is N ordered partitions, with no global order. Ordering is guaranteed only within a partition, so the partition key is both your ordering boundary and your skew risk — key by the entity whose order you must preserve (a
preliminary → finalresult flip is a safety bug), salt or re-key hot keys. - Offsets are committed by the consumer, and "committed" ≠ "processed." Commit before processing = at-most-once; commit after = at-least-once (the sane default). Manufacture effectively-once with idempotent consumers (Ch 25) — never chase exactly-once at the broker.
- Retention is consumption-independent (set it by how long you might replay and how long the law makes you keep the audit trail); compaction turns a log into a key→latest-value changelog;
acks=all+min.insync.replicas=2+ RF3 is the durable default, and it's the quorum reasoning you've already met in Kafka's clothing. - Consumer lag = log-end-offset − committed-offset is the pipeline's heartbeat — bounded/falling is healthy, monotonically rising is sick (and on a critical-value pipeline, dangerous).
- The outbox is mandatory because Kafka isn't in your DB transaction; replay is the log's superpower and a self-DDoS footgun against external side effects (re-submitted claims, re-fired reminders) — keep side-effecting consumers separate from rebuild-from-history projections.
- Events are facts (producer-owned), commands are intent (target-owned). Build event-driven flows with choreography for loose coupling, orchestration/sagas with compensating actions when failure handling gets complex (denial → reverse the A/R, open an appeal).
- Adopt CQRS and event sourcing with skepticism: event-source the claim lifecycle (audit + state machine earn it), keep patient demographics CRUD. The senior signal is knowing when not to.
← Previous: Ch 26 — Queues & Background Processing · Up: Part V overview · Master TOC · Next: Ch 28 — Realtime & Streaming Backends →