System designAsync systemsIntermediate

Message Queues and Event-Driven Systems

How queues decouple services, absorb spikes and move slow work off the request path, and how to handle the duplicates, ordering, retries and failures they bring with them.

The short answerA message queue is a durable buffer between services: a producer writes a message and moves on, and consumers process it when they can. Queues give you asynchronous processing, load levelling, independent scaling and failure isolation. Most systems deliver at least once, so consumers must be idempotent. Use a work queue when one worker should do each job, pub/sub when many services react to one event, and a retained log like Kafka when you need replay and ordered partitions.

HLD book
01Fundamentals

What is a message queue?

An intermediary that lets one component hand off work or events without the receiver having to process them right now.

ProducerCreates a message
Queue / brokerStores it durably
ConsumerProcesses it

Decoupling

The producer doesn't care when or how fast the work is done.

Async processing

The request finishes while background work continues.

Traffic buffering

Spikes queue up while consumers catch up.

Independent scaling

Producers and consumers scale separately.

Failure isolation

A consumer outage doesn't lose incoming work.

Load levelling

Bursty input becomes smooth downstream processing.

02Architecture

Synchronous vs asynchronous

Queues shine when the caller doesn't need every downstream activity to finish before getting a response.

Synchronous

Client → Order API → Notification service, and the caller waits.

  • Immediate, authoritative answer
  • Latency adds up across every hop
  • One slow dependency slows the whole request

Asynchronous

Client → Order API → queue → notification worker, and the API returns at once.

  • Fast response; work continues later
  • Dependencies can fail without failing the request
  • Results arrive eventually, not instantly
03Core components

Architecture and the message itself

Most messaging systems have producers, a broker with queues or topics, consumers, and some way of tracking what's done.

Producer AOrder service
Producer BPayment service
Producer CUser service
Message brokerQueues · topics · partitions · retention
Consumer ANotification
Consumer BAnalytics
Consumer CInventory
A well-formed eventjson
{
  "eventId": "evt_99201",
  "eventType": "ORDER_CREATED",
  "version": 1,
  "occurredAt": "2026-11-18T14:00:00Z",
  "correlationId": "req_123",
  "payload": { "orderId": "order_501", "userId": "user_42", "amount": 1999 }
}
FieldWhy it's there
eventIdA unique ID consumers use to deduplicate.
eventTypeWhich business fact this is.
versionLets the schema evolve safely.
occurredAtWhen it happened, not when it was processed.
correlationIdTraces one workflow across services.
payloadOnly the data consumers actually need.
04Decision guide

Which messaging pattern should you choose?

Start from semantics: who needs the message, whether order or replay matters, and whether it's a command, a job or an event.

What does the producer need?job · event · ordered change · future work
One workerWork queue
Many systemsPub/sub or stream
OrderingKeyed partition / FIFO
LaterDelayed queue
Retrytransient failures
DLQpoison messages
Idempotencyduplicate-safe effects
RequirementStart withWhyCommon mistake
One job → one workerWork queueClear ownership; scale workersUsing pub/sub and doing the job several times
Many services react to one factPub/subEach subscriber has its own progressOne competing queue, so only one service sees it
Replay historyEvent stream / logRetention + offsetsA destructive queue, and history is gone
Same entity stays orderedKeyed partition / FIFO groupOrder only where neededGlobal ordering that kills throughput
Do it laterDelayed queueNo database pollingAssuming exact timing; ignoring races
Temporary failureRetry queueBackoff lets the dependency recoverImmediate, infinite retries
Permanent failureDLQIsolate, inspect, replay safelyA DLQ nobody watches
05Pattern library

12 messaging patterns, explained

Pick a pattern to see how it works, a diagram, when to use it, when not to, and what to say in an interview.

Pattern 1 of 12

Point-to-point queue

A producer sends a message to a queue and one consumer processes it.

The simplest model. Producers write independent units of work; consumers compete for them, and each message is completed by one consumer.

The queue decouples producer speed from consumer speed. If producers create 20,000 jobs a second while workers handle 10,000, the backlog grows instead of making every producer wait.

Use it when the work should happen once. If three systems all need the same event, use pub/sub instead.

Order APICreates a background job
orders.queueM1 · M2 · M3
Worker 1M1
Worker 2M2
Worker 3M3

