How systems work

Message queues.

A message queue lets one part of a system hand work to another without waiting for it. The web server writes “send this receipt” into the queue and answers the customer at once. An email worker picks the message up when it is free.

That small idea brings its own problems: messages that arrive twice, messages that never arrive, work done out of order, and one bad message that blocks everything behind it. This page shows each one happening, then the fix.

In the labs after the walkthrough, every coloured chip is a single message in a simulation running in your browser. The letter is its key, such as a customer, and the number is its place in that key’s order. A3 is customer A’s third message. A dark chip marked !B2 always fails. A small number on a chip’s corner counts how many times it has been delivered. A faded chip is waiting out its visibility timeout.

00 The life of one message

Before the live labs, follow a single message from start to finish. Step through at your own pace, or press Play all.

Checkout serviceProducerBrokerStores messages on diskQueueEmail worker 1ConsumerCustomer inboxcreates workstores it until it is donedoes the work

Step 1 of 10

Meet the pieces

A queue has three parts. The producer creates work, the broker stores it, and the consumer does it. The producer and consumer never talk to each other directly; everything goes through the broker.

01 Why put a queue in the middle

Without a queue, the caller waits on the callee. If the email service is slow, checkout is slow. If it is down, checkout fails. With a queue, the producer only waits for the broker to store the message, a few milliseconds, and the consumer works at its own pace.

The queue also absorbs bursts. Producers can briefly send faster than consumers can work, and the extra messages wait in line instead of failing.

Producer1/sQueue (broker)ConsumersWaitingConsumer 1Idle
Waiting
0
Oldest wait
0.0s
Processed
0

Click any chip to follow that one message.

