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.
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.
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
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.
{
"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 }
}| Field | Why it's there |
|---|---|
| eventId | A unique ID consumers use to deduplicate. |
| eventType | Which business fact this is. |
| version | Lets the schema evolve safely. |
| occurredAt | When it happened, not when it was processed. |
| correlationId | Traces one workflow across services. |
| payload | Only the data consumers actually need. |
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.
| Requirement | Start with | Why | Common mistake |
|---|---|---|---|
| One job → one worker | Work queue | Clear ownership; scale workers | Using pub/sub and doing the job several times |
| Many services react to one fact | Pub/sub | Each subscriber has its own progress | One competing queue, so only one service sees it |
| Replay history | Event stream / log | Retention + offsets | A destructive queue, and history is gone |
| Same entity stays ordered | Keyed partition / FIFO group | Order only where needed | Global ordering that kills throughput |
| Do it later | Delayed queue | No database polling | Assuming exact timing; ignoring races |
| Temporary failure | Retry queue | Backoff lets the dependency recover | Immediate, infinite retries |
| Permanent failure | DLQ | Isolate, inspect, replay safely | A DLQ nobody watches |
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.
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.
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
| Aspect | In practice |
|---|---|
| Ordering | Usually none, unless the queue offers FIFO. |
| Delivery | Usually at-least-once with ACK or delete. |
| Scaling | Add consumers until they keep up, within downstream limits. |
| Tech | RabbitMQ queues, SQS standard, Azure Service Bus queues. |
Work queue (competing consumers)
Many workers pull from one queue to share slow or expensive jobs.
A point-to-point queue used to spread jobs across a worker pool running the same logic.
The key controls are worker concurrency, prefetch or batch size, when you ACK, and downstream capacity. Too much prefetch is unfair; too little wastes fast workers.
Autoscale on queue depth and oldest-message age together: ten 30-minute video jobs and ten 20-ms jobs look identical by depth alone.
Best when
- CPU- or I/O-heavy background jobs
- Independent jobs
- Workers that scale horizontally
- Users don't wait for completion
Avoid or reconsider when
- Every downstream needs a copy
- Multi-stage jobs without an explicit workflow
- Strict cross-job ordering
| Aspect | In practice |
|---|---|
| Ordering | Weak: many workers run at once. |
| Delivery | At-least-once; ACK only after success. |
| Scaling | Autoscale workers while protecting databases and APIs. |
| Tech | RabbitMQ, SQS, Celery, cloud task queues, Redis job queues. |
Publish / subscribe
A publisher emits an event without knowing its subscribers; each subscriber gets its own copy.
Use it when an event matters to several independent systems. The publisher writes to a topic; each subscription receives the event independently.
Each subscriber owns its progress: notifications can fail while analytics succeeds. That independence is the core benefit of event-driven design.
Events should state facts (ORDER_CREATED, PAYMENT_SUCCEEDED), not disguised remote procedure calls.
Best when
- Several systems react to one business event
- Loose coupling
- Subscribers fail and scale independently
- New subscribers get added later
Avoid or reconsider when
- Exactly one worker should own the task
- The publisher needs a reply from every subscriber
- Unmanaged, unstable event contracts
| Aspect | In practice |
|---|---|
| Ordering | Usually per key or partition. |
| Delivery | Often at-least-once per subscription. |
| Scaling | Each subscription scales on its own; a slow one doesn't block others. |
| Tech | Kafka consumer groups, Google Pub/Sub, SNS → SQS, RabbitMQ exchanges. |
Fanout / broadcast
Every bound subscriber receives a copy of every message.
No routing key: every bound queue gets every message.
Good for system-wide events every subscriber cares about, such as configuration changes or cache invalidation.
One message becomes many deliveries, so budget for payload size × subscriber count × retries.
Best when
- Every subscriber needs every event
- Config changes and cache invalidation
- Independent audit and notification copies
Avoid or reconsider when
- Most consumers need only a subset
- Huge subscriber counts with large payloads
- Selective routing would cut traffic a lot
| Aspect | In practice |
|---|---|
| Ordering | Per subscriber queue. |
| Delivery | Each subscriber has its own ACK lifecycle. |
| Scaling | Subscribers scale independently; watch fanout amplification. |
| Tech | RabbitMQ fanout exchange, SNS → SQS, pub/sub subscriptions. |
Topic-based routing
Subscribers receive only the events whose routing key matches their pattern.
Between one-to-one and full broadcast. Producers publish meaningful keys such as payment.success, payment.failed or order.created.
Subscribers bind to exact keys or patterns like payment.*, so unrelated traffic never reaches them and ownership stays clear.
Topic naming is architecture. Without conventions and schema ownership, event names turn ambiguous and consumers turn brittle.
Best when
- Consumers need subsets of events
- Event families share one broker
- Stable, meaningful routing rules
Avoid or reconsider when
- Everyone needs everything (use fanout)
- Routing so clever it hides the workflow
- Using topics as authorisation
| Aspect | In practice |
|---|---|
| Ordering | Per topic, partition or queue, not global. |
| Delivery | Broker-dependent; usually durable at-least-once. |
| Scaling | Different keys feed independent queues and worker pools. |
| Tech | RabbitMQ topic exchanges, Kafka topic naming, SNS filtering. |
FIFO / ordered queue
Messages are processed in sequence, globally or (better) per key.
FIFO matters when processing M2 before M1 would produce an invalid state, such as CREATED → PAID → SHIPPED for one order.
Global ordering forces everything through one lane and kills parallelism. Large systems order per entity instead.
Hash orderId, bookingId or accountId to a partition or message group: different entities run in parallel, each one stays in order.
Best when
- State transitions that must apply in order
- Per-account ledgers
- Per-SKU inventory changes
- Workflow steps for one entity
Avoid or reconsider when
- Independent jobs
- Throughput matters more than order
- “Global ordering” without a business reason
| Aspect | In practice |
|---|---|
| Ordering | Global, or (preferably) per key / message group. |
| Delivery | Still often at-least-once: FIFO ≠ exactly-once. |
| Scaling | Scale across many keys, not within one ordered lane. |
| Tech | Kafka partitions, SQS FIFO groups, RabbitMQ single active consumer. |
Priority queue
Urgent work jumps ahead of bulk work.
Not all work is equally urgent: security incidents and payment reconciliation shouldn't wait behind a marketing blast.
A priority number alone isn't enough. Prevent starvation of low-priority work with ageing, weighted scheduling or reserved workers.
Many teams simply use a separate queue per priority, because it makes capacity explicit.
Best when
- Real differences in urgency
- SLA tiers
- Incidents that must skip the bulk backlog
Avoid or reconsider when
- Everything marked high priority
- Fairness is the requirement
- No actual SLA difference
| Aspect | In practice |
|---|---|
| Ordering | Priority beats FIFO across levels; FIFO within a level. |
| Delivery | Same as the underlying queue. |
| Scaling | Separate pools or reserved capacity for high priority. |
| Tech | RabbitMQ priority queues, separate SQS queues, job frameworks. |
Delayed / scheduled queue
A message becomes available only after a delay or at a scheduled time.
Represents future work without repeatedly scanning a database: the broker holds the job until it's due.
Great for hold expiry, retry-after delays, reminders and cart abandonment. Treat the timing as approximate unless the technology promises otherwise.
For months-long horizons or millions of long timers, a scheduler plus a durable table may fit better than the broker.
Best when
- Short and medium future actions
- Hold or lock expiry
- Retry after backoff
- Reminder workflows
Avoid or reconsider when
- Sub-millisecond timer precision
- Jobs scheduled months ahead
- Brokers without clean delay support
| Aspect | In practice |
|---|---|
| Ordering | Due-time order isn't exact under retries. |
| Delivery | Inherits at-least-once from the queue. |
| Scaling | Partition timers; make handlers idempotent. |
| Tech | SQS delay/timers, RabbitMQ delayed messages, Redis sorted sets, schedulers. |
Retry queue
Temporarily failed work is retried later, with backoff, instead of hammering the dependency.
Retries are for transient failures: timeouts, 5xx, rate limits, short outages. Validation errors shouldn't loop through retries.
Use bounded attempts, exponential backoff and jitter, so thousands of failed messages don't all retry in the same second.
Common tiers: 5 s → 30 s → 5 min → DLQ, carrying the attempt count and last error with the message.
Best when
- Temporary downstream failures
- Recoverable timeouts
- Provider rate limits with retry hints
- Brief database or network issues
Avoid or reconsider when
- Invalid payloads
- Business-rule rejections
- Permanent auth failures
- Non-idempotent side effects
| Aspect | In practice |
|---|---|
| Ordering | Retries can break order unless built into the ordered lane. |
| Delivery | At-least-once by design; handlers must be duplicate-safe. |
| Scaling | Separate retry traffic so old failures can't swamp fresh work. |
| Tech | Retry queues/exchanges, SQS redrive, Kafka retry topics. |
Dead-letter queue (DLQ)
Messages that can't be processed are isolated for investigation and controlled replay.
Stops poison messages from blocking healthy traffic forever. They arrive after exhausting retries or failing validation.
The DLQ isn't the end: you need alerts, dashboards, failure metadata, inspection tools and a safe replay path after the fix.
Blind bulk replay can repeat the outage. Replay rate-limited, observed, and filtered by failure reason or version.
Best when
- Isolating poison messages
- Operator visibility
- Controlled replay after a fix
Avoid or reconsider when
- Replacing input validation
- Nobody owns monitoring or replay
- Sensitive payloads without retention controls
| Aspect | In practice |
|---|---|
| Ordering | Pulling one message out lets later ones pass. |
| Delivery | Stores failed deliveries for inspection. |
| Scaling | Should stay small; sudden growth is an incident. |
| Tech | SQS DLQ, RabbitMQ dead-letter exchange, Kafka DLT, Service Bus. |
Request-reply over messaging
A command goes out with a correlation ID and reply address; a response message comes back.
Useful when transport must be queued but the caller still wants a response. The request carries a correlationId and a replyTo.
Harder than HTTP: timeouts, abandoned replies, correlation state and duplicate responses all need handling.
Use it for long-running or disconnected work; for ordinary low-latency calls, HTTP or gRPC is simpler.
Best when
- Messaging is the required transport
- Requests outlive the caller's connection
- Queued requests with eventual responses
Avoid or reconsider when
- Plain low-latency RPC is enough
- Callers can't handle async timeouts
- Correlation state isn't worth it
| Aspect | In practice |
|---|---|
| Ordering | By correlation ID, not globally. |
| Delivery | Both directions need reliability and idempotency. |
| Scaling | Workers scale like a work queue. |
| Tech | RabbitMQ reply-to, JMS request/reply. |
Event stream / append-only log
Events are appended to a retained, ordered log that consumers read and replay independently.
Unlike a destructive queue, consuming advances a consumer offset; the event stays for everyone else.
Retention enables replay: a new analytics consumer can start from old offsets, or a fixed consumer can rebuild its state.
Partitions provide scale: the same key goes to the same partition (ordered); different keys spread across partitions (parallel).
Best when
- Replay matters
- Many independent consumers
- High-throughput pipelines
- CDC, analytics, event sourcing
Avoid or reconsider when
- A small task queue is all you need
- Partitions and retention are unneeded complexity
- Rich per-message routing dominates
| Aspect | In practice |
|---|---|
| Ordering | Within a partition, not across the topic. |
| Delivery | Commonly at-least-once; stronger within platform scope. |
| Scaling | More partitions → more consumers per group. |
| Tech | Apache Kafka, Redpanda, Amazon Kinesis, Pulsar. |
Consumer groups
Consumers in one group share a topic's partitions; separate groups each read the whole stream independently.
Different groups, same stream
Delivery guarantees
What can happen to a message when producers, brokers or consumers fail.
| Guarantee | Deliveries | Risk | You must… |
|---|---|---|---|
| At-most-once | 0 or 1 | Messages can be lost | Accept loss (metrics, logs) |
| At-least-once | 1 or more | Duplicates | Make consumers idempotent |
| Exactly-once | One business effect | Hard to guarantee end to end | Define the scope; use idempotency or transactions |
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
const partition = hash(orderId) % partitionCount;
// same orderId → same partition → processed in orderAcknowledgements and visibility timeouts
The broker needs to know when processing really finished.
What if the consumer crashes before the ACK?
Idempotent consumers
If the same message arrives twice, processing it twice must not duplicate the business effect.
async function handlePayment(message) {
await paymentProvider.charge(message.userId, message.amount);
}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).
Retries and backpressure
Give temporary failures time to recover, and don't let a queue hide sustained overload.
// 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
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.
Kafka internals
Kafka is best understood as a partitioned, replicated, retained log, not just a faster queue.
| Concept | What it means |
|---|---|
| Topic | A named stream of events, e.g. booking.events, split into partitions. |
| Partition | An ordered, append-only log. Order is guaranteed inside one partition only. |
| Offset | A record's position in its partition; groups track progress by offset. |
| Leader & replicas | One broker leads each partition; followers copy it for durability (acks=all + min.insync.replicas). |
| Consumer group | Each partition is owned by one active consumer in the group. |
| Retention | Events stay for a configured time or size after being read, which enables replay. |
| Rebalance | Partitions move when consumers join or leave; processing pauses briefly. |
| Hot partition | A skewed key overloads one partition while others idle. |
RabbitMQ internals
A traditional broker with powerful routing before messages ever reach a queue.
| Exchange | Routing rule | Good for | Example |
|---|---|---|---|
| Direct | Exact key match | Simple explicit routing | payment.success → booking.queue |
| Topic | Wildcards (* = one word, # = any) | Event families | payment.* or order.# |
| Fanout | Every bound queue | Broadcast | config.changed → all services |
| Headers | Match on headers | Metadata routing | x-region=IN, x-tier=premium |
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.
Kafka vs RabbitMQ vs managed queues
Their messaging models are different. Choose the model, then the product.
| Kafka-style log | RabbitMQ-style broker | Managed queue | |
|---|---|---|---|
| Core model | Distributed retained log | Broker with exchanges and queues | Hosted queue service |
| Replay | Native | Not its model | Service-dependent |
| Routing | Topics + partitions | Rich exchange routing | Queues, topics, filters |
| Streaming throughput | Excellent | Good | Service-dependent |
| Task queue | Possible | Very natural | Very natural |
| Operations | Significant (unless managed) | Significant (unless managed) | Mostly the provider's |
| Typical use | Events, CDC, analytics pipelines | Jobs, routing, business messaging | Cloud-native async jobs |
Quick picks for interview scenarios
| Scenario | Start with |
|---|---|
| 10M analytics events a day, with replay | Kafka-style log |
| Generate an invoice once, in the background | Work queue / managed queue |
| Order event → analytics + notification + warehouse | Pub/sub or stream with separate groups |
| payment.success → booking; payment.failed → recovery | Topic or direct routing broker |
| Release a booking hold after 5 minutes | Delayed queue / scheduler + queue |
| Same order's events must stay sequential | Partition (or FIFO group) keyed by orderId |
| Small team, durable jobs, minimal ops | Managed queue |
| Replayable CDC into a warehouse | Kafka / Kinesis / Pulsar |
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.
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;Code examples
In interviews you explain the design rather than write framework code, but these make the lifecycle concrete.
@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);
}
}@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()));
}
}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;
}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
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 doesExpiry, and its race with payment
Confirm + outbox, then fan out
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;| Operation | Sync or async | Why | Pattern |
|---|---|---|---|
| Search shows | Sync | User needs results now | None |
| Acquire seat lock | Sync | Immediate correctness decision | None for the lock itself |
| Create payment intent | Usually sync | User enters payment now | Events may follow |
| Payment callback | Durable + idempotent | Must survive retries and duplicates | Event / queue |
| Hold expiry | Async, delayed | Future action at T + N | Delayed queue |
| Ticket generation | Async | Can finish after confirmation | Work queue |
| Email / SMS | Async | Provider slowness mustn't fail booking | Work queue + retry + DLQ |
| Analytics | Async | Eventually consistent | Pub/sub / stream |
Failure scenarios to explain
Payment callback delivered twice
Provider idempotency key + unique payment transaction + idempotent state transition.
Payment arrives after the hold expired
Reconciliation; never book a seat someone else may now hold.
Expiry event delivered twice
Conditional release on state and version; the second is a no-op.
Email provider down
Booking stays confirmed; notifications retry and DLQ if exhausted.
Broker down right after the commit
The outbox keeps the event until the publisher can deliver it.
Consumer commits, then crashes before ACK
Redelivered; eventId keeps it idempotent.
Blockbuster traffic spike
Queue non-critical work, autoscale consumers, rate-limit, watch oldest-message age.
One show creates a hot partition
Key by bookingId (not showId) unless per-show ordering is truly needed.
Failure scenarios and metrics
Queues move complexity rather than remove it. Design for crashes, duplicates, backlog and poison messages.
| Failure | Response |
|---|---|
| Consumer crashes | Never ACK unfinished work; the message is redelivered. |
| Duplicate message | Idempotency keys, unique constraints, processed-event tracking. |
| Poison message | Bounded retries, then DLQ with metadata and an alert. |
| Consumer too slow | Watch lag and age, scale workers, check downstream bottlenecks. |
| Broker node fails | Replication, durable storage, acks=all for important topics. |
| Producer retries after a timeout | Stable event IDs and idempotent producers prevent duplicates. |
| DB commit succeeds, publish fails | Transactional outbox. |
| Retry storm | Backoff, jitter and bounded retries. |
| Backlog grows forever | Autoscale, throttle producers, prioritise, alert on sustained lag. |
| Schema change | Versioned 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
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.
1Why 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.
2When 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.
3Queue 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”.
4Fanout 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.
5FIFO 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.
6At-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.
7Why 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.
8How 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.
9What 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.
10How 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.
11What 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.
12How 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.
13What 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.
14What 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.
15Queue 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.
16Why 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.
17A 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.
18What 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.
19How 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.
20Direct 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.
21What 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.
22When 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.
23What 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.
24What 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.
25Command 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.
26Should 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.
27How 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.
28How 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.
29The 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.
30How 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.
31How 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.
Quick quiz
6 questions. Pick an answer to see why it's right or wrong.
An order event must reach notification, analytics and the warehouse. Which pattern?
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.
Key takeaways
- Queues decouple, buffer and level load. They trade immediate consistency for resilience and scale.
- Pick the pattern from semantics first: one worker (work queue), many systems (pub/sub), replay (log), ordering (keyed partitions), future work (delayed).
- Assume at-least-once delivery. Make every consumer idempotent with event IDs and unique constraints.
- Order per key, not globally: partition by the entity that needs ordering.
- Retry only transient failures, with backoff and jitter. Send the rest to a monitored DLQ with a replay plan.
- Use the transactional outbox whenever a database change and an event must both happen.
- Keep correctness-critical decisions (seat locks, payments) synchronous and atomic; queue the side effects.
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.
Every one of these systems ends in queries. Joins, CTEs, window functions, indexes and transactions, with interview problems.
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
Last reviewed 18 November 2026