Course contents

07. Messaging and Event-Driven Systems Lesson 4 of 10

Event Streaming

Logs instead of queues: append-only records with offsets, consumers that track their own position, replay from any offset, retention and compaction.

15 minIntermediate7 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A queue deletes a message once it is processed; a log keeps every event for a retention period.
  • Events are appended with increasing offsets into segments; nothing is changed by reading.
  • Each consumer owns one number per partition, its committed offset; lag = end offset − committed offset.
  • Consumers can start anywhere in the retained log: backfills and reprocessing are just offset resets.
  • Retention deletes old segments regardless of readers; compaction keeps the latest record per key.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

An event stream is an append-only, ordered log of records. Producers add records at the end; each record gets the next offset in its partition. Consumers read from any offset they choose and keep reading as new records arrive. Reading does not remove anything: records stay until a retention limit deletes them (or compaction replaces them). Apache Kafka is the best-known implementation; Redpanda, Amazon Kinesis Data Streams, Azure Event Hubs, Apache Pulsar and NATS JetStream offer the same model.

Why it exists

A message queue is a to-do list: once a job is done, it is deleted. That is right for work, but many systems need the events themselves: several services react to the same "order placed", a new service needs last month’s orders to build its database, a buggy consumer must reprocess yesterday after a fix, a cache or search index must be rebuilt from scratch. A log keeps the facts in order and lets every reader move through them at its own pace, so producers and consumers are decoupled not only in time but also in number and in history.

How it works

Appending. Each partition is a sequence of records with offsets 0, 1, 2… Records are immutable. On the broker the partition is stored as segment files; only the newest (active) segment is written to, older ones are closed. Appends are sequential writes, and reads of recent data are usually served from the operating system’s page cache, which is why logs sustain high throughput on ordinary disks.

Reading. A consumer asks for records starting at an offset and receives them in order. It records progress by committing an offset (in Kafka, to the internal __consumer_offsets topic, per group and partition). After a restart it resumes from the committed offset. Different consumers, or different consumer groups, have independent offsets: each sees every record.

Lag. Consumer lag is the log end offset minus the committed offset: how much has been written but not yet processed. Expressed in time (how old the oldest unprocessed record is), it tells you directly how stale the consumer’s view is.

Replay. Because records are kept, a consumer can start anywhere: a new group with auto.offset.reset=earliest starts at the oldest retained record, latest starts at the end, and tools such as kafka-consumer-groups --reset-offsets move an existing group to a timestamp or offset. Reprocessing is safe only if processing is idempotent.

Retention. Brokers delete whole closed segments once they are older than retention.ms (Kafka default: 7 days) or the partition exceeds retention.bytes (unlimited by default). Deletion ignores consumers: a consumer whose committed offset was deleted gets an out-of-range error and falls back to its reset policy, skipping what was lost. Tiered storage (KIP-405, production-ready since Kafka 3.9) can move old segments to object storage for long retention at lower cost.

Compaction. With cleanup.policy=compact, a background cleaner rewrites closed segments and keeps at least the latest record per key. Offsets do not change; they get gaps. A record with a null value (tombstone) deletes its key after delete.retention.ms. A compacted topic is a replayable table of current state, used for changelogs, configuration and Kafka’s own consumer offsets.

When to use it

  • Several independent consumers need the same events (analytics, search, notifications, audit).
  • You need replay: backfilling new services, rebuilding read models, reprocessing after bugs.
  • Event sourcing or change data capture, where the history is the source of truth or feeds other stores.
  • High-throughput pipelines where per-key order matters.

When not to

  • Independent jobs that each need one worker, per-message retries, delays and priorities: a work queue does this more simply.
  • Low-volume request/response between two services: an API call is simpler.
  • Data that must be deleted on request (personal data) without a plan: immutable logs need compaction with tombstones, short retention or encryption-key deletion to honour erasure.

Trade-offs

Choice You gain You pay
Log instead of queue Replay, many independent readers, per-partition order Consumers manage offsets; no per-message ack, delay or priority
Long retention Longer replay window and outage tolerance Storage, slower recovery of replicas (less with tiered storage)
Short retention Cheap, small Slow or offline consumers lose events
Compaction Complete latest state per key, bounded size Full history lost; tombstones and timing to understand
Auto-commit of offsets Simple Possible loss or duplicates around crashes

