04. Communication / Lesson 2 of 4

Message Queues

Put slow work in a line and let workers handle it later.

  • 10 min
  • Intermediate
  • 11 steps
  • Queue depth—
  • Workers—
  • Signup p99850 ms (warning)
UsersSignup API⚠ 850 msEmail provider800 ms
  • Request
  • Response
  • Health check
  • Failed request
Step 1/11

Step 1 of 11: The user waits for the email

Read every step as text
  1. Step 1: The user waits for the email

    A signup request does 50 ms of its own work, then sends a welcome email by calling an email provider, which takes about 800 ms. The user waits for both: about 850 ms (we ignore the slow tail for now).

    And if the provider is down, the whole signup fails, even though the account was created fine. The user does not need the email *before* the page loads.

    Work the user does not need right now should leave the request path.

  2. Step 2: Write a note and answer at once

    Instead of sending the email, the API drops a small message into a queue: { "type": "welcome", "user": 42 }. That takes about 2 ms, and the API answers right away.

    Signup now takes 50 + 2 = 52 ms. The email is sent later by someone else, and a provider outage no longer breaks signup.

    A queue turns "do it now and wait" into "promise to do it soon". The HTTP answer is often 202 Accepted.

  3. Step 3: Producers write, consumers read

    The code that puts messages in is the producer (the API). The code that takes them out is the consumer (a worker). They never call each other, and each can be changed, restarted or scaled alone.

    A worker takes the oldest message, does the job (sends the email) and asks for the next one. Messages leave the queue in roughly first-in, first-out order.

    The queue is a buffer between a fast producer and a slower consumer.

  4. Step 4: 4 workers share the line

    One worker sends an email in 800 ms, so it finishes 1000 / 800 = 1.25 emails a second. With 4 workers the pool handles 4 × 1.25 = 5 a second.

    Normal load is 3 signups a second, so the pool is about 60% busy and the queue stays almost empty. Each message goes to only one worker.

    Need more speed? Add workers. They are stateless, so any number can read the same queue.

  5. Step 5: A spike fills the queue, not the servers

    A promotion sends 20 signups a second for 60 seconds. The workers can only do 5 a second, so the queue grows by 20 − 5 = 15 a second: 900 messages waiting after 60 s.

    Signup still takes 52 ms, because the API only writes to the queue. When the spike ends, the pool has 2 a second of spare capacity, so it needs about 450 seconds to catch up. Starting 4 more workers when the spike ends would clear that backlog in about 129 seconds.

    Users do not wait, but the last email is sent minutes late. Watch the queue depth and the age of the oldest message.

  6. Step 6: A message stays until it is acknowledged

    When a worker takes a message, the queue does not delete it. It hides it for a while (a visibility timeout, say 30 seconds). The worker sends an ack only after the email is sent, and then the message is deleted.

    If the worker crashes before the ack, the timeout runs out and the queue gives the same message to another worker. This is redelivery: no message is lost with a crash.

    Ack after the work is done, never before. An early ack loses the job if the worker dies.

  7. Step 7: At-least-once means sometimes twice

    Suppose a worker sends the email and crashes just before the ack. The message comes back, and the user gets two welcome emails. Queues usually promise at-least-once delivery, not exactly-once.

    The fix is an idempotent worker: doing the job twice has the same result as once. Give each message an id, and record finished ids so a repeat is skipped.

    Idempotent jobs are safe to retry. This one habit makes queues, retries and crashes much less scary.

  8. Step 8: A poison message goes to a dead-letter queue

    One message may always fail, for example it points to a deleted user. If it is retried forever it blocks workers and wastes work.

    After a set number of tries (say 5), the queue moves it to a dead-letter queue (DLQ). The main line keeps moving, and people can look at the DLQ, fix the cause and re-send the messages.

    Put an alert on the DLQ. A DLQ nobody looks at is only a quiet place to lose work.

  9. Step 9: Many workers can reorder messages

    With several workers, message 1 ("deposit 100") and message 2 ("withdraw 100") may be handled by different workers, and the second can finish first. The order you sent is not the order of effect.

    If order matters, split the queue into partitions by a key such as the user id. All messages for one user go to the same partition and one worker reads each partition, so each user's messages stay in order while different users run in parallel.

    Strict order costs parallelism. Keep it only where the business needs it.

  10. Step 10: When the line never stops growing

    If producers are faster than consumers for a long time, the queue only grows. It uses more memory, and messages wait so long that their work is useless (an email for a sign-in code that expired).

    Backpressure pushes back: add workers, set a maximum size and reject or slow producers (429) when it is full, drop low-value messages, or expire old ones. Always alert on queue depth and oldest message age.

    A queue hides a slow consumer; it does not fix it. Capacity must still match the average load.

  11. Step 11: Message queues in one picture

    A queue lets the API answer in 52 ms instead of 850 ms, and lets workers do the slow part later. A pool of 4 workers does 5 jobs a second and the line absorbs spikes.

    Ack after the work, make jobs idempotent, send poison messages to a dead-letter queue, partition by key when order matters, and watch the depth.