AlgoViz

Queues & streams

medium 30 min

A message queue stores work between the program that asks for it and the program that does it.

Video lesson · Chapter 1 of 5

A message survives its producer

0:00 / 3:58

Message queue

1:16Reel

Queues & streams in one picture
Queues & streams in one picture

Theory

Read or listen first. About 1 min.

What it is

A message queue holds work that one program has sent and another has not yet done. The sender does not wait for the receiver. A log or stream is a close relative: it keeps messages in order for a while, and several readers can each go through them at their own pace.

Both put a buffer between programs, so that each can run, fail and grow on its own.

Why it exists

Some work does not have to finish before you answer the user: sending an email, resizing a picture, counting a click. Putting it in a queue makes the answer faster and survives a slow or broken receiver.

A queue also absorbs bursts. The cost is delay, and new questions: what if a message arrives twice, in the wrong order, or can never be processed? The requirements on this page answer those questions one at a time.

A short history

  1. 1993

    IBM releases MQSeries, a widely used commercial message queue.

  2. 2003

    Work that becomes the open AMQP standard begins at JPMorgan Chase.

  3. 2006

    Amazon SQS becomes generally available, a queue as a cloud service.

  4. 2007

    RabbitMQ is released, an open-source broker that speaks AMQP.

  5. 2011

    LinkedIn open-sources Kafka, a partitioned, replicated log built for very large streams of events.

Words to know

Producer and consumer
The program that sends, and the one that receives.
Acknowledgement
The consumer's word that the work is done and the message can go.
Visibility timeout
How long a received message stays hidden from other consumers.
Dead letter queue
Where messages go after failing too often.
At least once
Never lost, but may arrive twice.
Idempotent
Doing it twice has the same effect as once.
Partition
One ordered part of a stream.
Offset
A reader's position in a partition.
Consumer group
Readers that share the partitions.

How it works

Step through the idea, or press Play.

Step 1 of 3

Produce. The producer sends a message, and the queue stores it before it confirms

Understand it

Start here

The washing-up rack

Think of the evening after a big dinner. Nobody who brings a dirty plate waits until it is clean. They put it on the rack and leave. Whoever washes takes the next plate when their hands are free.

Plates waiting to be washed
12340Put it down

The rack is the queue, the card is the visibility timeout, and the red box needs somebody who looks inside it.

Why

What a queue gives you

A synchronous call ties your speed and availability to every service that you call. A broker in the middle lets the producer continue as soon as the message is stored. The pattern is explained in asynchronous communication; this page is about what the queue itself has to do.

  • Asynchronous

    The producer does not block while the work runs.

  • Buffering

    Messages are stored for a time until somebody can take them.

  • Load levelling

    A peak becomes a longer line instead of errors.

  • Decoupling

    Services deploy, scale and fail independently.

  • Reliability

    A message stays until the work is confirmed, if you set it up that way.

  • Ordering

    Messages of one key can be handled in order, if the queue supports it.

The life of a message

Seven steps from send to gone

Receive hides, acknowledge removes

The producer's wait ends after the message id. The consumer acknowledges only after the work.
  1. 1

    The producer sends

    A message is a payload plus metadata: an id, a time, perhaps a key and a type.

  2. 2

    The queue stores it

    It is written to disk, and normally to other machines, before the queue confirms.

  3. 3

    The consumer asks

    It polls, or the broker pushes when the consumer has room.

  4. 4

    The queue delivers

    The message is hidden for the visibility timeout. Each delivery gets its own receipt.

  5. 5

    The consumer works

    Business logic runs. A long job asks for more time before the timeout ends.

  6. 6

    The consumer acknowledges

    It sends the receipt of this delivery.

  7. 7

    The queue removes it

    No acknowledgement means that the message becomes visible again.

A queue service and the parts around it

A producer sends to a message queue service with three machines. Machine A stores the message and copies it to machines B and C. Two workers receive from the queue. Messages that failed too often go to a dead letter queue.
Thick borders are machines. The message is on three of them before the producer gets its confirmation.

Requirements 1

What the queue must do

Functional requirements

AreaThe queue must
ProduceAccept a payload and metadata, accept batches, return a message id, define how data is serialised
ConsumePoll or push, serve many consumers, hide received messages, filter if needed
Manage messagesRemove after acknowledgement, retry after failure, set aside in a dead letter queue, expire after a time to live
Manage queuesCreate and delete, report depth and age, purge, configure retention
Say which of these you need. Filtering and priorities, for example, cost complexity that many systems never use.

A small API

