Skip to content

Lesson 17 of 38Distributed systems

Logs, Kafka, and Stream Processing

How Kafka-style logs, partitions, and consumer groups really work, what exactly-once means, and how windows, event time, and watermarks turn streams into answers.

20 min read0/5 questions

The fraud team wants to block a card within seconds of the fifth failed payment in a minute. Marketing wants a live dashboard of sign-ups per region. The search index must reflect a price change before the customer refreshes. A nightly batch job answers all three questions about twelve hours too late. Stream processing answers them continuously, over data that never stops arriving, and Kafka (or something shaped like it) sits at the centre of most of these systems. Message Queues introduced logs, consumer groups, and ordering by key. This lesson goes under the hood: what partitions cost you, what "exactly-once" actually covers, and how windows, event time, and watermarks let you count things in a stream that arrives late and out of order.

The log is the primitive

A Kafka topic is a named log split into partitions. Each partition is an append-only file on disk (really a series of segment files). Every record gets an offset: its position in that partition, 0, 1, 2, and so on. Records are never edited. Consumers do not delete what they read; each one just remembers the offset it has reached.

Because reading does not remove anything, the same data can feed many independent readers, and any of them can replay from an old offset to rebuild state, backfill a new service, or recover from a bug. How long records stay is a per-topic choice:

  • Time or size retention. Delete segments older than retention.ms (7 days by default) or beyond a size cap. Good for event streams: clicks, page views, payments.
  • Log compaction (cleanup.policy=compact). Keep at least the latest record per key, and discard older ones in the background. A compacted topic of user_id -> profile behaves like a table you can replay. To delete a key, write a tombstone: the key with a null value. Compacted topics are how Kafka Streams stores state changelogs and how CDC tools publish "the current row".

Think of a compacted topic as a database table's changelog, and a retained topic as a database's write-ahead log with an expiry date. That framing is the whole idea behind "the log as the primitive": databases, caches, and search indexes can all be derived from it.

Partitioning by key, and what it costs

A producer picks a partition for each record. With a key, the default is hash(key) mod partition_count (Kafka uses the murmur2 hash). Without a key, the producer spreads batches across partitions. Ordering is guaranteed only within a partition, so every event for order-81 lands in one partition, in the order it was written, while other orders flow in parallel.

