← Building blocks

Keep events as a replayable log

Decoupling & async worksenior

Consumers need to re-read history, or new consumers need to catch up from the start.

Say it like this

I need consumers to replay history and new consumers to catch up, so instead of a queue that deletes on ack I keep an append-only log partitioned by key, and each consumer owns its offset.

Basic solution

Use a partitioned, append-only log with retention. Consumers track their own offset and can rewind.

KafkaPulsarKinesisRedpanda

Partitioned log with independent consumer groups

The producer hashes each key to a partition, and events stay in order within it. Every consumer group reads all partitions and keeps its own offset in each, so the archive can lag and the trainer can replay from zero without touching the live reader. Inside one group, each partition is read by one instance at a time.

How it works

  1. A producer appends an event to a topic with a partition key, such as the region id. The broker hashes that key to choose one of the topic's partitions and appends the event to the end of that partition, giving it the next offset: a number that increases by one per event within the partition.
  2. Each partition is an ordered, immutable file on disk; events are only ever appended, never modified. The broker copies each partition to other brokers (replication) so a lost disk does not lose events.
  3. Consumers read as a consumer group. The broker assigns each partition to exactly one consumer in the group, and that consumer reads its partitions sequentially, starting from the offset the group last committed.
  4. After processing a batch, the consumer commits its new offset back to the broker. If the consumer crashes before committing, the next consumer re-reads from the last committed offset, so a batch can be processed twice: this is at-least-once delivery.
  5. Retention (by time or size) deletes the oldest segments of each partition. Within the retention window any consumer group can rewind to any offset to reprocess, and a brand-new group can start from the beginning of the log or from the end.

What falls out of the design

  • Ordering is guaranteed only within a partition, because that is the only thing the broker appends to in order; events for the same key land in the same partition, so they stay ordered.
  • Parallelism is capped by the partition count, because one consumer owns each partition. Ten partitions means at most ten active consumers in a group.
  • Reads and writes are sequential disk I/O, which is why a log sustains millions of events a second on ordinary disks.

Worked example

Ride matching location stream

  • 1M active drivers × one update per 4 s = 250K events/s, 100 B each = 25 MB/s.
  • Partition by region id (say 400 regions) so all updates for one region are ordered and land on the location service shard for that region.
  • Retention 24 h ≈ 2.1 TB; three replicas ≈ 6.5 TB of disk across the cluster. Routine.
  • Consumers: the live location service (reads the head), the archive sink (reads at its own pace), and an ETA model trainer added months later that replays the last 24 h from offset zero.
  • Consumer lag alert at 30 s for the live service, because a position older than that is useless for matching.

Variants and when each wins

Kafka / Redpanda

  • The reference implementation: partitions, consumer groups, long retention and exactly-once processing with transactions, plus the most operational knobs. It wins when you need replay, several consumer groups, or sustained high throughput and can run a cluster.

Kinesis / Pub/Sub (managed)

  • The same model run by a cloud provider, with tighter limits on retention and on throughput per shard, billed per shard-hour. It wins when you want the log without operating it and your volume fits the per-shard limits.

Pulsar

  • Separates the serving layer from storage (BookKeeper), so partitions are easier to rescale and old data can be tiered to object storage automatically. It wins when you have many topics or very long retention.

Database table as a log

  • An append-only events table with a sequence column, which consumers poll with WHERE id > last_seen. It wins while you are small (a few thousand events a second) and want the events in the same transaction as your data.

Reach for Kafka when you need replay, multiple consumer groups or sustained high throughput; use a database table while you are small.

Failure modes

Hot partition

  • One consumer runs at 100% CPU while the others idle, and lag grows on a single partition. It happens because the partition key is skewed: one mega-city region produces far more events than any other, and all of them land in the same partition. Add a salt (a small random suffix) to the hottest keys to spread them across partitions, or split the region into smaller cells.

Consumer rebalance storms

  • Consumption pauses for several seconds every time a worker joins or leaves the group. It happens because the broker reassigns every partition on each membership change, and no consumer reads during the reassignment. Use cooperative or sticky assignment so only the affected partitions move, run fewer larger consumers, and use static membership so a restart is not treated as a departure.

Retention expires before a consumer catches up

  • A consumer that was down for three days comes back and silently skips a day of data. It happens because retention was shorter than the outage, so the broker deleted segments the consumer had not read, and the consumer resumed from the oldest offset that still existed. Keep retention longer than your worst recovery time, alert when lag approaches retention, and archive the stream to object storage so it can be replayed from there.

Unbounded partition growth with the wrong key

  • You need more consumers but cannot add partitions without breaking ordering. It happens because the partition count was set for day one, and changing it changes which partition each key hashes to, so events for one key would split across old and new partitions. Over-provision partitions up front (consumers can be fewer than partitions), or migrate by writing to a new topic with more partitions and switching consumers over.

Duplicates after a crash

  • Counts come out slightly high after a deploy. It happens because the consumer commits its offset after processing, so a crash between processing and commit makes the next consumer reprocess that batch. Make the consumer idempotent, keyed on (partition, offset), or use the broker's transactions to commit the output and the offset together where the sink supports it.

Interviewer follow-ups

Answer out loud before you open each one.

How do you pick the partition key?

By the entity whose events must stay ordered and co-located: conversation id for chat, author id for posts, region for locations. Check its cardinality and skew first; a key with a few giant values gives hot partitions no matter how many you create.

How many partitions?

More than your peak consumer parallelism with headroom for growth, because consumers cannot exceed partitions and changing the count breaks key-to-partition mapping. Tens to low hundreds per topic is normal; thousands have overhead.

Can you get exactly-once?

Within the log, yes, via idempotent producers and transactions that commit offsets and outputs together. The moment a consumer calls an external system such as an email provider you are back to at-least-once plus deduplication on your side.

What is the difference between this and a database change stream?

A change stream (CDC) is a log of row changes produced by the database itself. An event log holds domain events you define. CDC is great for syncing derived stores; domain events are better for other teams because they carry intent, not table diffs.

Connections

In study paths
Decoupling with events
Built on
Write-ahead log
Pairs with
Fan one event out to many consumers · Compute over events as they arrive · React to database changes · Publish events reliably with the write · Make retries safe
Pulls against
Decouple producer from consumer
Used in
Ride Matching (Uber / Lyft) · URL Shortener (TinyURL / bit.ly)

The same parts on other clouds

The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon EC2 Auto ScalingDriver gateway, Location serviceCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon MSK (Kafka)Topic: driver-locationsManaged Service for Apache KafkaEvent Hubs (Kafka API)Confluent Cloud, Redpanda
Amazon S3Archive sinkCloud StorageBlob StorageCloudflare R2, MinIO, Ceph
Amazon SageMakerETA trainerVertex AIAzure Machine LearningKServe, Ray Serve, NVIDIA Triton