A message queue lets one service hand work to another without waiting for it: the producer writes a message to a broker, and consumers process it whenever they are ready. This decouples services in time and space, absorbs traffic spikes and makes failures retryable. Two families dominate: queues that delete messages once processed (RabbitMQ, Amazon SQS) and logs that keep an ordered, replayable history (Apache Kafka).
Think of it like
The ticket rail in a restaurant kitchen
Waiters clip order tickets onto a rail and go straight back to their tables; they never stand over a cook waiting for a dish. Cooks pull tickets when they are free. At the dinner rush the rail gets longer, but nobody is turned away, and adding a cook drains it faster. Pub/sub is the expediter who photocopies each ticket for the grill, the salad station and the bar.
Why asynchronous messaging?
Picture checkout calling the email, inventory, loyalty and analytics services synchronously. The user waits for all four, and the latencies add up. Worse, availabilities multiply: if each dependency is up 99.9% of the time, the chain is up only about 99.6% (0.999⁴). With a queue in between, checkout only needs the broker to accept one message.
Synchronous calls
- Caller blocks until every downstream service answers
- Latency is the sum of the chain; availability is the product
- A spike upstream hits every downstream service at once
- Simple to reason about; the response carries the result
Asynchronous messaging
- Producer returns as soon as the broker has the message
- Consumers can be slow, scaled, deployed or down independently
- The queue absorbs bursts and lets consumers work at a steady rate
- Adds eventual consistency, duplicates and a broker to operate
- Decoupling: producers do not know who consumes their messages or whether those consumers are running right now.
- Buffering: messages wait safely on disk while a consumer is restarting or deploying.
- Load leveling: a burst of 10× normal traffic becomes a longer queue, not 10× load on the database.
- Independent scaling: add consumers to drain a backlog without touching producers.
- Fan-out: one event can trigger any number of independent reactions.
Flash-sale peak
5,000 /s
orders for 10 minutes
Worker capacity
2,000 /s
limited by the payments API
Peak backlog
1.8M
(5,000 − 2,000) × 600 s
Drain time
~20 min
1.8M ÷ (2,000 − 500 /s after the peak)
Without the queue the payments integration would have rejected 60% of orders during the sale. With it, every order is accepted and processed within about 20 minutes. Use the simulation above to change producer and consumer rates and watch the backlog grow and drain.
- Producer / publisher
- Writes messages to the broker.
- Consumer / subscriber
- Reads and processes messages.
- Broker
- The server cluster that stores and delivers messages (Kafka, RabbitMQ, SQS).
- Acknowledgement (ack)
- The consumer's signal that a message was processed and may be removed or skipped.
- Offset
- In a log, the position of a message within a partition. Consumers track how far they have read.
- Consumer group
- A set of consumers that share the work of one subscription; each message goes to one member.
- Dead-letter queue (DLQ)
- Where messages go after failing too many times, so they stop blocking the main queue.
Point-to-point vs publish/subscribe
Point-to-point (work queue)
- Each message is processed by exactly one of many competing consumers
- Adding consumers increases throughput
- Use for tasks: resize this image, charge this card, send this email
- SQS queues, RabbitMQ queues with several consumers
Publish/subscribe
- Each message is delivered to every subscription
- Subscribers are added without changing the publisher
- Use for events:
OrderPlacedinterests billing, email and analytics - SNS topics, RabbitMQ fanout exchanges, Kafka with multiple consumer groups
Most real systems combine both: a topic fans out to one queue per subscribing service, and each service runs several competing workers on its own queue. The diagram below is the classic AWS version of that pattern (SNS to SQS).
Acknowledgements, retries and dead letters
- 1
Send
The producer sends a message; the broker stores it durably (replicated or on disk) and confirms.
- 2
Deliver
A consumer receives it. The broker marks it in-flight (RabbitMQ: unacked; SQS: invisible) rather than deleting it.
- 3
Process
The consumer does the work: writes to its database, calls an API, and so on.
- 4
Acknowledge
Only after the work succeeds does the consumer ack (RabbitMQ
basic.ack, SQSDeleteMessage, Kafka offset commit). - 5
Or redeliver
If the consumer crashes, disconnects or the timeout passes without an ack, the broker delivers the message again.
| Guarantee | How you get it | Risk | Typical use |
|---|---|---|---|
| At-most-once | Ack (or commit) before processing | Crash after ack loses the message | Metrics, logs where loss is acceptable |
| At-least-once | Ack after processing; retry on failure | Crash after work but before ack causes a duplicate | The default for almost everything |
| Exactly-once (effectively) | At-least-once delivery plus idempotent processing or transactions | Needs dedup keys or transactional sinks | Payments, balances, inventory |
Retries with backoff
Transient failures (a timeout, a 503 from a partner API) should be retried, but not immediately and not forever. Use exponential backoff with jitter so thousands of failed messages do not all retry in the same second. Queues support this with delay queues or per-message visibility changes. In Kafka, a failed record blocks its partition, so teams use retry topics (orders.retry.1m, orders.retry.10m) and a final dead-letter topic instead of retrying in place.
Visibility timeouts
In SQS a received message is invisible for the visibility timeout (default 30 seconds, maximum 12 hours). Set it longer than your worst-case processing time; if it is too short, a slow but healthy worker's message reappears and a second worker processes it in parallel. For long jobs, extend it as you go with ChangeMessageVisibility (a heartbeat).
Dead-letter queues
A poison message (bad payload, a bug triggered by one record) fails every time. Without a limit it is retried forever and burns capacity, or, in an ordered queue, blocks everything behind it. A redrive policy moves it to a DLQ after N attempts. Alert on DLQ depth, keep enough context (error, stack trace, attempt count) to debug, and redrive once fixed.
Ordering guarantees
Global ordering across all messages requires a single consumer, which caps throughput at one machine. Competing consumers, retries and redeliveries all reorder messages. The practical goal is per-key ordering: all events for order 42 are processed in sequence, while different orders proceed in parallel.
| System | Ordering guarantee |
|---|---|
| Kafka | Strict order within a partition. Records with the same key go to the same partition, so per-key order holds (as long as the partition count does not change). |
| SQS standard | Best-effort ordering, at-least-once delivery, nearly unlimited throughput. |
| SQS FIFO | Strict order within a message group ID, deduplication within a 5-minute window, lower throughput per queue. |
| RabbitMQ | FIFO per queue with a single consumer; multiple consumers or requeues can reorder. Use consistent-hash exchanges or single active consumer for per-key order. |
Kafka: the distributed log
Kafka is not a queue that deletes messages once read. It is an append-only, partitioned, replicated log. Producers append records to the end of a partition; consumers read sequentially and remember their position (the offset). Records stay until the retention period expires, whether or not anyone read them, so new consumers can replay history and a buggy consumer can rewind and reprocess.
- Topic
- A named stream of records, such as
orders. - Partition
- An ordered, append-only log; a topic is split into partitions spread across brokers. The unit of parallelism and ordering.
- Offset
- A record's sequential position within its partition (0, 1, 2, ...).
- Replication factor
- How many brokers hold a copy of each partition, typically 3. One replica is the leader; the others are followers.
- ISR (in-sync replicas)
- The replicas that are fully caught up with the leader. Only ISR members can become leader without losing acknowledged data.
- Consumer group
- Consumers sharing a
group.id. Each partition is assigned to exactly one member; each group tracks its own offsets. - Retention
- How long records are kept (7 days by default), by time or size. Log compaction instead keeps the latest record per key.
orders with 3 partitions, replication factor 3, and two consumer groups reading independently. Pick a flow above to animate a request.Partitions and parallelism
The partition count is the ceiling on consumer parallelism within a group, so size it for future peak throughput (a few partitions per expected consumer is common). Be careful adding partitions to a keyed topic later: hash(key) mod partitions changes, so new records for a key may land in a different partition than its old ones, breaking per-key order across the change.
Offsets and delivery semantics
- Commit after processing gives at-least-once: a crash between processing and commit replays a few records.
- Commit before processing gives at-most-once: a crash after commit skips records.
- Exactly-once within Kafka: an idempotent producer plus transactions lets a consume-transform-produce job write output records and its input offsets atomically; downstream readers use
isolation.level=read_committed. - Effects outside Kafka (a database write, an email) still need idempotency or an outbox pattern.
Retention, compaction and metadata
Time- or size-based retention keeps the last N days or bytes per partition. Log compaction instead keeps the latest record for every key, which turns a topic into a durable changelog (handy for rebuilding caches or state stores). Cluster metadata used to live in ZooKeeper; modern Kafka uses its built-in Raft quorum (KRaft), and Kafka 4.0 removed ZooKeeper support entirely.
RabbitMQ: smart broker, simple consumers
RabbitMQ (AMQP 0-9-1) puts routing logic in the broker. Producers never publish to a queue directly; they publish to an exchange with a routing key, and bindings decide which queues receive a copy. Messages are pushed to consumers, limited by a prefetch count, and removed once acked.
| Exchange type | Routes to queues whose binding... | Example |
|---|---|---|
| Direct | matches the routing key exactly | Key pdf goes to the pdf-render queue |
| Topic | matches a pattern: * is exactly one word, # is zero or more words | Binding order.*.eu matches order.created.eu |
| Fanout | exists at all (routing key ignored) | Broadcast cache invalidations to every node |
| Headers | matches message header attributes | Route on format=pdf and priority=high |
- Quorum queues replicate a queue across nodes with Raft; prefer them over classic mirrored queues for durability.
- Publisher confirms tell the producer the broker has safely stored a message.
- Dead-letter exchanges (
x-dead-letter-exchange) receive rejected, expired or over-length messages. - Streams (since 3.9) add a Kafka-like append-only log for replay and large fan-out.
Amazon SQS and SNS
SQS is a fully managed, pull-based queue: consumers long-poll (up to 20 seconds) for batches of up to 10 messages, then delete each one when done. Messages are retained for 4 days by default (up to 14). Standard queues scale almost without limit; FIFO queues add ordering and deduplication. SNS is managed pub/sub that pushes each message to every subscription: SQS queues, Lambda functions, HTTPS endpoints, email or SMS. SNS fanning out into SQS queues, as in the first diagram, gives you durable, independently scalable subscribers.
Backpressure
A queue hides a slow consumer only temporarily. If producers outpace consumers for long enough, the backlog grows without bound: latency climbs, memory or disk fills up, and old messages may expire before anyone processes them. Backpressure is any mechanism that pushes the slowdown back toward the source.
- Pull-based consumption: Kafka and SQS consumers fetch at their own pace, so a slow consumer never gets overwhelmed; only lag grows.
- Prefetch limits: RabbitMQ's
basic.qoscaps unacked messages per consumer. - Bounded queues and blocking: RabbitMQ blocks publishers when memory or disk alarms trip; in-process queues can block or reject on
put. - Shed load at the edge: return
429or503to clients when lag passes a threshold. See Rate Limiting. - Autoscale consumers: scale on queue depth or consumer lag (KEDA, SQS
ApproximateNumberOfMessagesVisiblealarms). - Drop or degrade low-priority work: message TTLs, separate priority queues, sampling analytics events.
Kafka vs RabbitMQ vs SQS
| Kafka | RabbitMQ | Amazon SQS | |
|---|---|---|---|
| Model | Partitioned, replicated log | Broker with exchanges, bindings and queues | Managed queue |
| Consumption | Pull; consumers track offsets | Push with prefetch (pull also possible) | Pull with long polling |
| After processing | Kept until retention expires; replayable | Deleted on ack | Deleted by the consumer |
| Ordering | Per partition | Per queue with a single consumer | Best-effort (standard), per group (FIFO) |
| Routing | Topic + key → partition | Rich: direct, topic, fanout, headers | None; use SNS or EventBridge for fan-out |
| Fan-out | Any number of consumer groups, cheap | One queue per subscriber | SNS to one queue per subscriber |
| Throughput | Very high; scales with partitions and brokers | High; scales with queues and nodes | Near-unlimited (standard), lower for FIFO |
| Operations | Significant (or a managed service) | Moderate | None; pay per request |
| Best for | Event streaming, CDC, analytics, event sourcing, replay | Task queues, complex routing, request/reply | Simple decoupling on AWS, serverless pipelines |
Common patterns
- Work queue: competing consumers process background jobs (image resizing, emails, reports).
- Fan-out events: one domain event triggers many independent services. See Event-Driven Architecture, CQRS & Event Sourcing.
- Transactional outbox: write the business row and an outbox row in one database transaction; a relay publishes outbox rows. This avoids the dual-write problem of "saved to DB but failed to publish". See Distributed Transactions.
- Request/reply: include
reply_toandcorrelation_idheaders to get an asynchronous response. - Claim check: store the large payload elsewhere and pass a reference.
- Stream processing: continuous jobs consume, aggregate and republish. See Batch & Stream Processing.
Implementation
Long-poll, process, and delete only after success. Failures simply reappear after the visibility timeout and eventually land in the DLQ.
import json
import boto3
sqs = boto3.client("sqs", region_name="us-east-1")
QUEUE_URL = "https://sqs.us-east-1.amazonaws.com/123456789012/inventory"
def handle(order: dict) -> None:
# Must be idempotent: the same message can be delivered more than once.
print("reserving stock for", order["orderId"])
while True:
resp = sqs.receive_message(
QueueUrl=QUEUE_URL,
MaxNumberOfMessages=10,
WaitTimeSeconds=20, # long polling: fewer empty responses
VisibilityTimeout=60, # hidden from other consumers while we work
)
for msg in resp.get("Messages", []):
try:
handle(json.loads(msg["Body"]))
except Exception as err:
# No delete: the message becomes visible again after 60 s.
# After maxReceiveCount failures, the redrive policy moves it to the DLQ.
print("failed, will be retried:", err)
continue
sqs.delete_message(QueueUrl=QUEUE_URL, ReceiptHandle=msg["ReceiptHandle"])Key takeaways
- Queues decouple producers from consumers in time, absorb bursts and let each side scale and fail independently.
- Point-to-point gives each message to one consumer; pub/sub gives every subscription its own copy.
- Ack after processing for at-least-once delivery, and make consumers idempotent to get exactly-once effects.
- Visibility timeouts, retries with backoff and dead-letter queues turn crashes and poison messages into manageable events.
- Kafka is a replicated, partitioned log: order is per partition, consumers track offsets and data can be replayed.
- Watch backlog age and consumer lag; apply backpressure or autoscale before the backlog becomes an outage.
Common pitfalls
- Assuming exactly-once delivery and writing non-idempotent consumers that double-charge on redelivery.
- Setting a visibility timeout shorter than processing time, so healthy work is processed twice in parallel.
- No dead-letter queue, letting one poison message retry forever or block an ordered partition.
- Creating too few Kafka partitions, capping consumer parallelism, then adding partitions and breaking per-key order.
- Publishing to the broker and writing to the database as two separate steps without an outbox.
Interview tips
- Justify the queue: name the work that can happen after the response and the burst it absorbs.
- State the delivery guarantee and how you make consumers idempotent.
- Choose Kafka when you need replay, high throughput or many independent consumers; choose SQS or RabbitMQ for simple task queues and routing.
- Mention partitioning by entity ID for ordering and DLQs plus lag-based alerting for operations.
Real-world applications
- Background jobs: sending emails, generating thumbnails, video transcoding.
- Event-driven microservices reacting to
OrderPlaced,UserSignedUpand similar events. - Change data capture pipelines streaming database changes into search, caches and warehouses.
- Log and metrics ingestion at very high throughput.
- Smoothing spiky traffic in front of rate-limited third-party APIs.
Test yourself
A consumer processes a message, then crashes before acknowledging it. What happens under at-least-once delivery?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.