Choosing the key is a design decision with three consequences:

  • It decides what is ordered. Key by account_id and an account's deposits and withdrawals stay in sequence. Key by transaction_id and they do not.
  • It decides the load spread. A key with a few huge values (one celebrity's user_id, one merchant doing half your volume) makes a hot partition. One broker and one consumer do most of the work while the rest idle. Fixes are a finer key (merchant_id + day) or salting the key and re-aggregating later, at the cost of per-key ordering.
  • It fixes the partition count, in practice. You can add partitions to a topic, but never remove them, and adding them changes hash mod N, so new events for a key may land on a different partition from its older ones. Ordering for that key breaks across the change. Teams size partitions for a few years of growth up front (it is cheap to have more than you need, within reason), or create a new topic and migrate.
Keys, partitions, and one consumer group
Checkout service: producerCheckout serviceproducerPartition 0: ordersPartition 0ordersPartition 1: ordersPartition 1ordersPartition 2: ordersPartition 2ordersConsumer 1: group: billingConsumer 1group: billingConsumer 2: group: billingConsumer 2group: billingConsumer 3: idleConsumer 3idlekey adakey zoekey lin

The producer hashes each key. Every event for ada goes to partition 0, so Ada's cart, pay, and ship events stay in order.

1/4

Consumer groups, offsets, and lag

A consumer group is a set of consumers sharing the work of reading a topic. Kafka assigns each partition to one member. Different groups are independent: billing and analytics each read every record at their own pace.

Three operational facts matter more than the API:

  • Max parallelism is the partition count. Twelve partitions and twenty consumers means eight idle consumers. This is the most common capacity surprise.
  • Rebalancing pauses work. When a member joins, leaves, or misses heartbeats, partitions move. The old "eager" protocol stopped every consumer during a rebalance. The cooperative sticky assignor moves only the partitions that must move. Kafka 4.0 made the newer consumer group protocol (KIP-848) generally available, which moves the rebalance logic to the broker and avoids the group-wide pause. Long processing that exceeds max.poll.interval.ms gets a consumer kicked out, which triggers yet another rebalance: a classic death spiral.
  • Consumer lag is the metric that matters. Lag is the latest offset in a partition minus the group's committed offset. Rising lag means consumers are falling behind. Alert on lag that keeps growing, or better on time lag (how old the oldest unprocessed record is), since 10,000 records means very different things on different topics.

When you commit decides your delivery semantics. Commit before processing and a crash loses the records (at-most-once). Commit after processing and a crash reprocesses them (at-least-once). Auto-commit (enable.auto.commit=true, the default) commits on a timer based on what poll() returned, not what you finished. That is fine for a simple loop that processes each batch before polling again, but if you hand records to a thread pool it can commit work that never completed. Teams that care commit manually, after the work is durable.

Run this simulation: three keys over three partitions, a group assignment, and a consumer that crashes before committing.

Pythonconsumer_group.py
from zlib import crc32 PARTITIONS = 3 def partition_for(key: str) -> int: # Kafka uses murmur2; any stable hash shows the idea. # Python's built-in hash() is randomised per process, so never use it here. return crc32(key.encode()) % PARTITIONS events = [("ada", "cart"), ("zoe", "cart"), ("ada", "pay"), ("lin", "cart"), ("zoe", "pay"), ("ada", "ship"), ("lin", "pay"), ("zoe", "ship")] log = {p: [] for p in range(PARTITIONS)}for key, action in events: p = partition_for(key) log[p].append(f"{key}:{action}") # the offset is the list index for p, msgs in log.items(): print(f"partition {p}: {msgs}") def assign(consumers): owners = {c: [] for c in consumers} for p in range(PARTITIONS): owners[consumers[p % len(consumers)]].append(p) return owners print("\n2 consumers:", assign(["c1", "c2"]))print("4 consumers:", assign(["c1", "c2", "c3", "c4"])) # At-least-once: process, then commit. Crash between the two and you reprocess.committed = {p: 0 for p in range(PARTITIONS)}def poll(p, crash_after=None): for offset in range(committed[p], len(log[p])): print(f" p{p} offset {offset}: {log[p][offset]}") if offset == crash_after: print(" crash before commit!") return committed[p] = offset + 1 busy = max(log, key=lambda p: len(log[p]))print(f"\nconsumer reads partition {busy}, crashes at offset 1")poll(busy, crash_after=1)print(f"replacement consumer starts from committed offset {committed[busy]}")poll(busy)
Output
Press Run (⌘ Enter) to see what happens.

Notice ada:pay is processed twice. Every at-least-once consumer must be ready for that.

Quick check
A topic has 6 partitions. Lag is climbing, so the team scales the consumer group from 6 to 10 pods. What happens?
Need a nudge? A hint rules out a wrong answer.

Delivery semantics and the exactly-once myth

On the producer side, durability comes from three settings working together:

  • acks=all: the leader waits until all in-sync replicas have the record before acknowledging.
  • min.insync.replicas=2 on a topic with replication factor 3: if fewer than two replicas are in sync, writes are refused rather than accepted with weak durability. The broker default is 1, which quietly makes acks=all mean "one copy".
  • The idempotent producer: each producer gets an id and numbers its records per partition, so the broker drops a retry it has already written. No duplicates from producer retries, and no reordering.

Since Kafka 3.0, acks=all and idempotence are the producer defaults. min.insync.replicas is still yours to set.

Transactions go one step further. A producer with a transactional.id can write to several partitions and commit the consumer's input offsets as one atomic unit. Consumers configured with isolation.level=read_committed (the default is read_uncommitted) see only committed transactions. Kafka Streams turns this on with processing.guarantee=exactly_once_v2.

Here is the part that interviews test. Kafka's exactly-once covers read-process-write within Kafka: read from a topic, compute, write to a topic, commit offsets. The moment your processing has an effect outside Kafka (charging a card, sending an email, writing to Postgres), Kafka's transaction cannot cover it. If the consumer crashes after the email but before the commit, the record is processed again and the email goes twice. For external effects you are back to at-least-once plus idempotency: an inbox table, an idempotency key, or an upsert keyed by the event id. A clean variant for databases: store the consumed offset in the same database transaction as the result, and on startup seek to the stored offset.

Put it in order5 steps

Order the steps of an exactly-once read-process-write loop inside Kafka.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Kafka as a queue: share groups

Classic consumer groups tie parallelism to partitions and track one offset per partition, so one slow record blocks everything behind it. That is fine for ordered streams and awkward for job queues. Share groups (KIP-932) fix this. Consumers in a share group take records cooperatively from the same partitions, acknowledge each record individually, and a record that is not acknowledged within its lock time is redelivered, up to a delivery-count limit. You can run more consumers than partitions. You give up per-key ordering. Share groups were early access in Kafka 4.0, preview in 4.1, and production-ready in 4.2 (February 2026). Check your managed provider's support before you design around them.

Kafka (consumer groups)Kafka (share groups)Amazon SQSRabbitMQ
ModelPartitioned logLog, queue-style consumptionManaged queueBroker with queues and exchanges
OrderingPer partitionNone guaranteedNone (standard), per group (FIFO)Per queue, single consumer
ParallelismUp to partition countBeyond partition countEffectively unlimitedConsumers per queue
AckOffset per partitionPer recordPer messagePer message
ReplayYes, from any retained offsetYes, the log is retainedNoOnly with RabbitMQ Streams
Best forEvent streams, CDC, ordered processingJob queues on existing KafkaSimple background jobs on AWSRouting, priorities, RPC-style work

Stream processing: state, windows, and joins

Some stream operations are stateless: filter out test accounts, map a raw click to a clean event, route by country. Each record is handled on its own, so scaling is trivial.

The interesting ones are stateful: count clicks per ad per minute, sum spend per card per hour, join a payment to the order it belongs to. These need memory that survives crashes. Kafka Streams keeps state in a local RocksDB store backed by a compacted changelog topic, so a restarted instance can rebuild it. Flink keeps state in memory or RocksDB and takes periodic checkpoints: it injects barriers into the stream, each operator snapshots its state when the barrier passes, and after a failure the whole job restores the last checkpoint and replays input from the matching offsets. With a transactional sink, that gives exactly-once results, again only where the sink can join the protocol.

Joins come in two main shapes. A stream-table join enriches each event with the current value of a table (attach the customer's tier to each order). A stream-stream join matches events from two streams within a time window (a payment within 10 minutes of its order).

Counting needs windows, because "how many clicks?" has no answer on an infinite stream.

WindowShapeExample
TumblingFixed size, no overlap, every event in exactly one windowClicks per ad per minute, for billing
HoppingFixed size, advancing by a smaller step, so windows overlap5-minute average updated every minute
SlidingDefined by the time gap between events, evaluated as events arrive"5 failed payments within any 60 seconds"
SessionPer key, closed after a gap of inactivityOne browsing session ends after 30 idle minutes

Naming varies: Flink calls hopping windows "sliding". Say the shape, not just the name.

Match the pairs0/4 matched

Match each requirement to the window that fits it.

Choose an item, then its match on the other side.

Event time, watermarks, and late data

A phone in a tunnel records a click at 12:00:58 and sends it at 12:03:10. Which minute does it belong to? Processing time is when your system sees the event. Event time is when it happened. Windows by processing time are easy and wrong: a network blip moves clicks into the wrong minute, and replaying yesterday's data puts every event into the current windows. Real pipelines window by event time.

The difficulty is knowing when a window is complete. Events arrive out of order, so you can never be certain no more 12:00 events are coming. A watermark is the processor's estimate: "I believe no events older than time T will arrive now." The common strategy is bounded out-of-orderness: watermark = the highest event time seen, minus an allowed delay. When the watermark passes a window's end, the window fires and emits its result.

An event that shows up after its window fired is late. You choose what happens: drop it, send it to a side output for a correction job, or keep windows open longer (Flink's allowed lateness, Kafka Streams' grace period) and emit an updated result. A bigger delay means more complete answers but slower ones. That latency versus completeness trade-off is the core decision in every streaming design.

Tumbling 60 s windows, watermark = max event time minus 10 s
5
0
20
1
58
2
watermark = 48window 0-60 = 3

Three events land in window 0-60. The watermark is 58 - 10 = 48, so the window stays open.

1/4

Run the full version and change MAX_DELAY.

Pythonwatermarks.py
WINDOW = 60 # tumbling one-minute windows, by EVENT timeMAX_DELAY = 10 # we expect events to be at most 10 s out of order # (event_time_seconds, click_id) in the order they ARRIVE at the processorarrivals = [(5, "a"), (20, "b"), (58, "c"), (63, "d"), (55, "e"), (71, "f"), (50, "g"), (95, "h"), (130, "i")] open_windows = {} # window start -> countfired = set()max_seen = 0 for event_time, click in arrivals: start = event_time - event_time % WINDOW if start in fired: print(f"t={event_time:>3} {click} LATE: window {start}-{start + WINDOW} already emitted -> side output") continue open_windows[start] = open_windows.get(start, 0) + 1 max_seen = max(max_seen, event_time) watermark = max_seen - MAX_DELAY print(f"t={event_time:>3} {click} -> window {start}-{start + WINDOW} watermark={watermark}") for s in sorted(open_windows): if s + WINDOW <= watermark: # nothing older can arrive (we assume) print(f" EMIT window {s}-{s + WINDOW}: {open_windows.pop(s)} clicks") fired.add(s) print("still open at shutdown:", open_windows)
Output
Press Run (⌘ Enter) to see what happens.

One trap to know: a watermark only advances when events arrive. A partition that goes quiet holds back the watermark for the whole job (the job takes the minimum across inputs), and windows stop firing. Flink handles this with an idleness timeout on the watermark strategy.

Predict the outputPython

Same events, but MAX_DELAY is 0, so the watermark equals the highest event time seen. How many clicks does window 0-60 emit?

WINDOW, MAX_DELAY = 60, 0
arrivals = [5, 20, 58, 63, 55, 71, 50]
counts, fired, max_seen = {}, {}, 0
for t in arrivals:
  start = t - t % WINDOW
  if start in fired:
      continue                      # late: dropped
  counts[start] = counts.get(start, 0) + 1
  max_seen = max(max_seen, t)
  for s in sorted(counts):
      if s + WINDOW <= max_seen - MAX_DELAY:
          fired[s] = counts.pop(s)
print(fired[0])
Need a nudge? Hints walk you through it.

Tools, Lambda and Kappa, and CDC

The three engines you will meet:

  • Kafka Streams: a Java library inside your own service. No cluster to run; scales by running more instances of your app. Kafka in, Kafka out.
  • Apache Flink: a separate cluster (or a managed service) for large stateful jobs, many sources and sinks, event-time processing done thoroughly. Also offers Flink SQL.
  • Spark Structured Streaming: streaming on the Spark engine, micro-batch by default. A natural fit if your team already runs Spark for batch.

Lambda architecture runs a fast streaming path for fresh, approximate results and a batch path that recomputes exact results later, then merges them. It works, but you write the logic twice. Kappa architecture keeps only the stream: when the logic changes, replay the retained log through the new version. Kappa is the default for new systems now. Lambda survives where money is involved, as a deliberate nightly reconciliation against the streaming numbers.

Change data capture is the bridge from databases into this world. Debezium reads Postgres or MySQL's write-ahead log and publishes every insert, update, and delete as an event, usually to a compacted topic keyed by primary key. That is how search indexes, caches, and analytics stay in sync without dual writes, as Sagas, Outbox, and Two-Phase Commit explained.

Schemas and compatibility

A topic outlives every service that writes to it, so its format needs a contract. Teams encode records with Avro or Protobuf and register each version of the schema in a schema registry. Producers check new schemas against the registry's compatibility rule, and incompatible changes are rejected at deploy time instead of breaking consumers at 3 a.m.

  • Backward compatible (the Confluent registry default): consumers on the new schema can read data written with the old one. Upgrade consumers first. Adding a field with a default is backward compatible.
  • Forward compatible: consumers on the old schema can read data written with the new one. Upgrade producers first.
  • Full: both. Safest for topics with many independent teams.

Renaming a field, or removing a field without a default, breaks one direction. In Protobuf, never reuse a field number.

Quick check
A Kafka Streams app runs with exactly_once_v2. For each order it sends a confirmation email through an email API. The app crashes and restarts. What can happen?
Need a nudge? A hint rules out a wrong answer.
Key terms
partition
One ordered, append-only slice of a topic. Ordering is guaranteed only within a partition.
offset
A record's position in its partition. Consumers commit offsets to remember how far they have read.
consumer lag
How far a consumer group is behind the newest record, in records or in time. The key health metric for consumers.
log compaction
A retention mode that keeps the latest record per key, so a topic can act as a replayable table.
exactly-once semantics
Kafka transactions that commit outputs and input offsets together. Covers Kafka-to-Kafka only; external effects still need idempotency.
watermark
A stream processor's estimate that no events older than a given event time will still arrive, used to decide when a window is complete.
share group
A Kafka consumer group type with per-record acknowledgement and more consumers than partitions, at the cost of ordering.