Skip to content

Why put a queue between services

BasicsConcept

Your checkout calls the email service directly, so when email is slow or down, checkout is too. Put a queue between them and three things change: spikes get absorbed, failures get retried, and nobody waits for anyone else.

01 The direct call

An online shop saves the order, then calls the email service to send a receipt, then answers the customer. The customer’s request is open the whole time. If the email service takes two seconds, checkout takes two seconds longer. If it is down, checkout fails, even though the order itself was fine.

The fix is to stop calling and start leaving a message. The order service writes a small job, “send a receipt for order 42”, to a queue and returns. A separate worker (the consumer) reads jobs from the queue and sends the emails.

Direct call
def place_order(cart):
order = db.save_order(cart)
email.send_receipt(order) # waits for email
return order
Through a queue
def place_order(cart):
order = db.save_order(cart)
queue.send("email-jobs", {"order_id": order.id})
return order
Direct callSave + emailThe customer waits for the slowest service in the chain, and fails when any of them fails.
Through a queueSave + enqueueWriting a message is quick, and the queue is built to stay up. The email happens later.

02 Absorbing a spike

Traffic is never flat. A sale, a newsletter or a TV advert can bring many times the usual orders for a few minutes. With direct calls, the email service must cope with the peak. With a queue, it only has to keep up with the average: the queue holds the extra jobs until the worker gets to them.

Six orders arrive at once; one worker drains them
Step 1 of 10
Customers waiting 0
email-jobs queue
Empty
Worker
idle
Emails sent
Empty
  • just queued or sent
  • being sent
  • worker free

The shop is quiet. The queue is empty and the worker is waiting for a job.

0 queue depth

The customers’ experience did not depend on the worker at all. The cost is delay: the sixth receipt went out a little later than the first. For a receipt, that is fine.

03 Retrying a failure

A queue does not forget a job just because a worker took it. The worker must acknowledge the message when the work is done. Until then the queue only hides it, and if no acknowledgement arrives in time, it hands the message out again.

worker.py
while True:
for msg in queue.receive("email-jobs", max=10, wait=20):
try:
email.send_receipt(msg.body["order_id"])
queue.ack(msg) # only now is it gone
except EmailDown:
pass # no ack: it comes back after the timeout

The client here is a sketch. In Amazon SQS the acknowledgement is delete_message; in RabbitMQ it is basic_ack. The shape is the same: receive, do the work, then acknowledge.

The email provider fails once; the queue retries
Step 1 of 8
email-jobs queue
Empty
Worker
idle
Attempts
Empty
  • just queued
  • in flight, hidden
  • being sent
  • failed attempt
  • sent
  • worker free

One order, o7, is about to be placed. The queue and the attempt log are empty.

Acknowledge after the work, never before. Ack first and a crash halfway through loses the job silently. Ack after and a crash means the job runs again, so the same customer may get two receipts. Plan for that second case.

04 Decoupling who waits for whom

With direct calls, the order service has to know every service that cares about an order, call each one, and handle each one’s failures. With a queue, it publishes one fact, “order 42 was placed”, and stops there. Each interested service reads it on its own schedule.

To give several consumers their own copy of each message, you publish to a topic that feeds one queue per consumer (for example SNS in front of SQS queues, or one Kafka consumer group per service). Adding an analytics service then means adding a queue, not editing the order service.

The same change, with and without a queue
What happensDirect callsThrough a queue
Email service is down for 10 minutesCheckouts failJobs wait, then go out when it is back
Orders jump to 10× for an hourEmail service must handle the peakWorkers drain the backlog at their own rate
Email service gets slowEvery checkout gets slowerCheckout time does not change
Analytics wants every orderOrder service gains a new callAnalytics subscribes; order service unchanged

05 What a queue costs you

The answer comes laterThe producer cannot tell the user how the job went. Good for receipts and thumbnails; wrong for “was my card accepted?”, which the user needs before the page loads.
A message can arrive twiceMost queues deliver at least once: a worker that crashes before acknowledging gets the job again. Make handling safe to repeat, for example by recording which order ids already had a receipt.
Spikes, not overloadIf producers add jobs faster than workers finish them on average, the queue grows without end. Watch the queue depth and the age of the oldest message, and add workers when they climb.
maxReceiveCountPoison messagesA job that always fails (a bad order id, say) is retried for ever. After a few attempts, move it to a dead-letter queue for a person to look at. In SQS this is a redrive policy with maxReceiveCount.
Order is looseWith several workers and retries, jobs can finish out of order. SQS standard queues only try to keep order. If order matters, use a FIFO queue or a Kafka partition per key.

06 Check yourself

Question

The email service is down for five minutes. Receipts go through a queue. What happens to orders placed in those five minutes?

Question

Producers add 100 jobs a second, on average, all day. Your workers finish 80 a second. What does the queue do?

Question

A worker sends the receipt, then crashes before acknowledging the message. What happens next?

07 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?