OperationCallNotes
SendPOST /queues/{name}/messagesReturns an id after the message is stored
ReceivePOST /queues/{name}/receiveChanges state, so it is not a GET. Takes a maximum and a wait time
AcknowledgeDELETE /queues/{name}/messages/{receipt}The receipt belongs to one delivery
ExtendPUT /queues/{name}/messages/{receipt}/visibilityMore time for a long job
Waiting a few seconds for a message inside one receive call is long polling. It saves many empty answers.

Requirements 2

What the queue must promise

Non-functional requirements, with example targets

QualityExample targetWhat it means here
Availability99.99%Sending works even while a machine is down
Durability11 ninesA message that was confirmed to the producer is not lost
Latencyunder 10 ms p99Fast send and receive, not counting the wait in line
Throughput100,000 a secondLarge volumes, normally by adding partitions
ScalabilityHorizontalMore traffic means more machines, not a new design
OrderingFIFO or by keyOrder inside a stated scope, never only the word ordered
These are targets for a discussion, not the numbers of any product. Ask which one the design may give up.

Delivery

Once, at least once, at most once

Three delivery guarantees

GuaranteeHowGoodBad
At most onceAcknowledge before the work, or do not retryFastest and simplestMessages can be lost
At least onceAcknowledge after the work, retry until thenNo lossDuplicates happen
Exactly-once effectAt least once, plus an idempotent consumer or one transactionEach message counts onceMore work and more state

Where does the crash fall?

No acknowledgement order avoids both loss and duplicates. The handler has to finish the job.

A network timeout cannot tell you whether the other side did the work. That is why true end-to-end exactly-once delivery cannot be promised across independent systems, and why most real systems choose at-least-once delivery with idempotent handling: unique request ids, unique constraints or upserts, in the same transaction as the effect. Some brokers do offer more inside their own boundary, for example deduplication of a repeated send or transactions between two topics of one broker.

Failure

Timeouts, retries and dead letters

The states of one message

Count receives, not reported failures. A worker that crashes never reports anything.

Do

  • Set the visibility timeout well above the normal work time, and extend it for long jobs
  • Make consumers idempotent
  • Configure a dead letter queue with an alert
  • Monitor depth and the age of the oldest message
  • Send, receive and acknowledge in batches

Do not

  • Assume order without checking its scope
  • Take work without acknowledging it afterwards
  • Put large files in a message; store the file and send a link
  • Ignore failed messages
  • Send a message and then block until the answer comes back

How long until a poison message is set aside?

t≈nreceives×tvisibility=3×30 s=90 st \approx n_{\text{receives}} \times t_{\text{visibility}} = 3 \times 30\ \text{s} = 90\ \text{s}
If a worker crashes on it every time. An explicit failure with a short delay is quicker than waiting for the timeout.

Patterns

Four ways to connect senders and receivers

  • Point to point

    One queue. Each message is handled by one consumer. Good for distributing tasks.

  • Publish and subscribe

    A topic. Every subscriber gets each message. Good for telling others that something happened.

  • Fan-out

    An exchange copies a message into several queues, one for each processing path.

  • Competing consumers

    Several workers read the same queue, so more workers mean more throughput.

Fan-out, then competing consumers

An order service sends one event to an exchange. The exchange puts a copy in the email queue and a copy in the stock queue. Two email workers compete for the email queue, and one stock worker reads the stock queue.
One event, two queues, three workers. The email workers share one copy, and the stock worker has its own.

Pub-sub has a page of its own. Note that fan-out plus competing consumers gives you both at once: every purpose sees each message, and every purpose can have many workers.

Sizing

How many workers, and how long is the line?

Suppose a photo site gets 864,000 uploads a day. That is 10 a second on average, and 30 a second at a 3x peak. One resize job takes 0.5 seconds. These are assumptions for the example.

Workers for the peak

n=λ×tu=30×0.50.8=18.75→19n = \frac{\lambda \times t}{u} = \frac{30 \times 0.5}{0.8} = 18.75 \to 19
λ\lambda is messages a second, tt the seconds for each message and uu how busy a worker may be. Leave room for retries.

Or accept a line for a while

B=(λin−λout)×T=(30−20)×3600=36,000tdrain=36,00020−10=3600 sB = (\lambda_{in} - \lambda_{out}) \times T = (30 - 20) \times 3600 = 36{,}000 \qquad t_{drain} = \frac{36{,}000}{20 - 10} = 3600\ \text{s}
With capacity for only 20 a second, a one-hour peak leaves 36,000 messages. Back at 10 a second they need another hour. Is a photo that is ready 30 minutes later acceptable? (36,000 / 20 = 1,800 s.)

Queue or stream

Point-to-point queues and append-only streams

Messaging systems fall broadly into two models: task queues, and event streams built on a log.

