The coat-check pile
Picture a busy museum. At the coat-check desk, the clerk writes a job on a ticket ("fetch coat 12") and pins it on a pile. Behind the desk, a few attendants work through the pile. Each attendant takes the top ticket, does the job and tears the ticket up.
Two things matter here. Every ticket goes to just one attendant at a time, so two attendants don't chase the same coat. And once a job is done, the ticket is gone: the pile only holds work still waiting to be done. When the museum gets busy, you add attendants and the pile goes down faster. This pile is a message queue.
With several attendants working at once, a quick job can finish before a slow one that was pinned earlier. The pile hands tickets out in order, but the jobs don't always finish in order.
Queues: work handed out once
A message queue holds messages until a consumer has processed them. Each message is delivered to one
consumer, and it's removed once that consumer acknowledges it: basic.ack in RabbitMQ, DeleteMessage
in SQS. Several consumers on one queue are competing consumers: the broker
spreads messages across them, so adding consumers adds throughput until the broker or a downstream system becomes the
bottleneck; unlike a stream, there's no partition count capping them.
Delivery differs by broker. RabbitMQ pushes messages to subscribed consumers, and a prefetch limit
(basic.qos) caps how many unacknowledged messages each one may hold. SQS consumers poll with
ReceiveMessage, usually with long polling.
A queue is a list of work still to do, not a record of what happened. Once a message is acknowledged, nothing is left to read again. And with competing consumers, processing order isn't preserved: a message that arrived second can finish first, so two messages about the same thing can be handled out of order.
The museum guestbook
By the museum door lies a guestbook. Every visitor writes one line on the next empty line, and nobody ever tears a page out. Each line has a line number.
Lots of people read the guestbook, and reading doesn't change it. The café manager reads it to see how busy the day is. The gift shop reads the same lines to send thank-you cards. Each keeps a bookmark to remember where they stopped, so each reads at their own speed.
A new curator who arrives next month can start at the first line and read everything that happened. That's the big difference: the coat-check pile is a list of jobs to do, and the guestbook is a history of what happened. This book is an event stream. The museum does take out very old pages after a while, so the history reaches back a long way, but not forever.
Streams: a log that stays
An event stream is an append-only, ordered log. Producers append events; each event gets a position
(an offset in Kafka, a sequence number in Amazon Kinesis Data Streams, an entry id
such as 1700000000000-0 in Redis Streams). Reading an event doesn't remove it. Events are kept until a
retention limit by time or size: in Kafka, log.retention.hours defaults to 168 (7 days) and topics can
override it with retention.ms; Kinesis keeps records 24 hours by default, extendable to 365 days.
The consumer, not the broker, owns its position. A Kafka consumer group commits its offsets to the broker
(__consumer_offsets), and a Kinesis application checkpoints sequence numbers. Because each group has its
own offsets, any number of groups read the same events independently.
That makes replay possible. A new consumer group can start at the earliest retained event, and an existing one can rewind its offsets to reprocess history after a bug fix. A queue can't do that, because it deleted the messages as they were handled.
When a job goes wrong
When an attendant takes a ticket, it leaves the pile so no one else takes the same job. But it isn't torn up yet. If the attendant trips and doesn't come back within a few minutes, the ticket goes back on the pile and someone else does the job. If the attendant was only slow, not hurt, two of them may end up fetching the same coat, so the desk must cope with a job done twice.
Sometimes a ticket can never be done: the number is smudged and the coat can't be found. Rather than let attendants try it forever, the desk counts the tries. After three, the ticket goes into a problem tray, called a dead-letter queue, and the manager looks at it later. The other jobs keep moving.
The guestbook works differently. Nothing is ever handed out, so nothing comes back. If a reader trips, they just open the book at their bookmark and read on from there, maybe reading a few lines twice.
Other things go wrong too. If the pile grows faster than the attendants clear it, you can see it getting taller and send for more help. A guestbook reader who falls far behind has a worse problem: the museum takes out old pages on a schedule, and if the reader's bookmark sits on a page that has been taken out, those lines are gone unread.
And if a trip sends a ticket back to the pile while its neighbours were already done, the jobs for one visitor may now be done out of order. Finally, if the desk itself closes for the night, nothing new can be pinned or written, so visitors must wait and try again: one who walks off without trying again loses the job, and one who asks twice may leave it twice. Whatever was already on the pile or in the book is still there when it opens.
What can go wrong
Queues acknowledge per message. A received message is in flight until it's acked:
- In SQS it's hidden for the visibility timeout (30 seconds by default, up to 12 hours). If it isn't deleted in time, it becomes visible and is delivered again.
- In RabbitMQ, unacknowledged messages are requeued when the consumer's channel or connection closes, or when
the consumer rejects them with
basic.nackorbasic.rejectandrequeue=true.
A stream tracks one offset per partition instead of an ack per message. The failures below look different on each.
- A consumer crashes mid-message. Queue: the message is redelivered, so delivery is at-least-once and a
message can be processed twice (for example, after the work was done but before the ack). RabbitMQ marks
redeliveries with the
redeliveredflag; in SQS, the message'sApproximateReceiveCountattribute is above 1. Stream: the group re-reads from the last committed offset, so everything after it is processed again; a rebalance aftermax.poll.interval.ms(5 minutes by default) of silence does the same to a merely slow consumer. Fix: make consumers idempotent (a unique message id or a natural key checked in the same transaction as the side effect). A visibility timeout shorter than the processing time causes duplicates with no crash at all. - A poison message. A message that always fails. Queue: it retries and returns to the queue until a dead-letter
queue takes it: SQS moves it after the redrive policy's
maxReceiveCountreceives, and RabbitMQ routes rejected, expired or (on quorum queues) over-delivered messages to a dead-letter exchange. Other messages keep flowing. Stream: the consumer can't move past the record without moving its offset, so it blocks its whole partition and lag on that partition climbs while the others stay healthy. A record that can't even be deserialized fails the same way (Kafka'sRecordDeserializationException). Fix: bounded retries, then park the record in a dead-letter topic (see the deep layer below), and alert on DLQ depth. - A slow consumer. Queue: the backlog grows. Watch queue depth and the age of the oldest message
(
ApproximateNumberOfMessagesVisibleandApproximateAgeOfOldestMessagein SQS); add consumers. Stream: the group's consumer lag (log end offset minus committed offset, shown bykafka-consumer-groups.sh --describe) grows, and adding consumers helps only up to the partition count. The worse case is unique to streams: retention deletes data the group hasn't read yet. The group's offset then points before the oldest retained record, the consumer gets an out-of-range error, andauto.offset.resetdecides what happens (latest, the default, jumps to the log end and silently skips even unread records that are still retained;earliestjumps to the oldest record left;by_duration:<duration>(Kafka 4.0+) goes back a fixed time;nonethrows). SQS has the analogous limit in its message retention period (4 days by default). Fix: alert on lag well before retention, and size retention for your worst outage. - Out-of-order processing. Queue: competing consumers finish in any order, and a redelivered message arrives
after later ones (RabbitMQ puts a requeued message back in its original position if it can, otherwise nearer the
head). Stream: order holds per partition only, and breaks if you handle records of one key on several threads or
send failures to a retry topic. Fix: partition or group by key (a Kafka key, an SQS FIFO
MessageGroupId), process one key at a time, and guard with a version or timestamp so stale updates are ignored (more in Ordering and scaling below). - A broker outage. Producers can't publish: a send fails or times out, and without care the event is lost or,
after a retry, duplicated. Use publisher confirms in RabbitMQ,
acks=allwith idempotent producers in Kafka (enable.idempotenceis on by default since Kafka 3.0), and an outbox table when the event must not be lost. A replicated broker survives a node loss only while a majority (quorum queues) ormin.insync.replicascopies stay up; below that,acks=allwrites are refused (NotEnoughReplicasException) rather than risk losing data. Consumers just pause, and a backlog or lag builds that they work off afterwards.
| Choice | You gain | You pay |
|---|---|---|
| Queue vs stream | Queue: per-message retries, dead letters, free scale-out. Stream: replay, ordering per key, independent groups | Queue: no replay and weak ordering. Stream: a poison record blocks a partition, parallelism capped by partitions, data expires |
| Ack after processing vs before | After: a crash redelivers, so nothing is lost (at-least-once) | Duplicates, so idempotent consumers. Acking before is at-most-once: no duplicates, but a crash loses the message |
| Ordering vs parallelism | One consumer per key or partition keeps order | Throughput and the slowest key set the pace; free competing consumers scale but reorder |
| Long vs short retention | Long retention gives slow consumers time to catch up and allows replay | More storage |
| Long vs short visibility timeout | Long visibility timeout gives fewer false redeliveries | Slower redelivery after a crash |
Redis Streams sit in between. XADD appends to a retained log, but a consumer group created with
XGROUP CREATE hands each entry to one consumer (XREADGROUP) and tracks it in a pending entries list
until XACK. Entries stay in the stream after the ack until it's trimmed (MAXLEN, MINID), and stuck
entries can be taken over with XAUTOCLAIM.
Parking poison records in a stream. Spring for Apache Kafka's DefaultErrorHandler retries a failing
record (by default nine more times, with no delay) and can then publish it to a dead-letter topic with a DeadLetterPublishingRecoverer,
so the partition moves on. Retry topics (@RetryableTopic) do the same with delays.
Keeping things in order
On a busy day one guestbook isn't enough, so the museum puts out three, one for names starting A to H, one for I to P and one for Q to Z. These are called partitions. Ana always signs the A to H book, so all of Ana's lines sit in that one book, in the order she wrote them.
A team of readers shares the books out: each book is read by just one member of the team, so the lines in each book are read in order. More readers make the team faster, but only up to three. A fourth reader would have no book left.
The coat-check pile is the opposite. Any number of attendants can help, but jobs finish in any order.
Ordering and scaling
The two shapes trade ordering against elastic scaling:
| Queue | Stream | |
|---|---|---|
| Ordering | Not kept across competing consumers, and redeliveries reorder | Per partition (Kafka) or shard (Kinesis), by key |
| Scaling consumers | Add consumers freely | One consumer per partition per group, so partitions cap parallelism |
| Ordered option | SQS FIFO per MessageGroupId; RabbitMQ single active consumer | Built in, per key |
In a stream, the producer picks a partition from the event's key, so all events with one key land in one partition, in order. Within a group, each partition is read by exactly one consumer, which keeps that order while processing. The cost is that a group can't use more consumers than there are partitions, and one slow partition holds up only its own keys, but holds them up completely.
Queues scale out with no such ceiling, which is why they suit bursty background work. If order matters there, you need an ordered variant, and you give up some throughput for it.
One visitor, many teams
When a visitor arrives, several teams may need to know: the coat-check, the café, the gift shop. With piles, every team needs its own pile, and a copy clerk pins a copy of each ticket on every pile. That copying is called fan-out. When a new team starts, the clerk adds a pile for it, but the new pile only gets tickets from that day on. All the visitors who came before are long gone.
With the guestbook, nobody copies anything. Every team reads the same book, and a new team simply opens it at the first page.
Fan-out
To deliver one message to several services with queues, you fan out into one queue per consumer: an SNS topic with an SQS queue subscribed for each service, or a RabbitMQ fanout exchange with a queue bound for each. Each queue gets its own copy, and each service acks and deletes its copy independently. A queue created later receives only messages published after it was subscribed or bound.
A stream needs no copies. Each service is a consumer group on the same topic. A new group starts from
the earliest retained event if auto.offset.reset=earliest (the Kafka default is latest, which starts at
new events only), so it can build its state from history.
Pile or guestbook?
Ask one question: is this a job that someone must do once, or a thing that happened that others might want to know about, now or later?
Hanging up Ana's coat is a job. It goes on the pile, one attendant does it, and the ticket is torn up. "Ana came in at ten" is a thing that happened. It goes in the guestbook, and the café, the gift shop and the curator each read it to keep their own lists. If the curator's tally turns out wrong, they start again from the first line and count again.
Many museums use both: the arrival goes in the guestbook, and a job ticket is pinned for the work it causes.
Choosing, with examples
Use a queue for commands and jobs that need doing once: sending a confirmation email, resizing an image, charging a card. You get per-message acks, retries, dead letters and easy scale-out, and the backlog is the only state.
Use a stream for facts that several consumers care about, now or later: building read models and search indexes, analytics, audit, change data capture. You get ordering per key, independent consumers and replay. Fix a bug in a projection, reset its group's offsets to the earliest retained event and rebuild it (the group must be inactive while you reset):
1kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group order-history \2--topic orders --reset-offsets --to-earliest --execute
In Spring the listeners look alike; the difference is what happens after your method returns:
1// Queue (Spring AMQP): the message is acked when the method returns, then it's gone.2@RabbitListener(queues = "emails")3public void sendEmail(EmailJob job) {4mailer.send(job.to(), job.template());5}67// Stream (Spring for Apache Kafka): the offset is committed, the record stays in the log.8@KafkaListener(topics = "orders", groupId = "order-history")9public void project(OrderPlaced event) {10orderHistory.upsert(event.orderId(), event);11}
With Spring AMQP's default AcknowledgeMode.AUTO, a listener exception rejects the message with requeue (unless
defaultRequeueRejected is false or you throw AmqpRejectAndDontRequeueException), so a poison message loops:
configure a dead-letter exchange and a retry limit. Since RabbitMQ 4.0, quorum queues dead-letter or drop a
message after 20 deliveries by default. For SQS, Spring Cloud AWS offers @SqsListener, which
deletes the message after the method succeeds.
The line is blurring. RabbitMQ has offered streams since 3.9: an append-only queue type with non-destructive reads, offsets and replay. Kafka now has queue-style share groups (KIP-932, "Queues for Kafka"), production-ready since Kafka 4.2: consumers in a share group read records of the same partition together, with per-record acknowledgement and delivery counting. Choose by the semantics you need, not the product name.
Combining them. A common shape is to publish events to a stream and let one consumer group turn the events that need work into queue messages, or to write events to the database and a stream together with an outbox table so the two can't disagree.