Best when

  • One job, one owner
  • Background processing that scales with workers
  • Buffering temporary spikes
  • The producer doesn't need the result now

Avoid or reconsider when

  • Many services need the same message
  • New consumers need historical replay
  • Strict global ordering matters more than parallelism
AspectIn practice
OrderingUsually none, unless the queue offers FIFO.
DeliveryUsually at-least-once with ACK or delete.
ScalingAdd consumers until they keep up, within downstream limits.
TechRabbitMQ queues, SQS standard, Azure Service Bus queues.
06Kafka concept

Consumer groups

Consumers in one group share a topic's partitions; separate groups each read the whole stream independently.

Partition 0
Partition 1
Partition 2
Consumer 1owns P0
Consumer 2owns P1
Consumer 3owns P2

Different groups, same stream

orders topic
notification-groupreads every order
analytics-groupreads every order
warehouse-groupreads every order
07Reliability

Delivery guarantees

What can happen to a message when producers, brokers or consumers fail.

GuaranteeDeliveriesRiskYou must…
At-most-once0 or 1Messages can be lostAccept loss (metrics, logs)
At-least-once1 or moreDuplicatesMake consumers idempotent
Exactly-onceOne business effectHard to guarantee end to endDefine the scope; use idempotency or transactions
08Correctness

Ordering and partitions

Ordering requirements decide how you partition, and therefore how far you can scale.

Global ordering

  • M1 → M2 → M3 → M4 → M5 for everything
  • One lane: very limited parallelism
  • Rarely what the business needs

Per-key ordering

  • order-1: CREATED → PAID → SHIPPED
  • order-2: CREATED → CANCELLED
  • Each order in sequence; orders in parallel
Partition by order IDjs
const partition = hash(orderId) % partitionCount;
// same orderId → same partition → processed in order
Producerkey = orderId
Partition 0orders A, D, G
Partition 1orders B, E, H
Partition 2orders C, F, I
09Message lifecycle

Acknowledgements and visibility timeouts

The broker needs to know when processing really finished.

QueueMessage available
ConsumerProcessing…
DoneRemoved / offset committed

What if the consumer crashes before the ACK?

Consumer AReceives M1
No ACKNot considered complete
Consumer BProcesses M1 again
10Critical concept

Idempotent consumers

If the same message arrives twice, processing it twice must not duplicate the business effect.

Bad: a duplicate charges the customer twicejs
async function handlePayment(message) {
  await paymentProvider.charge(message.userId, message.amount);
}
Better: deduplicate in the same transactionjs
async function handleEvent(event) {
  await db.transaction(async (tx) => {
    // the unique constraint on event_id makes a duplicate fail here
    const inserted = await tx.query(
      "INSERT INTO processed_events (event_id) VALUES ($1) ON CONFLICT DO NOTHING RETURNING 1",
      [event.eventId]
    );
    if (inserted.rowCount === 0) return;   // already processed → safe no-op

    await applyBusinessChange(tx, event);  // commits together with the marker
  });
}

Unique event ID

Every event carries a stable identifier.

Idempotency key

A business or client key for operations that may be retried.

Unique DB constraint

The database itself rejects a repeated effect.

Processed-events table

A record of what's already been applied (the transactional inbox).

11Resilience

Retries and backpressure

Give temporary failures time to recover, and don't let a queue hide sustained overload.

Exponential backoff with jitterjs
// attempt 1 → now, 2 → ~2 s, 3 → ~4 s, 4 → ~8 s, 5 → ~16 s, then DLQ
const delay  = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * 2 ** attempt);
const jitter = Math.random() * 1000;          // spread retries out
scheduleRetry(message, delay + jitter);

Retry

  • Network blips and timeouts
  • Temporary 5xx
  • Rate limits with a retry hint

Don't blindly retry

  • Invalid schema or missing fields
  • Business-rule violations
  • Permanently invalid accounts

Backpressure

Incoming100K jobs / sec
QueueBacklog growing
ConsumersOnly 20K / sec

Autoscale consumers

On lag and oldest-message age.

Throttle producers

Reject, delay or rate-limit non-critical work.

Batch

Process many messages per call when downstream benefits.

Prioritise

Critical traffic first.

Shed load

Drop optional work under severe pressure.

Bound the queue