Stream on a log (for example Kafka)

  • Messages are appended to a log and stay after they were read.
  • Consumer groups read the same log, each at its own pace.
  • Readers keep an offset, so they can replay.
  • Order holds inside one partition.

Work queue (for example SQS, RabbitMQ queues)

  • A message is removed after it is acknowledged.
  • Competing workers share the messages.
  • A new service cannot replay what is gone.
  • Keeping order with many consumers is difficult.

Which one do I need?

Products overlap: RabbitMQ also has streams, and Kafka has share groups for queue-like reading.

Three well-known products

Amazon SQSRabbitMQApache Kafka
TypeManaged queueMessage brokerEvent streaming platform
OrderFIFO queues, by message groupPer queue; redelivery can change itPer partition
Kept for4 days by default, 14 at mostQueues: until acknowledged or expired. Streams: a size or age limit7 days by default, configurable
Good forSimple decoupling, serverless, no servers to runRouting, several protocols, priorities, request and replyEvent sourcing, stream processing, replay, high volume
Checked on the products' own pages in November 2026. Throughput depends on message size, replication and hardware, so measure it. One published limit: an SQS FIFO queue allows 300 calls a second for each action (3,000 messages with batches of ten), and far more in its high throughput mode.

Inside a stream 1

Commit log, replicas and the high watermark

Brokers for large streams avoid random disk writes. Each partition is an append-only series of segment files. Sequential writing suits both disks and the operating system's page cache and read-ahead. Log-based queues explains the files, indexes and cleanup.

Path of an appended message

A producer picks the partition by the hash of the key and sends to the leader broker, which appends to its log. Two follower brokers copy the log. The leader then acknowledges the producer.
The partition is hash(key) % num_partitions. Followers pull from the leader. With all in-sync replicas required, the ack waits for them.

Three ideas that make it durable

  1. 1

    In-sync replicas (ISR)

    The leader plus the followers that keep up within a time limit. A follower that hangs or is too slow leaves the set.

  2. 2

    High watermark

    The point up to which every in-sync replica has the log. Consumers do not read past it, so they never see a message that a failover could take back.

  3. 3

    Leader election

    If a leader fails, the cluster's controller promotes an in-sync replica. A lagging one is chosen only if unclean election is allowed, at the price of losing messages.

Inside a stream 2

Consumer groups share partitions

A consumer group combines two things: inside the group the work is shared, and different groups each see everything. Members join under one group id. If a member leaves or joins, the partitions are assigned again: a rebalance.

Python
import zlibclass Topic:    def __init__(self, partitions):        self.parts = [[] for _ in range(partitions)]        self.offsets = {}                      # (group, partition) -> next offset    def produce(self, key, value):        p = zlib.crc32(key.encode()) % len(self.parts)   # stable, unlike hash()        self.parts[p].append(value)        return p, len(self.parts[p]) - 1    def consume(self, group, p, limit=10):        start = self.offsets.get((group, p), 0)        return list(enumerate(self.parts[p]))[start:start + limit]    def commit(self, group, p, offset):        self.offsets[(group, p)] = offset + 1  # after processing: at least oncet = Topic(2)p, _ = t.produce("user-101", "order 1 created")t.produce("user-101", "order 1 paid")          # same key, same partitionfor offset, value in t.consume("fraud", p):    print("fraud reads", offset, value)    t.commit("fraud", p, offset)print("fraud, next poll:", t.consume("fraud", p))print("analytics still has", len(t.consume("analytics", p)))
A tiny stream broker: partitions, and one offset for each group. Messages stay after they were read.
Edit and run it in your browser

When to commit the offset

  1. 1

    At most once

    Commit before processing. A crash in the middle skips the message.

  2. 2

    At least once

    Commit after processing. A crash, or a lost commit, processes it again.

  3. 3

    Idempotent processing

    Duplicates come from retries and rebalances, so the effect must be safe to repeat.

Summary

The whole topic in one minute.

Queues and logs let programs work at different speeds. A queue hands each message to one worker and forgets it after the acknowledgement. A log keeps messages so that several readers can use them.

Receive hides, acknowledge removes, silence brings the message back. Expect duplicates and make handling idempotent. Order holds within a partition or message group, not across them. Watch the age of the oldest message: it tells you whether consumers keep up.

  • A queue stores, hides, waits for an acknowledgement and removes. Silence brings the message back.
  • State requirements with a scope: order by what, durable after which confirmation, delivered how often.
  • At-least-once delivery plus idempotent consumers is the normal choice.
  • Queues remove messages after the acknowledgement; streams keep them and let readers hold offsets.
  • Size workers from peak rate times work time, and alert on the age of the oldest message.

Sources