Summary#
In publish/subscribe (pub/sub), producers publish messages to a topic and every interested subscriber gets its own copy, so one event can drive many independent consumers (fan-out). Event streaming platforms such as Kafka implement this as an append-only log: a topic is split into partitions, each message gets an offset, and consumers track their own position. Consumer groups share a topic's partitions for parallelism, while different groups each read everything. Unlike a traditional broker (RabbitMQ), which deletes messages once consumed, a log retains messages for days or forever, so consumers can replay. Order is guaranteed per partition. Cloud options include SNS, Google Pub/Sub, Kinesis, and managed Kafka.
Why It Exists#
A work queue delivers each message to one consumer. But an event like "order placed" interests many systems: billing, inventory, email, analytics, fraud detection. With point-to-point queues, the producer must know and write to every consumer's queue, and adding a new consumer means changing the producer. Pub/sub inverts that: the producer publishes once, and any number of subscribers attach without the producer knowing. Event streaming goes further and keeps the history, so a new service can process last week's events, and a buggy consumer can rewind and reprocess. This page builds on Message Queues.
How It Works#
The pub/sub model#
- Publisher sends a message to a topic (a named channel, such as
orders). - Subscribers register interest in the topic; each subscription receives every message.
- Publishers and subscribers do not know each other; the broker decouples them.
Within one subscription, the work can still be spread across several worker instances (competing consumers). So pub/sub gives fan-out across subscriptions and load balancing within a subscription.
The pub/sub model, in depth#
Push or pull delivery. In a push subscription the broker calls the subscriber: SNS posts to an HTTP endpoint or invokes a Lambda function, and Google Pub/Sub can push to a URL. Push is simple for the subscriber, but the broker decides the rate, so a slow subscriber needs a buffer or a way to say "slow down", usually by returning errors that trigger backoff. In a pull subscription the subscriber asks for messages when it is ready. Kafka, Kinesis, SQS and Google Pub/Sub pull subscriptions work this way, which gives natural back pressure and efficient batching.
Durable or ephemeral subscriptions. A durable subscription keeps messages while its subscriber is offline: a Kafka consumer group's committed offset, a Google Pub/Sub subscription's backlog, or an SQS queue behind SNS. An ephemeral subscription delivers only to whoever is connected right now. Redis pub/sub is the common example: it is fire-and-forget, so a subscriber that disconnects for two seconds misses those two seconds forever. That sounds bad, but it is often exactly right, as the next example shows.
Filtering. Subscribers rarely want everything. Options, from coarse to fine: separate topics per event type (order-placed, order-cancelled); broker-side filters on message attributes (SNS filter policies, Google Pub/Sub subscription filters, RabbitMQ topic patterns); or consumer-side filtering, where the consumer reads everything and drops what it does not need. Consumer-side filtering costs bandwidth but keeps the broker simple, and it is the normal approach with Kafka.
Worked example: live comments for millions of viewers. A live video service keeps each viewer connected over Server-Sent Events to one of many real-time servers, each holding perhaps 100,000 connections. A new comment is written to the database by a comment service, and every server that has a viewer of that video must receive it. There are three designs, each better than the last:
- Every server subscribes to one global channel. It works, but each server processes every comment on every video, even if none of its viewers are watching. At a large scale, most of that work is wasted.
- Partitioned channels. Hash each video to one of N channels,
hash(video_id) mod N, and have each server subscribe only to the channels of videos its viewers watch. A channel per video would be too many for systems like Kafka, so N is bounded. This only pays off if viewers of the same video land on the same servers. An L7 load balancer (NGINX, Envoy) can route by consistent hashing on the video ID in the request path, so that viewers are co-located. Alternatively, a coordination service (ZooKeeper, etcd) can hold a dynamic video-to-server map, which adds flexibility and operating cost. - A dispatcher instead of subscriptions. A dispatcher service keeps a live map of which servers have viewers for which videos, updated by heartbeats and registrations, and forwards each comment directly to those servers. Routing logic is centralised and can be load-aware, but the map must stay accurate during viral surges, and several dispatcher instances must agree.
For this use case Redis pub/sub is a good fit. It has low latency and handles subscriptions that change every second as viewers switch videos, which Kafka handles poorly because its consumer groups are built for stable assignments. The fire-and-forget delivery is acceptable, because comments are already stored in the database, and a reconnecting client fetches what it missed using the last comment ID it saw.
When the stream is too fast to read. A mega-event can produce 5,000 comments per second. No human reads that, since each comment would be on screen for a few milliseconds. The requirement itself changes: viewers need the feeling of the crowd, not every message. Two responses: sample the stream adaptively (deliver 50% at 100 comments per second and 1 to 2% at 5,000, favouring comments from friends or with many reactions), or switch delivery mode entirely. In the second option, a ring buffer of the latest 100 to 200 comments is snapshotted every second to the CDN origin, and clients poll the CDN and animate the new comments across the interval. Latency rises to 1 to 2 seconds, which nobody notices at that speed, and the CDN does what it does best. The poster sees their own comment instantly through an optimistic local insert. Switching modes needs hysteresis, for example switching to CDN above 100,000 viewers and back only below 70,000, so the system does not flip back and forth.
Topics, partitions and offsets#
In a log-based broker, a topic is divided into partitions. Each partition is an ordered, append-only sequence of records stored on disk and replicated across brokers.
- A producer chooses the partition, usually by hashing the message key (
hash(order_id) % partitions), so all events for one key go to the same partition, in order. Messages without a key are spread across partitions. - Each record in a partition has a sequential offset (0, 1, 2, ...). The offset is its position in the log.
- Consumers read sequentially and commit the offset they have processed. On restart, they continue from the committed offset.
Partitions are the unit of parallelism and ordering: more partitions allow more consumers in parallel; order holds only within a partition.
Partitions and offsets, in depth#
What a record contains. A Kafka record has four optional parts: a key, which decides the partition; a value, the payload; a timestamp, set by the producer or the broker; and headers, key-value metadata such as a trace ID or schema version. Order within a partition comes from the offset, not the timestamp. Timestamps can go backwards when several producers write to the same partition.
How the partition is chosen. With a key, the default partitioner computes a murmur2 hash of the key bytes, modulo the partition count, so the same key always lands on the same partition while the count stays fixed. Without a key, modern clients use a sticky partitioner: they fill a batch for one partition, then move to another. This gives larger batches and an even spread over time, rather than strict round-robin per record. The producer learns from cluster metadata which broker leads each partition and sends batches straight to it.
How a partition is stored. A partition is a directory of segment files. The active segment receives appends, and when it reaches a size (1 GB by default) or an age, it is closed and a new one starts. Each segment has a sparse offset index and a time index beside it, so a consumer asking for offset 5,000,000, or for "the first record after 09:00", finds the byte position with a binary search and a short scan. Retention deletes whole closed segments, which is why deletion is cheap and also why data can outlive its retention time by up to one segment's age.
The offsets that matter.
- Log end offset: the next offset to be written.
- High watermark: the offset up to which all in-sync replicas have the data. Consumers can read only below it, so they never see a record that a leader failover could take back.
- Committed offset: per consumer group and partition, stored in the internal
__consumer_offsetstopic. It is the position the group will resume from. - Lag: log end offset minus committed offset, the backlog of that group on that partition.
When a group has no committed offset, or its offset has been deleted by retention, auto.offset.reset decides whether it starts at the earliest retained record or at the latest.
Keep messages small. The default maximum message size is about 1 MB, and performance is best with records from hundreds of bytes to tens of kilobytes. Large payloads raise memory pressure on brokers and clients and slow replication. For video processing, put the video in object storage and publish its location, which is the same claim-check idea used with queues.
Choosing a partition count. Partitions cap consumer parallelism, and each partition has a throughput ceiling, typically several MB/s to a few tens of MB/s depending on hardware and replication. A common rule: partitions ≥ max(target throughput / per-partition producer throughput, target throughput / per-partition consumer throughput). For 200 MB/s with consumers that each handle 5 MB/s, you need at least 40 partitions, so choose 48 or 64 for growth. More is not free. Every partition adds open files, replication traffic and controller metadata, and makes rebalances and failovers longer. Increasing the count later remaps keys, hash mod N changes, so per-key order breaks at the moment of the change. Topics that need strict per-key order are therefore sized generously up front.
Rough capacity per broker. As an order-of-magnitude figure for interviews, one well-provisioned broker can sustain hundreds of MB/s of writes, which with small messages is in the range of hundreds of thousands to about a million messages per second, and can store several terabytes. If your design's peak is far below that, Kafka's scaling is not the interesting part of the conversation. Focus on keys and ordering instead.
Consumer groups#
A consumer group is a set of consumers that share the work of reading a topic:
- Each partition is assigned to exactly one consumer in the group at a time, so messages in a partition are processed in order.
- Different groups are independent: each has its own offsets and gets every message (fan-out).
- If a consumer joins or dies, the group rebalances partitions among the remaining members.
- More consumers than partitions leaves the extras idle, so the partition count caps parallelism. Choose it with growth in mind (tens to hundreds for busy topics); you can add partitions later, but that changes key-to-partition mapping for new messages.
Consumer groups, in depth#
How partitions are assigned. When consumers join a group, one of them, or the broker coordinator in the newer protocol, assigns partitions using a strategy. Range gives each consumer a contiguous block per topic. Round-robin spreads partitions one by one. Sticky keeps existing assignments where possible, so caches and state stay put. Cooperative sticky also moves only the partitions that must move, without first revoking everything. Static membership (group.instance.id) lets a consumer restart within the session timeout and get the same partitions back, with no rebalance at all. That matters for rolling deploys of 100-instance consumer fleets.
What triggers a rebalance. A consumer joins, leaves or misses heartbeats for longer than session.timeout.ms, or fails to call poll within max.poll.interval.ms (5 minutes by default) because processing one batch took too long. The last case is a classic production bug: a consumer handling a slow batch is evicted, its partitions move, the batch is processed again by someone else, and the slow consumer rejoins and triggers another rebalance. Fix it by processing smaller batches (max.poll.records), raising the interval or moving slow work off the poll thread.
When to commit. Committing after processing gives at-least-once delivery. A web crawler that downloads pages should commit a URL's offset only after the raw HTML is safely stored in object storage. If it crashes before that, the URL is fetched again, which is acceptable. The more work a consumer does per message, the more is repeated after a crash. Splitting a pipeline into small stages, such as "fetch and store" and then "parse", each committing its own offsets, keeps the repeated work small. Auto-commit, which commits on a timer regardless of processing, can lose messages if the consumer crashes after the commit but before finishing.
Parallelism above the partition count. A group cannot have more active consumers than partitions. Two ways past that limit: process records from one partition concurrently inside a consumer, keyed so that each key still runs in order (Confluent's Parallel Consumer library does this), or use share groups. Share groups were introduced as early access in Kafka 4.0 (KIP-932, "Queues for Kafka"). They let many consumers take records from the same partition with per-record acknowledgement, which gives queue-like semantics on top of a log.
Watch lag in time, not just count. Lag of 50,000 records means nothing until you know the rate. At 100,000 records per second it is half a second behind, and at 100 per second it is eight minutes. Tools such as LinkedIn's Burrow evaluate lag trends per partition instead of fixed thresholds: lag that is growing while the committed offset stands still means a stuck consumer. Alert on estimated time lag against the freshness each consumer promises.
A consumer crash, step by step#
The diagram shows what happens when one member of a three-consumer group dies in the middle of a batch, using cooperative rebalancing.
Three numbers decide the cost of such a crash. The session timeout (45 seconds by default in recent clients) is how long partition 4 sits unprocessed before anyone notices. The commit interval sets how much work is repeated, here 300 records. The processing time per record turns those two into user-visible delay. Shorter timeouts detect crashes faster but cause false rebalances during GC pauses or network blips. Committing more often repeats less work but adds load on the coordinator. Typical production choices are a session timeout of 10 to 45 seconds and a commit after every batch.
Log-based broker vs traditional broker#
| Traditional broker (RabbitMQ, ActiveMQ, SQS) | Log-based broker (Kafka, Pulsar, Kinesis) | |
|---|---|---|
| Storage | Messages kept until acknowledged, then deleted | Append-only log, kept for a retention period |
| Consumption model | Broker pushes messages to consumers; per-message acks | Consumers pull and track offsets |
| Replay | Not possible once acked | Rewind to any retained offset |
| Ordering | Per queue, weakened by redelivery and multiple consumers | Strict per partition |
| Fan-out | Exchanges / topics copy to one queue per subscriber | Many groups read the same log |
| Routing | Rich: direct, topic patterns, headers, priorities, delays | Simple: topic + partition by key |
| Throughput | Tens of thousands of msgs/s per node typical | Hundreds of thousands to millions per second per cluster; sequential disk I/O |
| Per-message features | Per-message TTL, priority, delay, DLQ built in | Per-message work is your job (retry topics, DLQ topics) |
| Fits | Task distribution, complex routing, request/reply | Event streams, analytics, CDC, event sourcing, high throughput |
Logs versus traditional brokers, in depth#
Why the log design is fast. A traditional broker tracks the state of every message: delivered, unacked or acked, per consumer. That is random-access bookkeeping, and the broker slows as queues grow. A log broker tracks almost nothing per message. It appends to the end of a file and remembers one number per consumer group per partition. Writes are sequential appends, reads are sequential scans, and recent data is served from the operating system's page cache. Adding a tenth consumer group costs another reader of the same bytes, not ten times the storage. This is why a log keeps working when consumers fall far behind, while a classic queue that grows to millions of messages often slows down just when it is under the most pressure.
Why Kafka consumers pull. Kafka's designers chose pull deliberately. The consumer controls its own rate, so a slow consumer cannot be overwhelmed. It can fetch large batches when it is behind and small ones when it is caught up. Failure handling is simple, because the broker does not have to track what it pushed. A pull consumer needs long-poll fetches (fetch.max.wait.ms) so that it does not spin when there is no data. Push brokers such as RabbitMQ get lower latency for individual messages and use prefetch limits to protect consumers.
What a log gives up. Per-message features: there is no per-message TTL, priority, delay, or "hide this one message and retry it later". A partition is consumed in order, so one slow or poison message holds up everything behind it in that partition, unless the consumer moves it to a retry topic. Traditional brokers excel at exactly these per-message concerns, and at routing.
The lines are blurring. RabbitMQ added streams (in 3.9), an append-only, replayable structure inside the broker. Kafka added share groups for queue-style consumption. Google Pub/Sub and Pulsar offer both acks per message and replay by seeking to a time.
Pulsar's architecture as a contrast. Apache Pulsar separates serving from storage. Stateless brokers handle producers and consumers, while Apache BookKeeper nodes, called bookies, store the log as segments ("ledgers") replicated across bookies. A topic's data is therefore spread over many storage nodes instead of living on one broker's disk. Benefits: brokers can be added or replaced without moving data, a hot topic can move between brokers instantly, and old segments can be offloaded to object storage. Pulsar subscriptions come in four types: exclusive (one consumer), failover (one active consumer with standbys), shared (round-robin across consumers, queue-like, without ordering) and key_shared (several consumers, with order kept per key). The cost is more moving parts: brokers, bookies and a metadata store.
Queue vs stream: decision table#
| Question | Message queue | Event stream |
|---|---|---|
| Consumption model | Each message processed by one worker, then deleted | Each group reads all messages; offsets tracked per group |
| Retention | Until acked (SQS max 14 days) | Hours to forever (Kafka default 7 days; tiered storage for longer) |
| Replay | No | Yes, reset offsets |
| Ordering | Best effort, or FIFO per group | Per partition by key |
| Fan-out | Needs one queue per subscriber (SNS to SQS) | Native: add a consumer group |
| Per-message retries / delays | Built in | Build with retry topics |
| Tools | SQS, RabbitMQ, Celery, Sidekiq | Kafka, Pulsar, Kinesis, Redpanda |
Rule of thumb: jobs go in queues, facts (events) go in streams.
Retention and replay#
Kafka keeps records for a configured time or size (retention.ms, default 7 days) regardless of whether they were consumed. This enables:
- Replay after a bug: fix the consumer, reset its group's offsets to yesterday, reprocess.
- New consumers bootstrapping from history.
- Multiple speeds: a real-time consumer and a nightly batch consumer read the same topic.
- Log compaction (
cleanup.policy=compact): Kafka keeps at least the latest record per key, turning a topic into a durable changelog of current state (useful for CDC and caches).
Tiered storage (in Kafka 3.6+ and many managed offerings, and in Pulsar) moves older segments to object storage for cheap long retention.
Retention, compaction and replay, in depth#
Time and size limits. retention.ms (7 days by default) and retention.bytes (per partition, unlimited by default) bound how much history a topic keeps, and whichever limit is hit first applies. Size retention for the slowest recovery you need. If an outage of a downstream system can last a weekend and you want to replay after it, 3 days is too short. Storage math is simple: 50 MB/s of writes x 86,400 s x 7 days is about 30 TB, x 3 replicas is about 90 TB on broker disks. That is where tiered storage pays off.
Tiered storage. With tiered storage (KIP-405, production-ready in Kafka 3.9 after early access in 3.6), closed segments are copied to object storage, and brokers keep only a recent "hot" window on local disk. Consumers reading old data fetch it transparently from the remote tier, at higher latency. Retention of months or years becomes affordable, and brokers recover faster, because they hold less data to re-replicate.
Log compaction. A compacted topic keeps at least the latest record for each key and discards older values in the background. A record with a null value is a tombstone: it marks the key as deleted, and it is itself removed after delete.retention.ms. Compaction turns a topic into a durable table of current state, such as "latest profile per user" or "current price per product". A new service can rebuild its local copy by reading the topic from the start. Kafka uses compaction internally for __consumer_offsets, and Kafka Streams uses it for state-store changelogs. Compaction does not guarantee that only one value per key exists at a time, since the newest part of the log (the "head") is not yet compacted, so readers must still apply "last write wins".
Replay in practice. To reprocess, stop the consumer group and reset its offsets: to the earliest offset, to a specific offset, or to a time, for example with kafka-consumer-groups --reset-offsets --to-datetime. Replay is powerful and dangerous. Consumers with side effects will repeat them: a replayed order-shipped stream re-sends every shipping email unless the email consumer deduplicates. Common patterns:
- Replay into a new group that writes to a new table, compare it with the old one, then switch over. This is how you rebuild a search index or fix a buggy aggregation safely.
- Separate side-effect consumers (emails, payments) from state-building consumers, and replay only the latter.
- Mark replayed processing, so downstream systems can tell a backfill from live traffic, for example by writing to a different topic.
Ordering per partition#
Kafka guarantees order within a partition, not across a topic. So choose the key that defines the order you need: account_id keeps all events for an account in order. Hot keys put all their traffic on one partition (one consumer), so pick keys with enough spread. With retries, set the idempotent producer (enable.idempotence=true, the default in recent Kafka versions) to keep order and avoid duplicates on resend. See Delivery Semantics.
Ordering and hot partitions, in depth#
What exactly is ordered. Records in one partition are stored and delivered in offset order. If producer retries are enabled, the idempotent producer keeps that order even when a batch is resent: each producer gets an ID, each batch a sequence number, and the broker rejects duplicates and out-of-order sequences. It does this with up to 5 in-flight requests per connection. Without idempotence, a retried batch can land after a later one. There is no order across partitions or across topics. If a consumer needs "payment captured" and "order shipped" in order, both events must use the same key on the same topic, or the consumer must tolerate disorder.
Hot partitions. Partitioning by a natural key works until one key is far hotter than the rest. In an ad-click pipeline keyed by ad_id, a big brand's launch campaign can send a large share of all clicks to one partition, overwhelming the one consumer that owns it while others idle. Options:
- No key. If order does not matter, let the sticky partitioner spread records evenly.
- Salting. Append a random suffix from 0 to 9 to hot keys (
ad_123#7), so they spread across up to 10 partitions. Consumers then aggregate partial results per salt, for example summing 10 sub-counts per ad per minute. Order per ad is lost, which is acceptable for counting. - Compound keys. Key by
ad_id + regionorad_id + user_bucketwhen those attributes vary independently of the hot dimension. - Back pressure. Slow the producer when a partition's lag is too high, or use broker quotas to cap a noisy client.
Salting only hot keys requires knowing which keys are hot. Teams keep a small list, refreshed from traffic statistics, and salt only those, so ordinary keys keep their order.
Order with parallel processing. Within one consumer, you can process a partition's records on many threads and still keep per-key order, by dispatching records to threads by key hash. Commit offsets only up to the lowest offset that every thread has finished, otherwise a crash skips unfinished work.
Fan-out#
Fan-out means one published event reaches many consumers:
- Kafka: each consumer group is a subscriber; adding one costs nothing on the producer side.
- SNS + SQS fan-out: SNS publishes to many SQS queues (one per subscriber), each consumed independently with its own retries and DLQ. A very common AWS pattern.
- RabbitMQ fanout/topic exchanges: copy messages into each bound queue.
Fan-out to users (a post to a million followers) is a different, application-level problem built on these primitives. See Design a News Feed.
Fan-out, in depth#
Fan-out is cheap in a log and per-copy in a queue. In Kafka, ten consumer groups reading a topic cost ten readers of the same bytes, mostly served from the page cache when they keep up. With SNS and SQS, every subscriber gets a physical copy in its own queue. That costs a request per copy, but each subscriber has its own retries, DLQ and visibility settings, and a slow subscriber can never affect another's backlog. Choose per-subscriber isolation when subscribers are owned by different teams with different reliability needs, and a shared log when many consumers need the same high-volume history.
Filtering at fan-out time. SNS filter policies match on message attributes, such as {"region": ["eu"]}, so the EU fulfilment queue receives only EU orders. This cuts cost and code compared with filtering in every consumer. Google Pub/Sub subscriptions support filters on attributes too. In Kafka, filtering happens in consumers or in a stream processor that writes filtered topics.
Fan-out to people is a different problem. Pub/sub fans out to services, typically tens of subscribers. Delivering one post to millions of followers, or one comment to millions of viewers, is an application-level fan-out. It is built on pub/sub plus caches, connection servers and the co-location ideas above. A celebrity post is the "hot key" of social fan-out, and designs usually switch from pushing to every follower to letting followers pull, past a follower threshold. See Design a News Feed.
Event-carried data versus notifications. A fan-out message can carry the full new state (an "order placed" event with items, totals and address) or just a notification with an ID, after which every subscriber calls back to the source. Full events decouple subscribers from the source's availability and load. Thin notifications keep payloads small but turn one write into N reads against the source. See Event-Driven Architecture.
Evolution of messaging#
- IBM MQ (1993, as MQSeries) and JMS brokers: enterprise messaging with transactions and guaranteed delivery.
- RabbitMQ (2007): open-source broker implementing AMQP, flexible routing.
- Apache Kafka (open-sourced by LinkedIn in 2011): a distributed commit log for high-throughput streams, retention and replay.
- Apache Pulsar (open-sourced by Yahoo in 2016): separates serving brokers from storage (Apache BookKeeper), with multi-tenancy, geo-replication and both queue and stream semantics.
- Managed cloud services and Kafka-compatible engines (Redpanda, WarpStream, Confluent Cloud, Amazon MSK) are now common.
Evolution of messaging, in depth#
Enterprise messaging (1990s to 2000s). IBM MQ and the brokers behind Java's JMS API brought guaranteed delivery and transactions to banks and airlines. Messages could be sent and received inside the same distributed transaction as a database update, using XA two-phase commit. The brokers were centralised, carefully managed and expensive, and their throughput was in the thousands of messages per second.
Open protocols (2000s). AMQP started at JPMorgan in 2003 as an open, interoperable wire protocol for messaging, so banks would not be locked into one vendor's broker. RabbitMQ, written in Erlang, implemented it and became the default open-source broker. It brought exchanges, routing keys and flexible topologies, and it is still the right tool for task distribution and routing-heavy workloads.
The log (2010s). LinkedIn needed to move activity events, metrics and database changes between hundreds of systems at a volume that traditional brokers could not handle economically. The resulting system, Kafka, was described in "Kafka: a Distributed Messaging System for Log Processing" (Kreps, Narkhede and Rao, NetDB 2011). It treated messaging as a replicated, partitioned, append-only log with consumer-managed offsets. Jay Kreps's 2013 essay "The Log: What every software engineer should know about real-time data's unifying abstraction" made the broader argument: a log of events can be the integration backbone of a company, with databases, caches, search indexes and warehouses as derived views. Stream processing (Kafka Streams, Flink) and CDC grew on top of that idea.
Separating compute and storage (late 2010s to now). Pulsar, from Yahoo, moved storage to BookKeeper and made brokers stateless, with native multi-tenancy and geo-replication. Kafka itself added tiered storage, and replaced ZooKeeper with its own Raft-based controller quorum (KRaft). Newer Kafka-compatible engines push further. Redpanda is a single C++ binary with a Raft group per partition. Systems such as WarpStream write directly to object storage with stateless agents, trading a few hundred milliseconds of latency for far cheaper storage and no inter-zone replication traffic. The direction is clear: the log is becoming a protocol, and object storage is becoming the place where logs live.
Cloud options#
| Service | Model | Fits when |
|---|---|---|
| Amazon SNS | Push pub/sub to SQS, Lambda, HTTP, email/SMS | Simple fan-out on AWS, no replay |
| Amazon Kinesis Data Streams | Partitioned log (shards), 24 h to 365 days retention | Streaming on AWS without running Kafka |
| Amazon MSK, Confluent Cloud | Managed Kafka | Kafka API and ecosystem without operating it |
| Google Cloud Pub/Sub | Global pub/sub with per-message ack, optional ordering keys, replay by seek | Serverless pub/sub on GCP |
| Azure Event Hubs / Service Bus | Partitioned log (Kafka-compatible) / queues and topics | Streams / enterprise messaging on Azure |
Cloud options, in depth#
Amazon Kinesis Data Streams. A stream is made of shards, each a partition with fixed capacity: about 1 MB/s or 1,000 records per second of writes, and 2 MB/s of reads shared by all standard consumers. Enhanced fan-out gives each registered consumer its own 2 MB/s per shard, pushed over HTTP/2. Retention is 24 hours by default and can be extended up to 365 days. On-demand mode scales shards automatically. Sizing works like Kafka partitions: 50 MB/s of input needs at least 50 shards, and the partition key picks the shard by hash, so hot keys hit one shard's limit.
Amazon SNS and EventBridge. SNS is push-based fan-out to SQS, Lambda, HTTP endpoints, email and SMS, with filter policies and FIFO topics for ordered fan-out into FIFO queues. It stores nothing for replay. EventBridge is an event bus with content-based routing rules, a schema registry and archive-and-replay. It suits application events between AWS services and SaaS sources at moderate rates more than high-volume streams.
Google Cloud Pub/Sub. A global service where a topic can have many subscriptions, each with its own acknowledgements. Delivery is at-least-once by default, with an exactly-once delivery option for pull subscriptions within a region. Ordering keys give per-key order. Seek rewinds a subscription to a timestamp or a snapshot, which enables replay within the retention window. There are no partitions to plan: the service scales automatically. The trade-off is less control over throughput per key and over latency than with self-managed Kafka.
Azure Event Hubs and Service Bus. Event Hubs is a partitioned log, with capacity bought in throughput or processing units, and it exposes a Kafka-compatible endpoint, so Kafka clients connect unchanged. Service Bus is the enterprise broker: queues and topics with sessions for ordering, dead-lettering, scheduled delivery and transactions.
Managed Kafka. Amazon MSK, Confluent Cloud, Aiven and others run Kafka for you. Confluent Cloud and MSK Serverless also hide partition placement and broker sizing. You still choose keys, partition counts, retention and consumer design, because those are application decisions.
How to choose. Already on one cloud with modest volume and no need for the Kafka ecosystem: use the native service (SNS plus SQS, Pub/Sub, Event Hubs). Need the Kafka ecosystem (Connect, Streams, Flink connectors, schema registry) or portability across clouds: use managed Kafka. Very high, steady volume and a capable platform team: self-managed Kafka or a Kafka-compatible engine can be much cheaper at scale.
Designing topics and events#
One topic per event type, or per entity? With a topic per event type (order-placed, order-paid, order-shipped), consumers subscribe to exactly what they need, and each topic has one schema. But events of different types for the same order sit on different topics, so their relative order is lost. With a topic per entity stream (orders, carrying all order event types, keyed by order ID), a consumer sees an order's whole life in order, at the cost of a union schema and consumers that skip types they do not care about. The rule: if a consumer must see different event types for the same entity in order, those types belong on one topic with one key.
What goes in an event. Name events in the past tense, as facts that happened (PaymentCaptured), not as commands (CapturePayment). Include a unique event ID for deduplication, the entity ID, which is usually the key, the time it happened, a schema version and enough data that common consumers do not need to call back. The CloudEvents specification standardises such envelope fields (id, source, type, time, data), which helps when events cross team or company boundaries.
Keys decide more than partitions. The key is the unit of ordering, of compaction and often of stateful processing, since a stream processor groups state by key. Choosing customer_id instead of order_id changes all three. Decide it from the strictest consumer's needs, and check the key's skew before launch.
Lightweight pub/sub options#
Not every fan-out needs Kafka. Redis pub/sub delivers messages to connected subscribers in well under a millisecond, with no storage, which suits real-time signals such as "new comment on video 42" when the data itself is stored elsewhere. Redis Streams add a retained, consumer-group-aware log inside Redis, bounded by memory. PostgreSQL LISTEN/NOTIFY lets one database session wake others when a row changes. It is useful for small systems, but notifications are not stored for offline listeners and payloads are small. NATS is a lightweight, very fast messaging system for service-to-service pub/sub and request-reply, and its JetStream layer adds persistence and replay. Pick these when latency and simplicity matter more than long retention and very high throughput, and when losing a notification is acceptable because the data has a durable home.
Worked example: sizing a click-stream topic#
Inputs. An ad platform logs 500,000 click and impression events per second at peak, 300,000 on average, each about 400 bytes after compression is accounted for. Consumers: a real-time fraud detector, a per-minute aggregation job, a raw archive to object storage and a nightly billing reconciliation that may replay a day.
Throughput. 500,000 x 400 B = 200 MB/s of writes at peak. With replication factor 3, brokers receive 600 MB/s of total write traffic, and each of the four consumer groups reads 200 MB/s, mostly from the page cache because they keep up.
Partitions. Suppose one aggregation consumer instance handles 4 MB/s. Then 200 / 4 = 50 partitions are needed at peak. Choose 96 for growth and to allow 96 parallel fraud-detector instances. Key by ad_id for per-ad aggregation, salting the handful of hot campaign IDs as described above.
Retention and storage. Billing must be able to replay 3 days, and an outage may delay it by another 2, so keep 5 days. Average 300,000 x 400 B = 120 MB/s, x 86,400 x 5 is about 52 TB, x 3 replicas is about 156 TB. With tiered storage, keep 12 hours on broker disks (about 16 TB with replicas) and the rest in object storage.
Brokers. At roughly 100 MB/s of sustained replicated writes per broker, comfortably below disk and network limits, 600 MB/s needs at least 6 brokers. With headroom for a broker failure and for replay reads, choose 9 brokers across 3 availability zones, with replicas placed so that each partition has one copy in each zone.
Durability settings. acks=all, min.insync.replicas=2 and the idempotent producer. A single broker or zone loss then neither loses acknowledged data nor stops writes. See Delivery Semantics.
Sanity checks before you commit to the numbers. Inter-zone traffic is often the largest hidden cost of a self-managed cluster in the cloud. Each record crosses zones twice for replication and often once more for consumers, so 200 MB/s of input can become more than 500 MB/s of billed cross-zone transfer. Follower fetching (consumers reading from a replica in their own zone, available since Kafka 2.4) and object-storage-based engines both exist largely to cut this bill. Re-check the partition count against the largest consumer fleet you expect in two years, because adding partitions to a keyed topic later is disruptive.
Operating a streaming platform#
The signals that matter.
- Consumer lag per group and partition, in records and estimated seconds.
- Under-replicated partitions and ISR shrink events. A follower falling out of sync means less redundancy, and with
min.insync.replicas=2, one more loss stops writes to that partition. - Request latency on produce and fetch, especially p99.
- Disk usage per broker against retention.
- Controller and rebalance events. Frequent rebalances in a consumer group usually mean a poll-interval or session-timeout problem.
Topic hygiene. Use a naming convention such as domain.entity.event.version (payments.charge.captured.v1), with an owning team for every topic. Create topics through code review, not ad hoc, so partition counts, retention and replication are decided deliberately. Disable automatic topic creation in production, since a typo in a producer otherwise creates a new, empty, single-partition topic that silently swallows data.
Schemas are contracts. A schema registry with Avro, Protobuf or JSON Schema checks each new schema version against the previous ones (backward, forward or full compatibility) and rejects breaking changes at deploy time. Without one, a producer's renamed field breaks every consumer at 3 a.m. Version a topic (.v2) only for breaking changes that cannot be made compatible, and run both versions during migration.
Multi-tenancy and quotas. Shared clusters need quotas per client on produce and fetch bandwidth, so one team's backfill cannot starve another team's real-time consumers. Replays of large backlogs should run with throttled consumers or against a separate cluster fed by mirroring.
Cross-region. Tools such as MirrorMaker 2 or vendor cluster linking replicate topics between regions for disaster recovery or local reads. Offsets differ between clusters, so failover needs offset translation, and replicated topics carry the same at-least-once caveats. Consumers must be idempotent after a regional switch.
Queue or stream: three worked decisions#
Sending password-reset emails. One consumer type, per-message retries with backoff, a DLQ for bad addresses, no need for replay, low volume. Choose a queue (SQS or RabbitMQ). A stream would force you to build retry topics for no benefit.
Order events consumed by billing, inventory, email, analytics and a new recommendations team next quarter. Many independent consumers, a new consumer that wants history, per-order ordering and the possibility of replay after a billing bug. Choose a stream (Kafka or Kinesis) keyed by order ID with 7 or more days of retention. If the email service wants per-message retries, it can read the stream and push its own work into a queue. Mixing the two this way is common and healthy.
Live "someone is typing" indicators in a chat app. Very high churn of subscriptions, sub-100 ms latency and no value in old messages. Choose ephemeral pub/sub (Redis pub/sub or the chat servers' own fan-out). Storing these signals in a durable log would cost money and add latency for data nobody will ever replay.
The pattern behind all three: decide what must survive a consumer being offline, and for how long. Nothing: ephemeral pub/sub. Until processed once: a queue. For days, for many readers, with replay: a stream.
When to Use It#
- One event must reach several independent consumers (billing, email, analytics).
- High-throughput event pipelines: clickstreams, logs, metrics, IoT.
- You need replay, new consumers reading history, or event sourcing.
- Change data capture and data integration between services and stores.
When NOT to Use It#
- Simple background jobs with one consumer type and per-message retries: a queue is simpler.
- Request/response interactions where the caller needs an answer now.
- Small systems where running Kafka costs more than it saves; start with SNS/SQS or a managed service.
- When you need per-message priorities or delays; streams do not provide them natively.
How to Implement It#
- Model topics around business events (
order-placed,payment-captured), not around consumers. - Pick the key that defines required ordering and spreads load; pick partition counts for peak parallelism.
- Set replication (factor 3) and producer acks for durability (see delivery semantics).
- Use a schema registry with Avro, Protobuf or JSON Schema and compatibility rules.
- Name consumer groups per service; monitor consumer lag (latest offset minus committed offset).
- Set retention for replay needs; use compaction for changelog topics.
- Handle failures with retry topics and a DLQ topic; keep consumers idempotent.
# Kafka topic and consumer basics (illustrative)
kafka-topics --create --topic order-placed --partitions 48 --replication-factor 3 \
--config retention.ms=604800000 --config min.insync.replicas=2
# consumer settings
group.id=billing-service
enable.auto.commit=false # commit offsets after processing
auto.offset.reset=earliest # new group starts from the oldest retained record| Technology | Fits when |
|---|---|
| Apache Kafka (or MSK, Confluent) | Default for high-throughput streams with replay |
| Apache Pulsar | Multi-tenant, geo-replicated, queue + stream in one |
| Redpanda | Kafka-compatible, single binary, low latency |
| RabbitMQ | Complex routing and task distribution |
| SNS + SQS, Google Pub/Sub | Managed fan-out with low operations |
Trade-offs#
| Choice | Gain | Cost | Pick when |
|---|---|---|---|
| Log-based stream | Replay, ordering per key, huge throughput | Partition planning, offset management, no per-message features | Event streams, analytics, CDC |
| Traditional broker | Routing, per-message acks, priorities, delays | No replay, lower throughput | Task queues, routing |
| More partitions | More parallelism | More files, longer rebalances, harder ordering across | Busy topics |
| Long retention | Replay and backfills | Storage cost | Audit, event sourcing |
| Managed service | Low operations | Cost, fewer knobs | Most teams |
| Redis pub/sub | Sub-millisecond, dynamic subscriptions | No storage, offline subscribers miss messages | Live signals where data is stored elsewhere |
| SNS + SQS fan-out | Per-subscriber isolation, retries and DLQ | Copy per subscriber, no replay | Teams with different reliability needs on AWS |
| Tiered storage | Months of replay at object-storage prices | Slower reads of old data | Long retention, large topics |
| Salting hot keys | Spreads a hot key over many partitions | Loses per-key order, consumer must merge | Counting and aggregation workloads |
Common Pitfalls#
- Expecting global order across a topic; order is per partition only.
- Too few partitions, capping consumer parallelism.
- Auto-committing offsets before processing, losing messages on crashes.
- Hot keys sending most traffic to one partition.
- Ignoring consumer lag until data is hours late.
- Replaying a topic into consumers that send emails or charge cards without deduplication.
- Increasing the partition count on a keyed topic and breaking per-key order mid-stream.
- Slow batch processing that exceeds
max.poll.interval.ms, causing rebalance loops. acks=allwithoutmin.insync.replicas=2, giving one-copy durability when the ISR shrinks.- Leaving automatic topic creation on, so typos create silent new topics.
Real-World Examples#
Kafka was created at LinkedIn to move activity and operational data between systems as streams, and LinkedIn has reported processing trillions of messages per day through it.
Amazon's documentation describes the SNS-to-SQS fan-out pattern, where one SNS topic delivers each message to several SQS queues for independent processing.
LinkedIn's Kafka paper (NetDB 2011) and Jay Kreps's 2013 essay "The Log" describe how a single replicated log became the integration backbone between LinkedIn's systems. Yahoo open-sourced Pulsar in 2016 to serve many tenants and regions from one platform, with storage separated into BookKeeper.
In the Interview#
Interview playbook for streams#
Introduce the stream with its key. "Order events go to a Kafka topic keyed by order_id." The key immediately tells the interviewer you understand ordering and partitioning. Then give sizes: events per second, bytes per event, partitions, retention and replication factor.
Expect these probes.
- "How do you handle a hot partition?" No key if order does not matter, salting with consumer-side merging, compound keys, or back pressure on the producer. Say which one fits and what it costs.
- "What happens if a consumer dies?" Its partitions move to other members after the session timeout. They resume from the last committed offset, so a few records are processed twice. Consumers are idempotent.
- "What if Kafka goes down?" A properly replicated cluster across three zones rarely goes down as a whole. The realistic failures are a broker, which is covered by replicas and leader election, a consumer, which is covered by rebalancing, and a producer that cannot reach the cluster, which needs local buffering, retries and an alert. It is fair to say this politely.
- "How do you retry a failed message?" Kafka has no per-message retry. Publish failures to a retry topic with a delay, then to a DLQ topic. If per-message retries are central to the design, a queue such as SQS may be the better tool, as in a web crawler's fetch queue.
- "Kafka or Redis pub/sub for pushing live updates?" Redis pub/sub for dynamic, short-lived subscriptions with low latency where loss is tolerable. Kafka for durable streams consumed by services.
Signals of seniority. Separate the event log (facts, retained) from the delivery mechanism (connections, fan-out to users). Notice when the requirements change at extreme scale, such as sampling comments for a mega-stream. Plan replay deliberately, with idempotent side effects.
Deep Dive: Why Kafka is fast, and rebalancingShow
Sequential I/O and zero-copy. Kafka appends to segment files and reads sequentially, relying on the OS page cache; consumers reading recent data are served from memory. It batches and compresses records, and uses zero-copy transfer (sendfile) from page cache to the network socket. This is why one broker handles hundreds of MB/s.
Replication. Each partition has a leader and followers; the in-sync replica (ISR) set holds followers that are caught up. Metadata is managed by KRaft (Kafka's built-in Raft quorum), which replaced ZooKeeper; ZooKeeper mode was removed in Kafka 4.0.
Rebalancing. When group membership changes, partitions are reassigned. The original "stop-the-world" protocol paused all consumers; cooperative incremental rebalancing and static membership (stable IDs across restarts) reduce pauses, and the newer consumer protocol (KIP-848) moves assignment to the broker.
See Kafka in Practice.
Deep Dive: How Kafka replicates a partitionShow
Leader, followers and the ISR. Each partition has one leader replica, which handles writes and, by default, reads, and several followers that fetch from the leader exactly like consumers do. The in-sync replica set (ISR) contains the leader plus every follower that has caught up to the leader's log end within replica.lag.time.max.ms (30 seconds by default in recent versions). A follower that falls behind, because of a slow disk, a long GC pause or a network problem, is removed from the ISR and rejoins once it catches up.
When is a write committed? A record is committed when every replica in the current ISR has it. The leader then advances the high watermark, and only records below the high watermark are visible to consumers. The producer chooses when to hear "OK":
Producer acks | Acknowledged when | Can lose acknowledged data? |
|---|---|---|
0 | Sent on the socket | Yes, freely |
1 | Leader has written it | Yes, if the leader dies before followers copy it |
all | All current ISR members have it | Not while at least one ISR member survives |
acks=all alone is weaker than it looks, because the ISR can shrink to just the leader. Then "all" means one copy. min.insync.replicas=2 closes that gap: with fewer than 2 replicas in sync, the leader rejects acks=all writes with an error instead of accepting them with one copy. With replication factor 3 and min.insync.replicas=2, the cluster tolerates one replica loss without losing data or availability for writes, and a second loss stops writes but still loses nothing acknowledged. This is the standard production setting.
Leader failover. The controller notices a dead leader, through missed heartbeats to the KRaft controller quorum, and elects a new leader from the ISR. Because every ISR member has all committed records, no acknowledged write is lost. If the ISR is empty, the partition stays offline, unless unclean leader election is enabled, which promotes an out-of-sync replica and trades lost data for availability. It is disabled by default, and should stay that way for anything that matters.
Truncation and leader epochs. After a failover, a former leader may hold records that were never committed, written locally but not replicated. When it returns as a follower, it must truncate them to match the new leader. Older Kafka versions truncated to their own high watermark, which in rare sequences of failures could lose committed data or leave replicas with different logs. KIP-101 introduced leader epochs: each leadership term has a number, and a returning replica asks the leader where its epoch ended and truncates exactly there. This is the same idea as Raft's term numbers, applied to Kafka's replication.
KRaft. Cluster metadata (topics, partitions, leaders, ISR membership, configurations) used to live in ZooKeeper. KRaft moves it into an internal metadata log replicated by a Raft quorum of controller nodes, usually 3 or 5. Brokers follow that log instead of being pushed updates. Failover of the controller is fast, a cluster can hold far more partitions, and there is one system to operate instead of two. ZooKeeper mode was removed in Kafka 4.0.
What this means for designs. Kafka chooses consistency over availability per partition when configured safely: a partition without enough in-sync replicas refuses writes rather than risking loss. Producers must therefore handle write errors by buffering and retrying, ideally with the idempotent producer. Data is safe once acknowledged with acks=all and min.insync.replicas=2, and losses in practice come from weaker client settings, auto-committed offsets or unclean elections, not from the protocol itself.
Key Takeaways#
- Pub/sub delivers each message to every subscription; streams store events in a replayable log.
- Topics are split into partitions; offsets mark positions; order holds per partition by key.
- Consumer groups split partitions among their members; separate groups each read everything.
- Traditional brokers delete on ack and offer rich routing; log brokers retain, replay and scale to huge throughput.
- Jobs go in queues, facts go in streams; pick keys, partitions, retention and replication deliberately.
- Ephemeral pub/sub (Redis) is for live signals, and durable subscriptions (Kafka, Pub/Sub, SNS plus SQS) are for work that must not be missed.
- Partition count caps parallelism and is hard to change for keyed topics, so size it for peak and growth.
- Commit offsets after durable processing, keep consumer work small, and watch lag in seconds.
- Use
acks=all,min.insync.replicas=2, replication factor 3 and the idempotent producer for data that matters.