Retention, quotas and alerts, never infinite growth.

12Kafka deep dive

Kafka internals

Kafka is best understood as a partitioned, replicated, retained log, not just a faster queue.

Producer Akey = order-1
Producer Bkey = order-2
Producer Ckey = order-3
Partition 0leader + replicas · offsets 0…N
Partition 1leader + replicas · offsets 0…N
Partition 2leader + replicas · offsets 0…N
Consumer 1P0
Consumer 2P1
Consumer 3P2
ConceptWhat it means
TopicA named stream of events, e.g. booking.events, split into partitions.
PartitionAn ordered, append-only log. Order is guaranteed inside one partition only.
OffsetA record's position in its partition; groups track progress by offset.
Leader & replicasOne broker leads each partition; followers copy it for durability (acks=all + min.insync.replicas).
Consumer groupEach partition is owned by one active consumer in the group.
RetentionEvents stay for a configured time or size after being read, which enables replay.
RebalancePartitions move when consumers join or leave; processing pauses briefly.
Hot partitionA skewed key overloads one partition while others idle.
13RabbitMQ deep dive

RabbitMQ internals

A traditional broker with powerful routing before messages ever reach a queue.

ProducerroutingKey = payment.success
Exchangedirect · topic · fanout · headers
booking.queuepayment.success
fraud.queuepayment.*
audit.queuepayment.#
WorkersPrefetch limits in-flight messages
ExchangeRouting ruleGood forExample
DirectExact key matchSimple explicit routingpayment.success → booking.queue
TopicWildcards (* = one word, # = any)Event familiespayment.* or order.#
FanoutEvery bound queueBroadcastconfig.changed → all services
HeadersMatch on headersMetadata routingx-region=IN, x-tier=premium
14Cloud queues

Managed queues

No broker cluster to run, but you still need to know the delivery semantics and limits.

Standard queue

High-throughput independent jobs.

  • Huge parallelism
  • Simple worker scaling
  • Expect duplicates and loose ordering

FIFO with message groups

When one key's events must stay in order.

  • Ordered per message group
  • Different groups in parallel
  • Lower throughput limits than standard

Visibility timeout

An in-flight message is hidden, and redelivered if not deleted in time.

Long polling

Wait for messages instead of hammering empty receives.

Redrive / DLQ

After N receives, failing messages move to a DLQ.

Delay

Keep a message invisible until a future time.

15Technology selection

Kafka vs RabbitMQ vs managed queues

Their messaging models are different. Choose the model, then the product.

Kafka-style logRabbitMQ-style brokerManaged queue
Core modelDistributed retained logBroker with exchanges and queuesHosted queue service
ReplayNativeNot its modelService-dependent
RoutingTopics + partitionsRich exchange routingQueues, topics, filters
Streaming throughputExcellentGoodService-dependent
Task queuePossibleVery naturalVery natural
OperationsSignificant (unless managed)Significant (unless managed)Mostly the provider's
Typical useEvents, CDC, analytics pipelinesJobs, routing, business messagingCloud-native async jobs

Quick picks for interview scenarios

ScenarioStart with
10M analytics events a day, with replayKafka-style log
Generate an invoice once, in the backgroundWork queue / managed queue
Order event → analytics + notification + warehousePub/sub or stream with separate groups
payment.success → booking; payment.failed → recoveryTopic or direct routing broker
Release a booking hold after 5 minutesDelayed queue / scheduler + queue
Same order's events must stay sequentialPartition (or FIFO group) keyed by orderId
Small team, durable jobs, minimal opsManaged queue
Replayable CDC into a warehouseKafka / Kinesis / Pulsar
16Distributed transactions

The dual-write problem and the transactional outbox

Updating your database and publishing an event as two separate steps will, eventually, do only one of them.

Order service
DatabaseCOMMIT succeeds
Broker publish failsThe order exists, the event doesn't
Write the event in the same transactionsql
BEGIN;
INSERT INTO orders (id, user_id, amount, status) VALUES ('order_501', 'user_42', 1999, 'CREATED');
INSERT INTO outbox (event_id, aggregate_id, event_type, payload)
VALUES ('evt_123', 'order_501', 'ORDER_CREATED', '{"orderId":"order_501"}');
COMMIT;
Application DBOrder + outbox row committed together
Message brokerORDER_CREATED
17Implementation

Code examples

In interviews you explain the design rather than write framework code, but these make the lifecycle concrete.

BookingEventPublisher.java (Spring Kafka)java
@Service
@RequiredArgsConstructor
public class BookingEventPublisher {
  private final KafkaTemplate<String, BookingEvent> kafka;

  public CompletableFuture<SendResult<String, BookingEvent>> publish(BookingEvent event) {
    // bookingId as the key: all events for one booking land on one partition, in order
    return kafka.send("booking.events", event.getBookingId(), event);
  }
}
BookingNotificationConsumer.java (idempotent)java
@Service
@RequiredArgsConstructor
public class BookingNotificationConsumer {
  private final ProcessedEventRepository processed;
  private final NotificationService notifications;

  @KafkaListener(topics = "booking.events", groupId = "notification-group")
  @Transactional
  public void consume(BookingEvent event) {
    if (processed.existsById(event.getEventId())) return;   // duplicate → no-op
    notifications.createNotificationRecord(event);
    processed.save(new ProcessedEvent(event.getEventId()));
  }
}
RetryPolicy.java (classify before retrying)java
public RetryDecision classify(Throwable error, int attempt) {
  if (error instanceof ValidationException) return RetryDecision.DLQ;   // permanent
  if (attempt >= 5) return RetryDecision.DLQ;                            // exhausted
  if (error instanceof TimeoutException || error instanceof TemporaryProviderException) {
    return RetryDecision.RETRY_WITH_BACKOFF;                             // transient
  }
  return RetryDecision.DLQ;
}
18Case study

Ticket booking: where queues help and where they don't

A booking system mixes synchronous concurrency control with asynchronous events. The real skill is drawing the boundary.

The critical seat-hold path stays synchronous

User ASelects A10 + A11
Seat-lock serviceAtomic conditional acquire
Seat / booking storeAVAILABLE → HELD, expiresAt = T + 5 min
Hold createdbookingId + expiry
Atomic seat holdsql
UPDATE seats
SET    status = 'HELD', held_by = :bookingId, expires_at = :expiresAt, version = version + 1
WHERE  show_id = :showId AND seat_id = :seatId AND status = 'AVAILABLE';
-- 1 row → you have it; 0 rows → someone else does

Expiry, and its race with payment

Payment callbackPAYMENT_SUCCEEDED
Expiry eventHOLD_EXPIRED
Booking state machineAuthoritative status + version decides
CONFIRMEDExpiry becomes a no-op
EXPIREDLate payment → reconciliation

Confirm + outbox, then fan out

Booking confirmation transactionsql
BEGIN;
UPDATE bookings SET status = 'CONFIRMED', payment_id = :paymentId
WHERE  booking_id = :bookingId AND status = 'PENDING';
UPDATE seats SET status = 'BOOKED' WHERE held_by = :bookingId AND status = 'HELD';
INSERT INTO outbox (event_id, aggregate_id, event_type, payload)
VALUES (:eventId, :bookingId, 'BOOKING_CONFIRMED', :payload);
COMMIT;
Outbox / CDCBOOKING_CONFIRMED
booking.eventsRetained topic
Notificationemail / SMS / push
Ticket workerQR / PDF
Analyticsconversion
Warehousepipeline
OperationSync or asyncWhyPattern
Search showsSyncUser needs results nowNone
Acquire seat lockSyncImmediate correctness decisionNone for the lock itself
Create payment intentUsually syncUser enters payment nowEvents may follow
Payment callbackDurable + idempotentMust survive retries and duplicatesEvent / queue
Hold expiryAsync, delayedFuture action at T + NDelayed queue
Ticket generationAsyncCan finish after confirmationWork queue
Email / SMSAsyncProvider slowness mustn't fail bookingWork queue + retry + DLQ
AnalyticsAsyncEventually consistentPub/sub / stream

Failure scenarios to explain

  1. Payment callback delivered twice

    Provider idempotency key + unique payment transaction + idempotent state transition.

  2. Payment arrives after the hold expired

    Reconciliation; never book a seat someone else may now hold.

  3. Expiry event delivered twice

    Conditional release on state and version; the second is a no-op.

  4. Email provider down

    Booking stays confirmed; notifications retry and DLQ if exhausted.

  5. Broker down right after the commit

    The outbox keeps the event until the publisher can deliver it.

  6. Consumer commits, then crashes before ACK

    Redelivered; eventId keeps it idempotent.

  7. Blockbuster traffic spike

    Queue non-critical work, autoscale consumers, rate-limit, watch oldest-message age.

  8. One show creates a hot partition

    Key by bookingId (not showId) unless per-show ordering is truly needed.

19Production engineering

Failure scenarios and metrics

Queues move complexity rather than remove it. Design for crashes, duplicates, backlog and poison messages.

FailureResponse
Consumer crashesNever ACK unfinished work; the message is redelivered.
Duplicate messageIdempotency keys, unique constraints, processed-event tracking.
Poison messageBounded retries, then DLQ with metadata and an alert.
Consumer too slowWatch lag and age, scale workers, check downstream bottlenecks.
Broker node failsReplication, durable storage, acks=all for important topics.
Producer retries after a timeoutStable event IDs and idempotent producers prevent duplicates.
DB commit succeeds, publish failsTransactional outbox.
Retry stormBackoff, jitter and bounded retries.
Backlog grows foreverAutoscale, throttle producers, prioritise, alert on sustained lag.
Schema changeVersioned contracts; consumers tolerate compatible changes.

Metrics worth a dashboard

  • Queue depth
  • Consumer lag
  • Oldest message age
  • Messages / sec in and out
  • Consumer throughput
  • Processing latency
  • Retry rate
  • DLQ size
  • ACK failures
  • Rebalances
  • Broker disk & CPU
  • Partition skew
Interview prep

Message queues interview questions, with answers

Say your answer out loud first, then open the card to compare. These are the questions interviewers actually ask.

1

Why do we use a message queue in system design?

It decouples producers from consumers, lets work happen asynchronously, buffers traffic bursts, isolates temporary consumer failures and lets producers and consumers scale independently. The cost is eventual consistency plus new concerns: retries, duplicates, ordering, monitoring and DLQs.

2

When should you NOT use a message queue?

When the caller needs an immediate, authoritative answer and a synchronous API is simpler; when the workload is tiny and the operational cost outweighs the benefit; or when delayed processing would break business semantics. A queue is an architectural boundary, not a default for every call.

3

Queue vs pub/sub: what's the difference?

A work queue delivers each job to one successful consumer in a competing worker pool. Pub/sub lets several independent subscriptions each receive the same event. Use a queue for “do this job once”, pub/sub for “this happened, and several systems may react”.

4

Fanout vs topic routing?

Fanout broadcasts every message to every bound subscriber. Topic routing uses a key or pattern such as payment.success or payment.* so only interested subscribers receive it. Fanout is simpler; topic routing cuts unnecessary traffic when subscribers' interests differ.

5

FIFO vs standard queue?

Neither is better in general. Choose FIFO only when correctness needs ordering for a key or group. Standard queues allow more throughput and parallelism. Per-order or per-account ordering is usually enough; global ordering is expensive.

6

At-most-once vs at-least-once vs exactly-once?

At-most-once may lose messages but never redelivers. At-least-once retries until acknowledged, so it rarely loses messages but can duplicate them, which means consumers must be idempotent. Exactly-once must be scoped carefully: a broker may offer it within its own system, but external databases, payment APIs and emails still need idempotency or transactions to produce one business effect.

7

Why can a duplicate arrive even after successful processing?

The consumer commits its database transaction and then crashes before sending the ACK. The broker can't know the work succeeded, so it redelivers. That's why processing and deduplication must be designed together.

8

How do you make a consumer idempotent?

Give every event a stable eventId or business key, enforce a unique constraint, record processed event IDs in the same database transaction as the business change, and pass provider idempotency keys to external APIs.

9

What is a poison message?

A message that always fails, because of bad data, an incompatible schema or a deterministic bug. Retrying it forever wastes capacity and can block an ordered partition. After bounded retries, move it to a DLQ with failure metadata and alert the owning team.

10

How should retries be designed?

Retry only transient failures, with bounded attempts, exponential backoff and jitter. Keep the attempt count and last error with the message, separate retry traffic from fresh traffic when needed, and send exhausted or permanent failures to a DLQ. Never retry a failing dependency in a tight loop.

11

What is a visibility timeout?

In SQS-style queues, receiving a message hides it from other consumers for a period. If the consumer deletes (ACKs) it in time, it's done. If the consumer crashes or the timeout expires first, the message becomes visible again and another worker can take it.

12

How do you keep order without destroying throughput?

Use per-key ordering: hash orderId, accountId or bookingId to a partition or FIFO message group. Events for one entity stay in sequence while different entities process in parallel. Avoid global ordering unless it's truly required.

13

What happens when one message in an ordered stream keeps failing?

Later messages for that partition or group can't pass it, so the lane blocks. You need bounded retries, a quarantine or DLQ policy, and a business decision on whether later messages may proceed without it.

14

What is backpressure, and how do you handle it?

Producers create work faster than consumers finish it, so the backlog grows. Handle it with consumer autoscaling, producer throttling, batching, admission control, prioritisation, shedding optional work and protecting downstream systems. A queue absorbs bursts, not infinite sustained overload.

15

Queue depth or oldest-message age: which matters more?

Both. Depth shows backlog size; oldest-message age shows the delay users actually feel, which is what SLAs care about. Also watch produce and consume rates, processing latency, retry rate, DLQ rate and downstream saturation.

16

Why does Kafka use partitions?

A partition is an ordered, append-only log. Splitting a topic into partitions spreads storage and throughput across brokers and lets consumers in a group work in parallel. Order is guaranteed only within a partition, so the partition key decides both correctness and load balance.

17

A consumer group has 10 consumers but the topic has 3 partitions. What happens?

Only three consumers do work, one per partition; the other seven sit idle as standbys. To get more parallelism, add partitions (which changes key-to-partition mapping) or redesign the workload.

18

What is consumer lag?

The distance between the newest offset in a partition and the offset a consumer group has committed. Rising lag means the group is falling behind. Look at processing latency, downstream bottlenecks, too few consumers, hot partitions and errors.

19

How do you choose a Kafka partition key?

Pick a stable key that groups events needing order, such as orderId, with enough cardinality to spread load. A poor key, such as one celebrity ID or a region, creates a hot partition while the others idle.

20

Direct vs topic vs fanout exchanges in RabbitMQ?

Direct routes when the routing key exactly matches a binding key. Topic supports wildcards such as payment.* (one word) and order.# (zero or more words). Fanout ignores keys and broadcasts to every bound queue.

21

What is prefetch, and why does it matter?

Prefetch caps how many unacknowledged messages a consumer holds. Too high causes unfair distribution and big redelivery after a crash; too low leaves fast workers waiting on the broker. Tune it to message cost and worker concurrency.

22

When would you choose SQS-style managed queues over Kafka?

For durable background jobs when you value low operations, visibility timeouts, elastic scaling and simple ownership. Choose Kafka-style logs when retained, replayable streams, many independent consumer groups and partitioned ordering are central.

23

What is the dual-write problem?

A service commits a database change and then publishes an event as two separate steps; one can succeed while the other fails, leaving the database and downstream systems out of sync. The transactional outbox fixes it by writing the business row and an outbox row in one transaction and publishing from the outbox afterwards.

24

What is the transactional inbox?

The consumer stores each incoming event ID (or the message) in its own database, in the same transaction as the business change. That gives durable deduplication, so at-least-once delivery becomes effectively-once processing.

25

Command vs event: what goes on the queue?

A command asks one capability to do something (GenerateInvoice) and has one logical owner. An event states a fact that already happened (InvoiceGenerated) and may have many consumers. Keeping them distinct makes event-driven systems far easier to reason about.

26

Should seat locking in a booking system go behind a queue?

Usually not. The user needs an immediate answer on whether they got the seat, so use an atomic lock or conditional database update synchronously. Queues are great after that decision: hold expiry, ticket generation, notifications and analytics.

27

How would you release a seat after the payment window expires?

Schedule a delayed expiry message with bookingId, seat IDs and a hold version. When it fires, the worker reads the authoritative booking and releases only if it's still HELD with the same version. If payment already succeeded, the expiry is a no-op.

28

How would you send 10 million emails without overloading the provider?

Write email jobs to a durable work queue; run workers with bounded concurrency and the provider's rate limit; batch where the API supports it; retry transient errors with backoff and jitter; send permanent failures to a DLQ; use idempotency keys; and monitor oldest-message age, success rate and throttling.

29

The backlog keeps growing after doubling workers. What do you check?

Arrival rate vs processing rate, oldest-message age, worker CPU, database or API saturation, lock contention, hot partitions, per-message latency, retry storms and poison messages. If the bottleneck is downstream, more workers can make it worse.

30

How do you safely replay a DLQ?

Fix or classify the root cause first, check schema and version compatibility, pick a bounded subset, replay at a controlled rate through the normal idempotent handler, watch downstream capacity, and keep an audit trail. Never bulk-replay blindly into the same failing dependency.

31

How do you evolve message schemas without breaking consumers?

Prefer backward-compatible additions, version events, never silently change a field's meaning, validate with a schema registry where useful, support old and new versions during migration, deploy consumers before producers for compatible changes, and define ownership and deprecation rules.

Check yourself

Quick quiz

6 questions. Pick an answer to see why it's right or wrong.

Question 1 of 60 / 6

An order event must reach notification, analytics and the warehouse. Which pattern?

Reference

Message queues glossary

The terms from this guide, in one line each.

Producer / consumer
The service that writes messages / the one that processes them.
Broker
The system that stores and delivers messages (Kafka, RabbitMQ, SQS…).
Work queue
Competing consumers: each message is handled by one worker.
Pub/sub
Each subscription receives its own copy of every event.
Partition
An ordered append-only log; a topic is split into several.
Offset
A record's position in a partition; consumer groups track progress by it.
Consumer group
Consumers sharing a topic's partitions; each partition has one owner.
ACK
The consumer's confirmation that a message is done.
Visibility timeout
How long a received message stays hidden before it can be redelivered.
DLQ
Dead-letter queue: where messages go after they can't be processed.
Idempotent consumer
Processing the same message twice has the same effect as once.
Transactional outbox
Writing the event in the same DB transaction as the change, then publishing it.
Summary

Key takeaways

  1. Queues decouple, buffer and level load. They trade immediate consistency for resilience and scale.
  2. Pick the pattern from semantics first: one worker (work queue), many systems (pub/sub), replay (log), ordering (keyed partitions), future work (delayed).
  3. Assume at-least-once delivery. Make every consumer idempotent with event IDs and unique constraints.
  4. Order per key, not globally: partition by the entity that needs ordering.
  5. Retry only transient failures, with backoff and jitter. Send the rest to a monitored DLQ with a replay plan.
  6. Use the transactional outbox whenever a database change and an event must both happen.
  7. Keep correctness-critical decisions (seat locks, payments) synchronous and atomic; queue the side effects.
Questions

Message queues: frequently asked questions

Why do we use a message queue in system design?

Message queues decouple producers from consumers, enable asynchronous processing, absorb traffic bursts and let each side scale and fail independently.

What is the difference between a queue and pub/sub?

In a work queue, each message is handled by one consumer. In pub/sub, every subscriber receives its own copy of each published event.

What is a dead letter queue?

A dead letter queue (DLQ) holds messages that couldn't be processed after the allowed retries, or that broke processing rules, so they stop blocking healthy traffic and can be inspected and replayed later.

When should I choose Kafka instead of RabbitMQ?

Choose Kafka when retained event history, replay, very high-throughput streams, partitioned ordering and many independent consumer groups are central. Choose RabbitMQ for flexible routing, classic work queues and acknowledgement-driven business messaging.

Does a message queue guarantee exactly-once processing?

Not end to end. Failures can still cause duplicate deliveries. Exactly-once business effects need a clearly defined scope plus idempotency, transactions, unique constraints or provider idempotency keys.

Where should queues be used in a booking system?

Keep seat locking and the immediate booking decision synchronous and atomic. Use queues for hold expiry, payment events, ticket generation, notifications, analytics and retries.

Next topicSQL

Every one of these systems ends in queries. Joins, CTEs, window functions, indexes and transactions, with interview problems.

Go deeperSee queues inside complete designs

Learn how caching, databases, load balancing, queues, rate limiting, concurrency and failure handling work together in systems like BookMyShow and Uber.

  • Kafka
  • Pub/sub
  • Retry
  • DLQ
  • Outbox
  • BookMyShow
Explore the book

Last reviewed 18 November 2026