One producer, one consumer taking about 0.8 seconds per message. Send a burst and watch the line grow, then drain.
    Try this. Raise messages per second to 2. One consumer manages about 1.25 a second, so the line now grows without end and the oldest wait climbs with it. Add a second consumer and watch it drain.

    Watch two numbers on any queue: how many messages are waiting, and how long the oldest one has waited. A depth that keeps growing means consumers are slower than producers.

    02 Acks: lost or duplicated, pick one

    The broker cannot see inside a consumer. It only knows a message is finished when the consumer says so with an ack. When to send that ack is the most important choice in queue design.

    • Ack when received (at-most-once). If the consumer dies mid-way, the broker already thinks the message is done. It is lost.
    • Ack after the work (at-least-once). Nothing is lost, but if the consumer dies after doing the work and before the ack, the message is delivered again and the work runs twice.
    Producer1/sQueue (broker)ConsumersWaitingConsumer 1IdleConsumer 2Idle
    Processed
    0
    Duplicates
    0
    Lost
    0

    Click any chip to follow that one message.

    Two consumers. Crash one and see what happens to the message it was holding.
      Try this. With ack after processing on, press “Crash a consumer after it works”. The message comes back and is processed again: a duplicate. Now turn ack after processing off and press “Crash a consumer mid-way”. That message is never finished.

      Exactly-once delivery over a network is not something a broker can promise on its own. Real systems choose at-least-once and make processing safe to repeat (section 04).

      03 The visibility timeout

      With ack after processing, a received message is not deleted. It is hidden for a while (Amazon SQS calls this the visibility timeout; Google Pub/Sub calls it the ack deadline). If no ack arrives in time, the broker assumes the consumer died and hands the message to someone else.

      That is how crashed work gets retried. It is also a trap: if the work takes longer than the timeout, the message is handed out again while the first consumer is still working on it.

      Producer1/sQueue (broker)ConsumersWaitingConsumer 1IdleConsumer 2Idle
      Processed
      0
      Duplicates
      0

      Click any chip to follow that one message.

      Work takes 2.2 seconds but the timeout is 1.5 seconds. Faded chips are hidden, waiting for their timeout.
        Try this. Watch duplicates climb with no crash at all. Raise the visibility timeout above the work time and they stop.

        Set the timeout comfortably above your slowest job, or have long jobs extend it while they run.

        04 Idempotency: making repeats harmless

        Since duplicates will happen, make processing safe to run twice. The usual ways:

        • Record each message id you have processed, in the same transaction as the work, and skip ids you have seen.
        • Pass an idempotency key to outside services, so a repeated charge returns the first result.
        • Write with upserts (“set the status to shipped”), not increments (“add one to shipped”).
        Producer1/sQueue (broker)ConsumersWaitingConsumer 1IdleConsumer 2Idle
        Processed
        0
        Duplicates
        0
        Repeats skipped
        0

        Click any chip to follow that one message.

        Same crash as before. Turn on the id check and crash again.
          Try this. Crash a consumer with the id check off, then turn it on and crash again. The repeat is still delivered, but now it is skipped instead of run.

          At-least-once delivery plus idempotent processing gives you the effect of exactly-once. This is what “exactly-once” usually means in practice.

          05 Poison messages and the dead-letter queue

          Some messages fail every time: a malformed payload, a deleted account, a bug. With unlimited retries a poison message comes back again and again, wasting consumer time forever.

          The fix is a cap on attempts. After the last attempt the broker moves the message to a dead-letter queue (DLQ), where a person can look at it, fix the cause and replay it.

          Producer2/sQueue (broker)ConsumersWaitingConsumer 1Idle
          Processed
          0
          Failed attempts
          0
          Dead-lettered
          0
          Waiting
          0

          Click any chip to follow that one message.

          Every fourth message is poison. Watch the attempt counters on the dark chips.
            Try this. Set attempts before dead-letter to 3. Poison messages now leave after their third try and stop eating the consumer’s time.

            Alert when anything lands in the DLQ. A dead-letter queue nobody reads is a slower way of losing messages.

            06 More consumers, less order

            Adding consumers to a queue scales throughput almost in a straight line, because they compete for the next message. The cost is order. A2 can be picked up just after A1 by a faster consumer and finish first.

            Producer5/sQueue (broker)ConsumersWaitingConsumer 1IdleConsumer 2IdleConsumer 3Idle
            Processed
            0
            Out of order
            0

            Click any chip to follow that one message.

            Three consumers whose work time varies. Messages for the same key now finish out of order.
              Try this. Drop to one consumer: order comes back, but it can no longer keep up. You need both, and that is what partitions are for.

              If order matters for each customer or account but not across them, you want order per key, not one global order.

              07 Partitions, offsets and consumer groups

              A log-based broker such as Kafka works differently. Messages are appended to partitions, and the key decides which one, so every message for customer A lands in the same partition. Each partition is read by exactly one consumer in a group, in order. The consumer records how far it got by committing an offset.

              • Order is kept within a partition, so it is kept per key.
              • Parallelism is capped by the number of partitions. Extra consumers sit idle.
              • When consumers join or leave, the group rebalances: reading pauses, partitions are reassigned and each one rewinds to its last committed offset. Uncommitted work runs again.
              • Messages stay in the log after they are read, so a new group can replay history from the start.
              Producer4/sLog (broker)Consumer groupPartition 0 · committed 0Partition 1 · committed 0Partition 2 · committed 0Consumer 1IdleConsumer 2Idle
              Processed
              0
              Out of order
              0
              Waiting
              0

              Click any chip to follow that one message.

              Three partitions, keyed by letter. Lines show which consumer owns which partition.
                Try this. Add consumers until there are four. One gets no partition and does nothing. Each change triggers a rebalance: watch reading pause. Out-of-order stays at zero throughout.

                08 One bad message can block a partition

                A log cannot skip a message without breaking order, so a consumer that keeps failing on one message stops its whole partition. Everything behind it waits, while the other partitions carry on.

                Producer4/sLog (broker)Consumer groupPartition 0 · committed 0Partition 1 · committed 0Partition 2 · committed 0Consumer 1IdleConsumer 2IdleConsumer 3Idle
                Waiting
                0
                Failed attempts
                0
                Dead-lettered
                0

                Click any chip to follow that one message.

                Every seventh message is poison. A partition that hits one stops moving.
                  Try this. Set attempts before dead-letter to 3. The stuck message moves to the DLQ, its partition moves on and the backlog drains.

                  09 Fan-out: publish once, many readers

                  Often several services care about the same event. An order placed should send an email, update analytics and refresh the search index. With publish/subscribe, the producer publishes once to a topic and each subscription gets its own copy, its own queue and its own pace.

                  Producer2/sTopic, one queue per subscriptionConsumersEmailAnalyticsSearch indexConsumer 1IdleConsumer 2IdleConsumer 3Idle
                  Processed
                  0
                  Waiting
                  0

                  Click any chip to follow that one message.

                  One topic, three subscriptions. The search indexer is slow.
                    Watch. The search index falls behind, and email and analytics do not care. A slow subscriber only delays itself.

                    The viral feed system uses this at scale: one post, fanned out to every follower’s timeline.

                    10 When the queue fills up

                    A queue hides overload until it doesn’t. An unbounded queue keeps accepting work, so the wait grows and grows: by Little’s law, time in queue is roughly depth divided by throughput. A bounded queue rejects new messages when it is full, which tells producers to slow down. That signal is called backpressure.

                    Producer3/sQueue (broker)ConsumersWaitingConsumer 1Idle
                    Waiting
                    0
                    Oldest wait
                    0.0s
                    Rejected
                    0

                    Click any chip to follow that one message.

                    Three messages a second into one consumer, with room for ten.
                      Try this. Set max depth to no limit: nothing is rejected, but the oldest wait climbs without end. Bound it again and the wait stays short, at the cost of rejections. More consumers fix both.

                      Pick what happens when you are full: reject and let producers retry, drop the least important work, or add consumers. Autoscaling on queue depth, not CPU, is the usual answer for worker pools.

                      11 Choosing a broker

                      Every broker makes the trade-offs above in its own way. A rough map:

                      BrokerModelOrderReplayGood for
                      Amazon SQSQueue, visibility timeout, DLQ by redrive policyBest effort (standard); per message group (FIFO)NoBackground jobs with little to run
                      RabbitMQQueues fed by exchanges (direct, topic, fanout), acks, dead-letter exchangesPer queue, until consumers competeOnly with streamsRouting rules, task queues
                      Apache KafkaPartitioned log, consumer groups, offsetsPer partitionYes, within retentionEvent streams, high volume, many readers
                      Redis StreamsLog with consumer groups and a pending listPer streamYes, bounded by memoryLightweight streams next to an existing Redis
                      Google Pub/SubTopics and subscriptions, ack deadlineWith ordering keysWith seek and retentionManaged fan-out

                      Check the current docs before you choose: these products add features every year, and limits differ by plan.

                      12 Check yourself

                      1. A consumer charges a card, then crashes before it acks the message. The queue is at-least-once. What happens?

                      2. Jobs take up to 40 seconds. The visibility timeout is 30 seconds. Nothing crashes. What do you see?

                      3. All events for one account must be handled in order, and you need ten consumers. What do you do?

                      4. A consumer group has 12 consumers reading a topic with 8 partitions. How many consumers do work?

                      5. One malformed message fails every time. Retries are unlimited. What goes wrong?

                      Next partLoad balancers