Alternatives

  • Work queues (RabbitMQ, SQS, Azure Service Bus queues): per-message acknowledgement, retries, delays and dead-lettering, no replay.
  • Pub/sub with durable subscriptions (SNS + SQS, Google Pub/Sub): every subscriber gets each message, limited replay (Pub/Sub supports seek within its retention).
  • Database tables plus polling or CDC: the table is the history; Debezium-style CDC turns it into a stream.

Failure modes

  • Consumer slower than retention: silently skips data after an offset reset. Alert on lag in time against retention.
  • Replay side effects: reprocessing re-sends emails or charges cards unless handlers are idempotent.
  • Wrong reset policy: latest on a new group skips everything already in the log; earliest on a huge topic floods a new consumer.
  • Disk full: retention by time alone with a traffic spike can fill broker disks; set size limits or alerts.
  • Poison record: a record that crashes the consumer blocks progress on its partition until handled.

In production

Decide retention from the longest replay you need (backfills, outages, audits), not from defaults. Monitor per-partition lag in records and seconds. Commit offsets after processing, and make processing idempotent so replays are safe. Use schemas (a schema registry with compatibility rules) because old events will be read by new code. For state-like topics, use compaction and document tombstones. Keep an explicit runbook for offset resets.

Common misconceptions

  • "Kafka is a queue." It is a log: reading does not remove, and consumers track their own position.
  • "Consumers that have not read an event keep it alive." Retention deletes by time or size regardless.
  • "Compaction keeps only one record per key." It keeps at least the latest; recent records in the active segment are not compacted yet.
  • "Replay is free." Replay re-runs side effects; it needs idempotent consumers.

Interview angle

When you introduce Kafka in a design, say why a log rather than a queue: multiple consumers, replay, ordering per key. Mention retention sizing and lag monitoring, and how a new service backfills from the log. Explaining offsets, committed position and the effect of retention on a lagging consumer shows you understand the model rather than the product name.

Model assumptions

