Queues and event streams
Foundations F10. What to say when your design has an arrow labelled "queue" or "Kafka": why a queue goes in the middle (load levelling and decoupling), task queues vs event logs and pub/sub, partitions, keys and ordering, delivery guarantees and what "exactly-once" really covers, retries and dead-letter queues, backpressure and consumer lag, the transactional outbox, and commands vs events when picking a broker. Each idea is told as a story you'll remember, with a lab that shows when a queue absorbs a spike, when partitions cap the fix, and when retries eat the capacity.
Start here
Almost every design at Senior level has an arrow labelled "queue" or "Kafka" somewhere. Drawing it is easy. The follow-ups are where the points are: what happens when consumers fall behind, can a message arrive twice, what order do they come in, what happens to the one message that always fails, and how do you publish an event without losing it when the database commit succeeds but the publish doesn't?
This page covers eight ideas: why a queue goes in the middle, task queues vs event logs, partitions and ordering, delivery guarantees (and what "exactly-once" really covers), retries and dead-letter queues, backpressure and consumer lag, the transactional outbox, and how to pick a broker (and when not to use one). Making consumers idempotent and running multi-step workflows (sagas) get their own page next. Stream processing (windows, joins) comes with data pipelines.
Sunday breakfast rush at a Bengaluru darshini
A busy darshini on a Sunday morning: the cashier takes orders and prints a token, the kitchen cooks, and the counter hands out plates. Nobody waits for anybody else to finish. One morning touches every idea on this page:
- The cashier doesn't walk each order to the cook. He spikes the slip on the rail and takes the next customer. (why a queue)
- Kitchen slips are thrown away once a dosa is made, but the billing register is kept, and the owner, the stock-keeper and the accountant each read it at their own pace. (queues vs logs)
- There are four tawas. All of table 7's orders go to the same tawa, so they come out in the order they were placed. (partitions and ordering)
- The cashier shouts an order, hears nothing, and shouts it again. Now there are two masala dosas. (delivery guarantees)
- One slip says "Jain, no onion, no potato, extra crisp, half oil, ghee on the side". The cook keeps putting it back on the rail. (retries and dead letters)
- At 9 am a bus of pilgrims arrives and the rail fills faster than the kitchen can clear it. (backpressure and lag)
- The cashier writes the bill and the kitchen slip on one carbon sheet, so he can't take money without the kitchen hearing about it. (the outbox)
- A request to the cook goes on the rail; "we're out of vada" goes on the board for everyone. (commands vs events, picking a broker)
The darshini is made up for teaching; it is not any real restaurant's system.
Why put a queue in the middle
A queue lets the producer hand off work and move on, so a spike becomes a wait instead of an outage, and a slow or dead consumer doesn't slow down or break the caller.
The slip rail between cashier and kitchen
Without the rail, the cashier would take an order, walk to the cook, wait for the dosa, bring it back, and only then serve the next customer. The line would reach the road.
With the rail, he prints the slip, spikes it, and takes the next order. The kitchen pulls slips at its own pace. If the cook steps out for two minutes, slips pile up on the rail, nothing is lost, and he catches up when he's back.
But the rail only helps if the kitchen keeps up on average. If ten orders come in every minute and the kitchen can make eight, the pile never shrinks, however long the rail is.
A message queue (or broker) sits between a producer that publishes messages and consumers that process them later. It buys you:
- Load levelling: a burst is stored and drained at the rate the consumers (and the database behind them) can take.
- Decoupling in time: the producer doesn't wait for the work, and doesn't fail when the consumer is down.
- Decoupling in space: the producer doesn't need to know who consumes, or how many consumers there are.
- Independent scaling: add consumers without touching the producer.
What it costs:
- The caller no longer gets the result in the response. You need a status endpoint, a callback, or a push.
- One more system to run, monitor and keep durable.
- New failure modes: duplicates, reordering, poison messages, and lag.
Use a queue when the work can happen after the response (emails, thumbnails, indexing, fan-out to other services) or when bursts would overwhelm the next stage. Don't use one when the caller needs the answer now (checking a password, reading a balance).
Slack's job queue runs the work that happens after an API call returns. At the time of the post it handled "over 1.4 billion jobs at a peak rate of 33,000 per second". Jobs were originally stored only in Redis. During an incident, database contention slowed the workers, Redis filled to its memory limit, new jobs couldn't be enqueued, and even dequeuing needed free memory, so the queue stayed stuck after the database recovered. The fix put Kafka in front of Redis as a durable buffer: a stateless Go service (Kafkagate) writes jobs to Kafka, another (JQRelay) moves them into Redis at a controlled rate. The cluster: 16 brokers, 32 partitions per topic, replication factor 3 (Slack, Dec 2017).
Microsoft's queue-based load levelling pattern states the same limit plainly: if the average producer rate exceeds the consumer rate, the queue keeps growing and latency rises.
- Synchronous call: simple, the caller gets the answer, but a slow or dead callee slows or breaks the caller. Queue: the caller is protected, but the answer arrives later and you must handle duplicates and lag.
- A queue absorbs bursts, not a sustained overload. If consumers can't keep up on average, it only delays the failure.
Sending the confirmation email doesn't need to be in the order request, so the order service publishes an OrderPlaced event and returns. Email workers consume at their own pace; a sale-night spike becomes a few minutes of lag, not a slow checkout.
Putting a queue in front of something the user is waiting on (for example a payment authorisation the checkout page needs) and then having to poll for the result. Ask first: does the caller need the answer in this response?
Task queues vs event logs (and pub/sub)
A task queue hands each message to one worker and deletes it once done; an event log keeps every message for a set time, and each reader tracks its own position, so many teams can read the same stream and replay it.
Kitchen slips vs the billing register
A kitchen slip has one job. One cook takes it, makes the dosa, and throws the slip away. If two cooks are free, they take different slips.
The billing register is different. Every bill is written in it, in order, and nothing is torn out for three months. The owner reads it at night to count the takings. The stock-keeper reads it on Monday to see how much rava went. The accountant reads it at the end of the month. Each keeps a bookmark at the last page they read, and nobody's reading affects anybody else's.
If the accountant finds a mistake in his sums, he moves his bookmark back to the 1st and reads the month again.
Two models, often both called "a queue":
Task (message) queue, e.g. Amazon SQS, RabbitMQ classic and quorum queues:
- Each message goes to one consumer. When the consumer acknowledges it, the broker deletes it.
- Work is spread across consumers message by message, so adding workers just works.
- Good for jobs: send this email, resize this image, call this webhook.
Event log (stream), e.g. Apache Kafka, Amazon Kinesis, Redpanda:
- An append-only, ordered log per partition. Messages stay for a retention period (or forever, with compaction) whether or not anyone read them.
- Each consumer group stores its own offset (bookmark). Every group gets every message; within a group, each partition is read by one consumer.
- Replay: reset the offset to reprocess history, for example after fixing a bug, or to build a new service's data from old events.
Pub/sub is the fan-out shape on top of either: one published message, many independent subscribers (Kafka consumer groups, SNS topics fanning out to SQS queues, Google Pub/Sub subscriptions).
The line is blurring: Kafka 4.2 (February 2026) made share groups ("Queues for Kafka") production-ready, letting several consumers share one partition with per-message acknowledgement, which is queue behaviour on a log.
LinkedIn, where Kafka was created, reported in October 2019 that its Kafka deployment had "surpassed 7 trillion" messages per day, across over 100 clusters, more than 4,000 brokers, over 100,000 topics and 7 million partitions.
Retention differs by model: SQS keeps a message 4 days by default (60 seconds to 14 days) and deletes it when the consumer does; Kafka's broker setting log.retention.hours defaults to 168 (7 days) in its configuration reference, and the log is kept that long no matter how many groups have read it.
- Queue: simplest way to spread jobs over workers, per-message acks and retries built in; but once consumed, a message is gone, and a second consumer means a second queue.
- Log: many independent readers, replay and ordering per partition; but parallelism is capped by partitions, and one slow message holds up its partition.
Order events go on a Kafka topic, because payments, fulfilment and analytics each need every event and analytics wants to replay history. The email job is a simple task, so a plain queue with retries and a DLQ is enough there.
Saying "Kafka" for every arrow. If there is one consumer, no replay and no ordering need, a managed queue is simpler and cheaper; say why you need a log before choosing one.
Partitions, keys and ordering
A topic is split into partitions; a message's key picks its partition, order is kept only within a partition, and the number of partitions caps how many consumers in a group can work at once.
Four tawas, one table per tawa
The darshini has four tawas. If any free cook grabbed any slip, table 7's "one plain dosa" and "make it a masala, actually" could be cooked on different tawas and come out in the wrong order.
So the rule is: table number decides the tawa. Tables 1, 5 and 9 go to tawa 1; tables 2, 6 and 10 to tawa 2; and so on. Each tawa cooks its slips strictly in order, so every table's orders come out in the order they were placed. Different tables can overtake each other, and nobody minds.
The rule has two costs. Hiring a fifth cook doesn't help, because there are only four tawas. And when a 20-person office party sits at table 7, tawa 3 is drowning while tawa 2 is idle.
- A partition is one ordered log. A topic is split into many so it can be spread over brokers and read in parallel.
- The producer picks the partition, usually by hashing the message key (hash(key) mod partitions). Same key, same partition, same order.
- Ordering: guaranteed only within a partition. There is no order across partitions, so choose the key as "the thing whose events must stay in order": order_id, user_id, account_id.
- Parallelism: in a consumer group, each partition is assigned to exactly one consumer. More consumers than partitions means idle consumers.
- Hot partitions: one very busy key (a celebrity, a big merchant) makes one partition the bottleneck. Options: a finer key, a key plus a suffix (gives up order for that key), or a separate topic for the giant.
- Adding partitions later changes hash(key) mod N, so new messages for a key can land on a different partition from its old ones. Order across the change isn't guaranteed. Size for the peak up front.
- Rebalancing: when consumers join or leave, partitions are reassigned; Kafka 4.0 (March 2025) made the new consumer group protocol (KIP-848) generally available, replacing stop-the-world rebalances; consumers opt in with group.protocol=consumer.
Kafka's documentation is explicit: "Kafka only provides a total order over records within a partition, not between different partitions in a topic", and "there cannot be more consumer instances in a consumer group than partitions."
Google Pub/Sub has the same idea under another name: messages with the same ordering key are delivered in order, all of them must be published in the same region, and publishing on each ordering key is limited to 1 MBps. If one message is redelivered, every later message for that key is redelivered too, even ones already acknowledged.
Slack's job queue used 32 partitions per topic (Dec 2017).
- More partitions: more parallelism and smaller hot spots; but more metadata for the cluster to track, more leaders to move when a broker fails, and more work in every rebalance (🔶 typical; measure before going to thousands per topic).
- Strict order for a key means one consumer at a time for that key; if you don't need order, don't pay for it.
I'll key the topic by order_id, so all events for one order stay in order on one partition. I'll create 64 partitions, enough for the peak number of consumers I expect, because adding them later remaps keys.
Promising "messages are processed in order" for the whole topic. Say per key, per partition, and only while one consumer handles that partition; a retry that republishes to the end of the topic breaks it too.
Delivery guarantees: at-most-once, at-least-once, exactly-once
When you acknowledge decides the guarantee: ack before the work and a crash loses the message (at-most-once); ack after and a crash repeats it (at-least-once). "Exactly-once" is at-least-once plus deduplication, and only inside the boundary that does the deduplicating.
The cashier who shouts twice
The cashier shouts "one masala dosa, table 7" and waits for the cook's "haan!". The kitchen is loud; he hears nothing. Did the cook miss it, or did the cook say "haan" and it got lost?
If he never repeats, a missed order means a hungry customer (at most once). If he repeats until he hears "haan", sometimes the cook heard both, and table 7 gets two dosas (at least once).
The darshini's fix isn't a better shout. Every slip has a token number, and the cook keeps a list of tokens he's already made. A second "token 41" gets a nod and no dosa. Notice that this works only for the kitchen. If the cook phones a delivery boy for each dosa, the delivery boy needs his own list too.
- At-most-once: acknowledge (or commit the offset) before doing the work. A crash in between loses the message. Fine for metrics you can afford to drop.
- At-least-once: do the work, then acknowledge. A crash after the work but before the ack means the message is delivered again. This is the default for SQS standard queues, RabbitMQ with manual acks, and Kafka consumers that commit after processing.
- Exactly-once, said precisely, is exactly-once effect: the message may be delivered more than once, but its effect happens once, because something deduplicates. That something has a boundary.
What each tool actually deduplicates:
- Kafka's idempotent producer stops duplicates from producer retries (on by default since Kafka 3.0, along with acks=all). Kafka transactions make "read from Kafka, process, write to Kafka, commit the offset" atomic.
- SQS FIFO deduplicates sends with the same deduplication ID within a 5-minute window.
- Neither covers your side effects outside the broker: the email sent, the card charged, the row written to your database. For those, the consumer must be idempotent (a processed-message table or a unique key, written in the same transaction as the effect).
The visibility timeout is how a queue implements at-least-once: SQS hides a received message for 30 seconds by default (up to 12 hours); if it isn't deleted by then, it reappears for another consumer. Set it longer than the slowest processing time, or extend it while working.
Confluent's 2017 post introducing Kafka's exactly-once semantics (by Neha Narkhede, Guozhang Wang and others) is careful about scope: Kafka Streams' guarantee covers its own read-process-write within Kafka, not remote calls or custom writes from the processing code, and exactly-once is an end-to-end property the application has to be designed to keep.
AWS's SQS docs say the same of standard queues: because of the at-least-once model, a message may be delivered more than once even within the visibility timeout.
- At-least-once plus idempotent consumers is the practical default: it never loses messages and duplicates do no harm.
- Broker-level exactly-once (Kafka transactions) adds latency and only covers Kafka-to-Kafka work; it's worth it in stream processing, not as a substitute for idempotent side effects.
Delivery is at-least-once, so the payment consumer stores each event ID in a processed_events table in the same transaction as the ledger write. A redelivered event hits the unique key and is skipped. That's exactly-once effect, which is the guarantee that matters.
Saying "Kafka gives exactly-once, so duplicates can't happen" while the consumer sends emails or calls a payment API. The interviewer will ask what happens when the consumer crashes after the charge and before the commit.
Retries, poison messages and dead-letter queues
Retry transient failures a few times with growing delays, and move a message that keeps failing to a dead-letter queue, so one bad message can't block the line or burn the consumers' time.
The slip nobody can cook
"Jain, no onion, no potato, extra crisp, half oil, ghee on the side, and make it a set dosa." The cook reads it, can't make it with what's in the kitchen, and puts it back on the rail. The next cook does the same. Every few minutes someone wastes a minute on it, and if the rail is strictly first-in first-out, every slip behind it waits.
The manager's rule: a slip gets three tries. If the gas went off or the batter ran out, a short wait and another try usually works. After three, the slip goes on a separate clip by the cash counter, where he can read it, call the customer, and put it back on the rail once it's fixed.
- Transient failures (timeout, rate limit, database failover) usually succeed on retry. Permanent failures (bad data, a bug, a deleted account) never will; retrying them only wastes capacity. These are poison messages.
- Retry with exponential backoff and jitter, a small fixed number of times. Retrying immediately and forever turns a short outage into a retry storm.
- After N attempts, move the message to a dead-letter queue (DLQ): alert on its depth, inspect, fix, then redrive (replay) the messages back.
- On a partitioned log, a consumer that retries in place blocks its whole partition (head-of-line blocking). The common fix: publish the failing message to a separate retry topic (with a delay) and commit the offset, so the partition moves on. That gives up order for that key, so do it only where order doesn't matter, or park all later messages for the same key too.
- Classify errors: send obvious bugs (validation errors, null pointers) straight to the DLQ instead of retrying.
Uber's 2018 post on reliable reprocessing describes exactly this. With blocking retries, "the Kafka consumer will not commit a new offset and the batches with these bad messages would be blocked". Their design forwards a failed message to a chain of retry topics, each with its own consumer group and a longer delay, and finally to a DLQ that supports listing, purging and merging back into the first retry topic. Transient errors are retried; code bugs go straight to the DLQ (Uber Engineering, Feb 2018).
On SQS, the redrive policy's maxReceiveCount sets how many receives a message gets before it moves to the DLQ. AWS advises against a value as low as 1, warns that a DLQ on a FIFO queue can break the exact order, and says to give the DLQ a longer retention than the source, because a standard queue's message keeps its original enqueue timestamp when it moves.
- More retries recover more transient failures, but each one costs an attempt and delays the messages behind it; 3 to 5 with backoff is a common start.
- Non-blocking retry topics keep a partition moving, but break per-key order for the retried message.
Consumers retry three times with exponential backoff and jitter, then move the message to a DLQ with the error attached. We alert when the DLQ isn't empty, and we have a redrive tool to replay messages after a fix.
Unlimited immediate retries. A bad deploy then makes every consumer spend most of its time on messages that will never succeed, the backlog grows, and healthy messages miss their deadline. The lab's Bad deploy preset shows the numbers.
Backpressure and consumer lag
Lag is how far consumers are behind; it grows at (arrival rate − processing rate), so watch it, scale consumers on it within what partitions and the database allow, and push back on producers when you can't catch up.
The pilgrim bus at 9 am
At 9 am a bus of 60 pilgrims pulls up. For ten minutes, orders come in at four times the usual rate. The kitchen can make twice the usual rate. The rail fills up.
The manager does the arithmetic on his fingers: the extra orders pile up for ten minutes, then the kitchen eats into the pile. A family that ordered at 9:10 waits about ten minutes. That's acceptable on a Sunday.
What he can't do is hire cooks without tawas, and calling three extra cooks won't help if the one batter grinder is the real limit. And if a second bus is due before the pile clears, he stops taking orders for complicated dosas at the cashier. That's backpressure: slowing the producer instead of letting the pile grow forever.
- Lag: for a log, the latest offset minus the group's committed offset (messages behind), or the age of the oldest unprocessed message (time behind). For a queue: depth and age of the oldest message. Time behind is what users feel; graph and alert on it.
- The arithmetic: during a spike, backlog grows at (arrival − capacity) per second. Afterwards it drains at (capacity − normal arrival). The last message of the spike waits roughly backlog ÷ capacity. Little's law ties them together: items in the system = arrival rate × time in system.
- Scale on lag, not on CPU: consumers waiting on a database can be at 10% CPU and still falling behind. But capacity is min(consumers, partitions) × per-consumer speed, and the database behind them has its own limit.
- Backpressure: when you can't catch up, slow the producers instead of growing the backlog until messages expire: bounded queues, rate limits at the producer, rejecting or deferring low-priority work. Inside a consumer, cap in-flight work (RabbitMQ's prefetch limits unacknowledged messages per consumer).
- Retention is a deadline: a message still unread when retention ends is lost.
KEDA, the Kubernetes event-driven autoscaler, scales Kafka consumers on total lag across partitions against a lagThreshold (default 10). By default it won't create more replicas than the topic has partitions, because the extra consumers would sit idle; allowIdleConsumers turns that cap off (KEDA 2.21 docs).
Microsoft's load levelling guidance adds the other half: "Autoscaling without bounding consumers' aggregate downstream rate only moves the overload to downstream dependencies." Slack's JQRelay, for example, reads its rate limits from Consul when moving jobs from Kafka into Redis (Dec 2017).
- Provisioning for the peak keeps lag near zero but leaves capacity idle most of the day; buffering the spike is cheaper if users can wait.
- Autoscaling on lag reacts in seconds to minutes; a spike shorter than that is absorbed by the queue anyway, so the delay target decides which you need.
The spike is 4,000 a second for ten minutes against 2,000 of capacity, so about 1.2 million messages pile up and the last one waits about ten minutes. That's fine for emails, so we buffer. For payment events with a 5-second target we'd need about 80 consumers, so we create the topic with 96 partitions and scale on lag.
Adding consumers past the partition count, or past what the database can write, and calling it scaled. The numbers have to hold at each step: partitions, consumers, and the store behind them.
Try it: Will the queue keep up?
Set the normal rate, a spike, how long each message takes, the consumers and partitions, and how many messages fail. Each row shows the arithmetic: the real capacity after retries, how big the backlog gets and how long the last message waits, how many consumers the delay target needs, and what lands in the dead-letter queue.
Order-confirmation emails on a sale night: 800 orders a second normally, 4,000 a second for the first 10 minutes. 40 consumers, 20 ms each, 48 partitions. An email that arrives within 15 minutes is fine.
| What we're sizing | Number | How we got it | So we decide |
|---|---|---|---|
| 1 · How fast the consumers drain | |||
| CapacityCapacity is consumers × speed, but on a partitioned log only one consumer per partition works, and every retry is an attempt that didn't finish a new message. | 2.0K msg/s | consumers doing work = min(consumers, partitions) = min(40, 48) = 40 one consumer: 1,000 ms ÷ 20 ms = 50 msg/s → 40 × 50 = 2.0K attempts/s attempts per message = 1 + 0.1% × 3 retries = 1.003 → 2.0K ÷ 1.003 = 2.0K msg/s busy at the normal rate: 800 ÷ 2.0K = 40% | Healthy headroom at normal load. |
| 2 · The spike | |||
| Longest waitA queue converts a rate you can't handle into a wait. Lag (how many messages, or how many seconds, consumers are behind) is the number to graph and alert on. | 10 min | backlog when the spike ends = (spike − capacity) × duration = (4.0K − 2.0K) × 600 s = 1.2M messages the last spike message waits behind all of them: 1.2M ÷ 2.0K msg/s = 10 min back to empty: backlog ÷ (capacity − normal rate) = 1.2M ÷ 1.2K = 17 min | Within the 15 min target: let the queue absorb it; no need to provision for the peak. |
| 3 · Meeting the delay target | |||
| Consumers neededA short spike with a loose target needs far less than the peak rate; a tight target needs nearly all of it. That is why "how late is too late?" is the first question to ask about any queue. | 33 | last spike message waits (spike − c) × T ÷ c; set that ≤ target S → c ≥ spike × T ÷ (T + S) = 4.0K × 600 ÷ (600 + 900) = 1.6K msg/s and at most 80% busy normally: c ≥ 800 ÷ 0.8 = 1.0K msg/s → need 1.6K msg/s consumers = 1.6K × 1.003 attempts ÷ 50 per consumer = 33 (you have 40, partitions allow 48) | Current consumers are enough. |
| 4 · Messages that fail | |||
| To the dead-letter queueA message that fails every time will never succeed by being retried. Retries are for transient errors; a few with growing backoff, then park it where a person can look. | 69K a day | 800 msg/s × 0.1% × 86,400 s = 69K messages a day, each tried 4 times first wasted on retries: 6 of every 2.0K attempts a second (0.3%) retention check: longest wait 10 min vs retention 168 h → nothing expires | Retries cost little here. Alert on DLQ depth anyway: it's how you find bad deploys and bad data. |
| 5 · Verdict for this workload | |||
| What you get | The queue absorbs the spikeFor 10 minutes, 4.0K a second arrive and 2.0K are finished, so 1.2M pile up. The last of them waits 10 min, inside the 15 min target, and the queue is empty again 17 min after the spike. This is load levelling: the database behind the consumers never sees more than 2.0K a second, and nobody had to provision for the peak. | ||
Try: on Sale emails, double the spike to 20 minutes and watch the wait cross 15 minutes. On Payments, 5 s, raise consumers to 80 and see that only 48 do work. On 96 partitions, set consumers to 80. On Bad deploy, cut retries to 3: the queue drains again, but too slowly; then set failures back to 0.1% (the rollback). The model is first-in first-out with steady rates; real traffic is burstier, which is why it plans for 80% busy, not 100%. All numbers are rounded teaching values.
The dual-write problem and the transactional outbox
You can't commit to your database and publish to a broker atomically, so write the event into an outbox table in the same transaction as the business change, and let a relay (often change data capture) publish it afterwards, at least once.
One carbon sheet for the bill and the slip
The old cashier wrote the customer's bill, took the money, and then wrote the kitchen slip. On busy mornings he sometimes got distracted between the two. The customer had paid, and the kitchen never heard about the dosa.
Writing the slip first was no better: if the customer then changed his mind and left, the kitchen made a dosa nobody paid for.
The new cashier uses a carbon sheet. One stroke writes the bill and its copy, and the copy goes into a tray. A runner empties the tray onto the rail every minute. If the runner is late, the slip is late, but it can't be lost and it can't exist without a bill. If the runner isn't sure he spiked a copy, he spikes it again, and the cook's token list takes care of the duplicate.
The dual write: "save the order, then publish OrderPlaced" is two writes to two systems. If the process crashes between them, or the publish times out, the database and the event stream disagree: a paid order nobody ships, or a shipment for an order that rolled back. There's no shared transaction (Kafka doesn't join XA transactions, and you wouldn't want one).
The outbox:
- In the same local transaction as the business change, insert a row into an outbox table (id, aggregate id, type, payload).
- A relay publishes outbox rows to the broker: either a poller (SELECT unpublished rows, publish, mark them sent) or change data capture (CDC), which tails the database's transaction log (Debezium reads the Postgres WAL or MySQL binlog).
- Delivery is at-least-once: the relay can publish a row twice after a crash, so consumers deduplicate on the event id.
- Use the aggregate id as the message key, so events for one order stay in order.
The reverse direction (consume a message and update the database) is the inbox or idempotent consumer: record the message id in the same transaction as the change.
Gunnar Morling's 2019 Debezium post sets out the problem and the fix. Because "we cannot have one shared transaction that would span the service's database as well as Apache Kafka", the order service writes the purchase order and an outbox row in one transaction, and Debezium, which "tails the append-only transaction log" rather than reading the table, publishes the insert to Kafka. The row can be deleted right after insert, since CDC reads the log, not the table. The post is explicit that delivery is at least once: after a restart, "a few events may be processed a second time", so each event carries a UUID the consumer checks against a table of processed messages (Debezium blog, Feb 2019).
- CDC relay: low latency, no polling load, preserves commit order; but another system to run (Kafka Connect, Debezium) and a dependency on the database's log format.
- Polling relay: simple, any database; but adds query load and latency equal to the poll interval, and needs care to keep order.
The order service never publishes directly. It writes the order and an outbox row in one transaction; Debezium streams the outbox to Kafka keyed by order_id. Delivery is at-least-once, so consumers deduplicate on event_id.
"Save to the database, then publish to Kafka, and retry the publish if it fails." The retry doesn't help when the process dies between the two lines. Name the dual-write problem and the outbox.
Commands vs events, and picking a broker
A command asks one service to do something; an event announces that something happened for anyone to react to. Pick the broker by what you need: a managed queue for jobs, a log for fan-out, replay and order, and no broker when the caller needs the answer now.
The slip rail and the notice board
"Make two idlis for table 4" is a slip for the kitchen. It's addressed to one place, someone must do it, and the cashier cares if it fails.
"We're out of vada" is written on the notice board. The cashier stops selling vada, the waiter tells his tables, the owner adds urad dal to tomorrow's list. Whoever wrote it doesn't know or care who reads it.
When the manager wants to know whether the kitchen can make a pongal before he takes the order, he doesn't write a slip. He leans through the hatch and asks.
Commands vs events:
- Command ("SendEmail", "ChargeCard"): one intended handler, imperative, may be rejected. Usually a task queue.
- Event ("OrderPlaced", "PaymentFailed"): a fact in the past tense, zero or more subscribers, can't be rejected. Usually a topic or log. Events let new consumers appear without changing the producer; the cost is that the overall flow lives in many places and is harder to trace.
- Schemas: events are a contract with readers you don't know. Use a schema (Avro, Protobuf, JSON Schema) and evolve it compatibly: add optional fields, never rename or reuse one.
Picking a broker (a starting point, not a rule):
- Managed queue (SQS, Cloud Tasks, RabbitMQ): background jobs, one consumer type, per-message retries and DLQ, no partition planning. SQS messages up to 1 MiB.
- Log (Kafka, Kinesis, Redpanda, Pub/Sub with ordering keys): many independent consumers, replay, per-key order, high throughput, stream processing.
- Redis lists or streams: light, fast, in-memory; fine for best-effort work, risky as the only copy of something important (see Slack above).
- No broker: the caller needs the result now, or the work must happen inside the same transaction.
Large payloads don't belong in the message: store the file in object storage and send its key (the claim-check pattern).
The Uber deep dive in this series picks Kafka for location and trip events because several services need replay and independent reads, and names RabbitMQ or SQS as the simpler choice it considered (🧭 interview choice, not Uber's published design).
SQS's message limit is 1 MiB (1,048,576 bytes); for bigger payloads its Extended Client Library stores the body in S3, up to 2 GB, and sends a pointer. Long-retention, replayable streams are Kafka's design point: LinkedIn ran 100,000+ topics in 2019.
- Events decouple teams and make new consumers cheap; commands make the flow explicit and easier to trace and to reason about failures.
- A log does everything a queue does with more planning (partitions, offsets, retention); a queue is less to run but can't replay or fan out on its own.
OrderPlaced is an event: payments, fulfilment and analytics subscribe, so it goes on a Kafka topic with a schema registry. SendReceiptEmail is a command with one handler, so it's an SQS queue with a DLQ. Checking stock before checkout is a synchronous call, not a message.
Publishing an event when you need an answer ("InventoryCheckRequested", then waiting for "InventoryChecked"): that's a slow, fragile remote call wearing a queue. If the caller waits, call it directly with a timeout.
Remember it
One line per idea. Read this the night before.
- A queue turns a spike into a wait, not an outage; it can't fix a consumer that's slower than the producer on average.
- Task queue: one worker per message, deleted on ack. Event log: kept for days, each group has its own offset, many readers, replay.
- Key picks the partition; order holds only within a partition; consumers that work ≤ partitions. Size partitions for the peak.
- Ack after the work = at-least-once. "Exactly-once" = at-least-once + dedup, only inside the boundary that dedups. Make consumers idempotent.
- Retry a few times with backoff and jitter, then dead-letter. Alert on the DLQ; have a redrive. Blocking retries stall a partition.
- Lag grows at arrival − capacity. Last spike message waits ≈ backlog ÷ capacity. Scale on lag, within partitions and the database.
- Never "save, then publish": write an outbox row in the same transaction and let CDC or a poller publish it, at least once.
- Command = one handler, do this. Event = it happened, anyone listens. Queue for jobs, log for fan-out and replay, no broker if the caller waits.
Check yourself
Answer out loud, then open.
A sale brings 4,000 orders a second for 10 minutes; your email consumers handle 2,000 a second; normal traffic is 800 a second. What happens, and is it acceptable?
Work it out:
- Backlog at the end of the spike: (4,000 − 2,000) × 600 s = 1.2 million messages.
- The last order of the spike waits about 1.2 M ÷ 2,000 = 600 s, 10 minutes.
- Afterwards it drains at 2,000 − 800 = 1,200 a second: about 1,000 s, 17 minutes, to get back to zero.
For order-confirmation emails, a 10-minute delay on a sale night is acceptable, so buffering is the right call; nobody provisions email workers for the peak. For anything with a seconds-level target, it isn't.
Say it The queue turns the spike into ten minutes of lag; I'd alert on lag age above 15 minutes.
Your consumer group has 12 partitions and 24 consumers, and it is still falling behind. What's going on and what do you do?
Only 12 consumers are doing work: each partition goes to one consumer in a group, so 12 sit idle.
Options, in order:
- Check where the time goes. If each message waits on a database or API, that's the real bottleneck; more consumers would only overload it.
- Make each message cheaper: batch writes, cache lookups, drop unneeded work.
- Process in parallel inside a consumer, per key, if order only matters per key.
- Add partitions (for example to 48), knowing that hash(key) mod N changes, so per-key order isn't guaranteed across the change. Do it at a quiet time, or create a new topic and migrate.
- Or use a model that doesn't tie consumers to partitions: a plain queue, or Kafka share groups if order doesn't matter.
Your order service saves an order and then publishes OrderPlaced to Kafka. What can go wrong, and how do you fix it?
It's a dual write to two systems with no shared transaction:
- Crash (or a publish timeout) after the commit: the order exists, no event. Payment or fulfilment never hears about it.
- Publish first, then the database commit fails: an event for an order that doesn't exist.
- Retrying the publish doesn't help when the process itself dies.
Fix with a transactional outbox: insert the event into an outbox table in the same transaction as the order. A relay (Debezium reading the WAL, or a poller) publishes it to Kafka keyed by order_id. Delivery is at-least-once, so consumers deduplicate on the event id.
The interviewer says: "Kafka supports exactly-once, so you don't need to worry about duplicates." How do you answer?
Partly true, and the scope matters.
- Kafka's idempotent producer removes duplicates from producer retries, and transactions make read-from-Kafka, process, write-to-Kafka and the offset commit atomic.
- That covers Kafka-to-Kafka processing. It doesn't cover side effects outside Kafka: an email, a card charge, a row in Postgres. If the consumer crashes after charging and before committing the offset, the message is redelivered and the charge runs again.
- So for external effects: at-least-once delivery plus an idempotent consumer, for example a processed_events table with a unique key written in the same transaction, or an idempotency key on the payment API.
Say it Exactly-once delivery isn't the goal; exactly-once effect is, and I get it by deduplicating where the effect happens.
One malformed message makes your consumer throw every time. What happens to the partition, and how do you design around it?
With blocking retries, the consumer never commits past that offset, so every message behind it in the partition waits: head-of-line blocking. Lag on that partition grows until someone intervenes.
Design:
- Classify errors: validation or parsing errors go straight to a dead-letter topic with the error and the original offset attached.
- Transient errors: a few retries with backoff; then publish to a delayed retry topic and commit, so the partition moves on (Uber's 2018 design).
- If per-key order matters, also park later messages for the same key until the bad one is resolved.
- Alert on DLQ depth, and build a redrive tool to replay fixed messages.
When would you choose SQS over Kafka, and the other way round?
SQS (or another managed task queue) when:
- It's a job with one consumer type: send an email, resize an image, call a webhook.
- You want per-message retries, visibility timeouts and a DLQ without planning partitions.
- No replay needed, and per-key order isn't needed (or a FIFO queue's message groups are enough).
Kafka (or another log) when:
- Several independent consumers need every event (payments, fulfilment, analytics).
- You need replay, to rebuild a service's data or reprocess after a bug.
- You need per-key order at high throughput, or stream processing.
Neither when the caller needs the answer in the response.
How do you set up autoscaling for a queue consumer, and what can go wrong?
Scale on lag, not CPU: the age of the oldest message (or messages behind), against the delay target. Consumers blocked on I/O can be idle on CPU while falling behind.
What can go wrong:
- Partitions cap useful consumers; past that you pay for idle pods (KEDA caps at the partition count by default).
- The database or API behind the consumers becomes the bottleneck; now the overload has just moved. Bound the total rate.
- Every scale event triggers a rebalance, which pauses consumption briefly; scale in steps with a cool-down.
- Scaling reacts in minutes; short spikes are absorbed by the queue anyway, so size the minimum for normal load with headroom.
Where you'll use this in the series
- Coordination: clocks, leaders, locks and consensus · partition leaders, and one relay per topic via a lock
- Replication and sharding · partitions are shards: keys, hot keys and adding shards
- APIs and real-time communication · pub/sub fan-out to WebSocket gateways
- Uber: from tap to pickup · location and trip events on a durable log
- Idempotency, exactly-once and sagas · idempotent consumers and multi-step workflows over queues
- Data pipelines: batch and stream · stream processing on top of the log
- Notification system · queues, retries and DLQs per channel (coming)
- Message queue (Kafka) · designing the log itself: storage, replication, consumer groups (coming)
Sources
- Exactly-once semantics are possible: here's how Kafka does it, Confluent (Jun 2017)
- Scaling Slack's job queue, Slack Engineering (Dec 2017)
- Building reliable reprocessing and dead letter queues with Apache Kafka, Uber Engineering (Feb 2018)
- Reliable microservices data exchange with the outbox pattern, Debezium blog (Feb 2019)
- How LinkedIn customizes Apache Kafka for 7 trillion messages per day, LinkedIn Engineering (Oct 2019)
- Apache Kafka 4.0.0 release announcement (Mar 2025)
- Apache Kafka 4.2.0 release announcement (Feb 2026)
- Introduction (topics, partitions, consumer groups), Apache Kafka 0.10.2 docs (checked Oct 2026)
- Broker configs (log.retention.hours), Apache Kafka 2.3 docs (checked Oct 2026)
- Upgrading to 3.0 (producer idempotence and acks defaults), Apache Kafka docs (checked Oct 2026)
- Amazon SQS message quotas, AWS docs (checked Oct 2026)
- Amazon SQS visibility timeout, AWS docs (checked Oct 2026)
- Exactly-once processing in Amazon SQS, AWS docs (checked Oct 2026)
- Using dead-letter queues in Amazon SQS, AWS docs (checked Oct 2026)
- Order messages (ordering keys), Google Cloud Pub/Sub docs (checked Oct 2026)
- Consumer prefetch, RabbitMQ docs (checked Oct 2026)
- Apache Kafka scaler, KEDA 2.21 docs (checked Oct 2026)
- Queue-based load levelling pattern, Azure Architecture Center (checked Oct 2026)
- Outbox Quarkus extension, Debezium docs (checked Oct 2026)
Checked October 2026. Limits and defaults come from the official AWS SQS, Apache Kafka, Google Cloud Pub/Sub, RabbitMQ and KEDA docs (KEDA 2.21; Kafka's retention default from its 2.3 configuration reference); company statements are as published on the dates shown (Confluent 2017, Slack 2017, Uber 2018, Debezium 2019, LinkedIn 2019, Kafka 4.0 in 2025 and 4.2 in 2026) and may have changed since. The lab's rates and timings are rounded teaching values; its model is first-in first-out with steady rates.
System Design Mastermind · Foundations
Series homeAll of Foundations
18 publishedStart here: the concepts every design uses, each told as a story you'll remember.
How a request travels: DNS, load balancers, gateways and open connections
Name → address (DNS) → open a secure line once and reuse it (TCP, TLS) → nearby copies for static files (CDN) → spread and guard the work (load balancer, gateway) → find colleagues inside (discovery) → keep a line open for live updates.
The interview framework: requirements, numbers and scope before boxes
Agree what users must do (three core requirements) → put numbers on how well (p99 latency, availability, durability, staleness) → say what's out of scope → sketch the simple end-to-end design → go deep only where a number breaks it.
Back-of-envelope estimation: from users to servers in one minute
Users × actions ÷ 86,400 (≈10⁵) = average per second → × peak factor → split reads and writes → storage = count × size × time × copies → bandwidth × 8 bits → in flight = rate × latency → servers = peak ÷ (capacity × 60%) + 2 spares.
APIs and real-time communication: REST, gRPC, retries, webhooks and live updates
Nouns + HTTP verbs (user from the token) → REST outside, gRPC inside → cursor pagination → POST with an Idempotency-Key, retries with backoff and jitter → add, don't change → poll for rare updates, SSE for one-way live, WebSockets for both ways → webhooks are at-least-once → thin connection gateways with resume and push fallback.
Databases: data models, indexes and transactions
Relational by default (each fact once, keys, constraints) → key-value / document / wide-column / graph only for a named access pattern → B-tree for reads, LSM for heavy writes → composite index with equality columns first, then the sort → one transaction per local change, made durable by the write-ahead log → know your isolation level → win races with a conditional write and a unique constraint.
Replication and sharding: copying and splitting your data
Copies scale reads and survive failures (leader + followers); splits scale writes and size (shards). Replicate first; shard only when data size or write rate outgrows one leader → pick the shard key from the main query → hash it into many fixed slots so growth moves ~1/(N+1) → name your hot key and your one cross-shard query.
Caching: hit ratios, invalidation and stampedes
Cache what is read far more than it changes → say the expected hit ratio and size the database for the misses → cache-aside with a TTL; on writes, update the database then delete the key → coalesce misses on hot keys and jitter TTLs → plan for the cache failing or restarting empty, because by then the system depends on it.
Consistency, CAP and quorums: what replicas promise
Say what each operation needs, not what the system is: strong (linearizable) for money, stock, seats and uniqueness; read-your-writes for a user's own data; eventual for counts, feeds and pages → during a partition, strong operations fail on the minority side, the rest keep serving (CAP) → on a normal day, strong costs a round trip to a quorum (PACELC) → with N copies, W + R > N makes reads overlap the latest write, but it isn't linearizability.
Coordination: clocks, leaders, locks and consensus
Don't order events across machines by wall-clock time; let one leader assign the order → elect that leader by majority vote with increasing terms, so a split network can't elect two → give it a lease so a dead leader is replaced without anyone proving it died → and a fencing token the storage checks, so a paused old leader can't do harm → use consensus (Raft) for the few decisions that must be agreed, not for every request.
Queues and event streams
Put a queue between work that can wait and the caller, so a spike becomes lag instead of an outage → use a task queue for jobs and an event log (Kafka) when many consumers need every event, replay or per-key order → key by the entity whose order matters and size partitions for peak consumers → deliver at least once and make consumers idempotent → retry a few times with backoff, then dead-letter → scale on lag → publish through an outbox, never "save, then publish".
Idempotency, exactly-once and sagas
Treat a timeout as unknown, never as failed → make writes idempotent by design (set, don't add; client IDs; conditional writes) → for the rest, an idempotency key per intent, stored with the result in the same transaction as the effect → consumers deduplicate by message ID in the same transaction → exactly-once holds only inside one boundary → across services, use a saga of local steps with compensations, not 2PC → compensable steps first, the pivot (capture payment) next, retryable steps last, on a durable orchestrator.
Scaling and performance
State latency as a percentile at a stated load → size each tier to the utilisation where its p99 is still flat (pooled, least-request balancing lets you run hotter) → budget fan-out calls against the page deadline, hedge stragglers → scale up first, scale out stateless tiers → name the shared resource (database, lock, connections) that caps the speed-up → find the saturated resource and cut work per request → pre-scale known peaks, autoscale on the signal that saturates → under overload, shed the lowest-priority work fast and budget retries.
Reliability and disaster recovery
Turn the target into a downtime budget → cut hard dependencies, because chains multiply → spread copies across zones (cells for blast radius) → timeouts from the deadline, one layer of jittered retries under a budget → circuit breakers with fallbacks and a bulkhead per dependency → fast, non-flapping health checks (readiness checks dependencies, liveness doesn't) → statically stable: spare capacity already running, config cached → PITR plus tested restores, because replicas copy mistakes → the cheapest DR strategy that meets RTO and RPO, drilled.
Observability and safe deployments
Metrics to notice, traces to locate, logs to explain (joined by a trace ID) → watch latency percentiles, traffic, errors and saturation → set an SLO per user journey and treat 1 − SLO as an error budget → page on burn rate over two windows, not on CPU → canary every change on a slice with automated analysis against a baseline → keep every version compatible with its neighbours (expand, migrate, contract) so rollback is always possible → ship dark behind flags, and stage config like code → when it breaks: one commander, mitigate first, blameless postmortem.
Security essentials for system design
Prove who the caller is (slow salted hashes, MFA, passkeys, rate-limited login) → carry identity in short-lived signed tokens with revocable refresh tokens, or in sessions you look up → delegate with OAuth code flow + PKCE, sign in with OpenID Connect → check this user against this object on every request, least privilege for people and services, audit logs → TLS 1.3 at the edge, mTLS inside, no trust from network location → envelope encryption with a KMS, secrets in a vault, tokenise what you needn't keep → treat all input as data (parameterise, encode, CSRF tokens, no user-chosen fetches) → absorb floods and abuse at the edge.
Search, feeds and geo building blocks
Search: analyse text into terms → inverted index of sorted postings → BM25 or hybrid (BM25 + vectors via RRF) retrieval of ~1,000 candidates → learned ranker → shards with replicas, fed from the database by CDC, refreshed every second. Typeahead: precomputed top-k per prefix in memory. Feeds: push IDs into followers' timelines, pull celebrities at read time, hydrate, filter, rank, page with cursors. Geo: index by cell (geohash, S2, H3), search the cell plus neighbours, exact distance on the few candidates.
Data pipelines: batch and stream
Pick batch or stream by how fresh each output must be. Get data in with log-based CDC (snapshot, then the WAL) and schemas that evolve safely; land raw events as Parquet in lakehouse tables partitioned by date. Batch jobs map, shuffle and reduce one partition and overwrite it, so retries and backfills are safe. Stream jobs window by event time, fire on watermarks, decide whether late events wait, correct or drop, and checkpoint state with offsets for exactly-once effect, with transactional or idempotent sinks. Reprocess by replaying retained data (Kappa) rather than keeping two codebases (Lambda).
AI foundations: inference, RAG and agents
Latency is time to first token (prefill reads the prompt, compute-bound) plus output tokens × time per token (decode, memory-bound), so stream answers and limit by tokens. GPU memory is weights plus a KV cache per request; long prompts, not users, fill it. Continuous batching shares each weight read across many requests, cutting cost per token by 10× or more until time per token hits its target. Route easy requests to small models, cache shared prompt prefixes, quantize carefully. RAG retrieves, reranks and cites a few permission-filtered chunks; agents are tool-calling loops with budgets, idempotent tools and approval for irreversible steps. Evaluate every change on an eval set, and design so a model fooled by prompt injection still can't do damage.