The simulation in this lesson is a simplified model, not a benchmark. The Orders service produces 20 events per second at random (Poisson). In the first step a queue deletes each message when Billing acknowledges it. From the second step the log is modelled as a topic that copies each event into one queue per consumer; that queue’s depth stands for the consumer’s lag. A real log stores each event once and keeps one offset per consumer. Billing has 2 slots at about 30 ms per event, Analytics 2 slots at about 45 ms, Search 6 slots at about 30 ms (lognormal, cv 0.3). Search starts with no processing slots until 1.5 s into its step, so the backlog built up until then stands for the history it replays. Segments, offsets, retention, the offset-out-of-range reset and compaction are scripted illustrations with example numbers, not simulated. Not modelled: partitions (see the next lessons), disk and page cache, replication. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. A queue forgets what it delivered

    Start with what you know from message queues: the Orders service puts each "order placed" message on a queue, and Billing takes and acknowledges it. On acknowledgement the queue deletes the message.

    The queue stays near empty: it holds only work not yet done. That is perfect for jobs. But a month later, when a new service wants every order since January, or Billing needs to re-run last Tuesday after a bug fix, there is nothing left to read.

    Scene: The Orders service sends 20 messages per second to a queue. Billing processes and acknowledges each one, and the queue deletes it, so the queue stays near empty.

    Key idea: A queue holds work until it is done, then deletes it. History is not kept.

  2. 2. A log keeps every event, in order

    Replace the queue with an event stream: an append-only log. Every event is added at the end and gets the next offset (0, 1, 2…). Nothing is changed or removed when it is read.

    On disk the log is a series of segments. Only the newest, active segment is written to; older segments are closed and immutable. The animation shows each append landing in the active segment.

    Billing now reads the log instead of a queue. The queue next to it shows Billing’s lag: events written but not yet processed. It stays near zero.

    Scene: The Orders service appends events to the Orders log. An illustration shows each append going to the active Segment 2; Segments 0 and 1 are closed. Billing reads the log and its lag stays near zero.

    Key idea: A log appends events with increasing offsets and keeps them after they are read.

  3. 3. Each consumer keeps its own offset

    Analytics starts reading the same log. It does not take events away from Billing: the log hands every event to every reader, because reading does not remove anything.

    What each reader owns is a single number, its offset: how far it has read. Billing has processed up to offset 2,317, Analytics up to 2,290. Each commits its offset back to the broker, so after a restart it continues where it stopped.

    Lag is simply log end offset minus committed offset. The broker stores each event once, however many readers there are.

    Scene: Billing and Analytics both read every event from the Orders log. Each tracks its own committed offset; both lags stay small.

    Key idea: Consumers are independent readers of one log, each tracking its own offset; lag = end offset − committed offset.

  4. 4. Replay history from offset 0

    A new Search service needs every order, including old ones, to build its index. It starts with its offset set to the beginning of the log (auto.offset.reset=earliest for a new group, or an explicit seek). The animation shows it reading the oldest segment first, then the next, then the active one.

    In the simulation, Search starts at 1.5 s with a backlog of about a hundred events, its "history". It reads faster than new events arrive, so its lag drains to zero: it has caught up and continues live. Billing and Analytics are not affected.

    The same mechanism repairs mistakes: after fixing a bug, Billing can reset its offset to yesterday and reprocess, provided its processing is idempotent.

    Scene: A Search consumer is added and reads the log from offset 0; an illustration shows reads from Segment 0, then 1, then 2. In the simulation its backlog of about a hundred events drains within seconds, while Billing and Analytics continue unaffected.

    Key idea: Because the log keeps events, a consumer can start from any retained offset: new services backfill, fixed services reprocess.

  5. 5. Retention deletes old segments, read or not

    A log cannot grow forever. Retention deletes whole closed segments once they are older than a limit (Kafka’s default is 7 days) or the partition exceeds a size limit. Segment 0 has expired and is gone.

    Retention does not wait for consumers. An Audit job that last ran weeks ago asks for offset 120, which no longer exists. The broker answers offset out of range, and the consumer falls back to its reset policy: here earliest, the first offset still kept, in Segment 1. Everything between was skipped, silently unless you alert on it.

    Set retention longer than the longest outage or replay window you need, and monitor lag in time, not just in events.

    Scene: Segment 0 has been deleted by retention. In an illustration, the Audit job asks for offset 120, receives an out-of-range error, resets to the earliest offset still kept and reads from Segment 1.

    Key idea: Retention removes old data on a schedule; a consumer slower than retention loses events.

  6. 6. Compaction keeps the latest value per key

    Some streams are better kept by key than by time. A topic with cleanup.policy=compact, for example customer profiles, keeps at least the latest record for every key and lets older ones go.

    The log cleaner rewrites closed segments in the background. Customer 17 was updated three times (v1, v2, v3); after cleaning, only v3 remains in the old segment. Offsets do not change, they just have gaps. A record with an empty value (a tombstone) deletes the key after a grace period.

    A compacted topic is a replayable snapshot of current state: a new service reads it from the start and gets one value per key. The active segment is never compacted, so recent history is always there.

    Scene: An illustration of compaction: the log cleaner reads closed Segment 1 and rewrites it keeping only the latest record per key, for example only version 3 of customer 17. The active segment is untouched.

    Key idea: Compaction trades full history for a complete, replayable latest state per key.

  7. 7. Queue or log?

    A queue is a to-do list: each message is work for one consumer and disappears when done. A log is a record of facts: events are kept for a retention period, in order, and any number of consumers read them at their own pace from their own offsets.

    Pick a log when several services need the same events, when you need replay (backfills, reprocessing, rebuilding state) or when order per key matters. Pick a queue for independent jobs, per-message retries and delays. The next lessons look at how logs scale: partitions, consumer groups and ordering.

    Scene: The Orders log with its segments is read by Billing, Analytics and Search, each at its own offset. All lags stay near zero.

    Key idea: Queues distribute work and forget it; logs keep ordered history that every consumer can read and re-read.