Sub topic 1
Why Use a Message Queue
A message queue lets one part of a system hand work or events to another part without waiting for the work to finish. This chapter explains the problem queues solve, the trade-offs they bring, and how to decide whether you need one. Later chapters cover the mechanics: brokers, acknowledgements, delivery guarantees, and so on.
Prerequisites
This chapter assumes you have:
- Basic programming skills in any language. The examples use Python.
- Familiarity with client-server communication and HTTP request/response.
- A basic understanding of processes, threads, and how networked services fail.
The problem with synchronous calls
In a synchronous call, the caller sends a request and blocks until it gets a response. An HTTP call from a web service to a payment service is the usual example. This model is simple, but it ties the caller to the callee in three ways:
- Time coupling. The caller waits for the full duration of the work. If the callee takes 8 seconds to resize an image, the user's request takes at least 8 seconds.
- Availability coupling. If the callee is down or slow, the caller fails or hangs. The caller's uptime can be no better than the product of the uptimes of everything it calls synchronously.
- Load coupling. If traffic spikes, the spike lands on the callee at the same moment. The callee has to handle the peak rate or start rejecting requests.
A message queue breaks these couplings. The caller (the producer) puts a message describing the work on a queue and returns right away. A separate process (the consumer) takes messages off the queue and does the work at its own pace.
A first look at the shape
The smallest version of this idea lives inside one process. The producer calls put and moves on. A consumer thread calls get and handles items one at a time.
import queue
import threading
q = queue.Queue()
def consumer():
while True:
item = q.get()
if item is None:
q.task_done()
break
print("processing", item)
q.task_done()
t = threading.Thread(target=consumer)
t.start()
for i in range(3):
q.put(f"job-{i}")
q.put(None)
q.join()
t.join()The None value is a sentinel: a special message that tells the consumer to stop. The q.join() call blocks until every item has been marked done with task_done().
This in-process queue is useful for learning, but it has limits. The messages live in memory and vanish if the process crashes. It cannot connect two separate services. A message broker, a separate server that stores and routes messages, removes both limits. Chapter 3 covers brokers in detail.
What a queue gives you
Decoupling in time
Producer and consumer do not need to be running at the same time. If the consumer is being deployed or has crashed, messages accumulate in the queue and are processed when it returns. The producer is unaffected.
Load leveling
A queue absorbs bursts. Suppose a site receives 1,000 orders in one minute during a sale but the fulfillment service can process 100 per minute. With synchronous calls, most of those requests would fail or time out. With a queue, the 1,000 messages wait, and the service drains them over about ten minutes. You size the consumer for the average load, not the peak.
Independent scaling
You can add more consumers to drain a queue faster without changing the producer. This is the competing consumers pattern, covered later in the tutorial.
Failure isolation
A failing downstream service no longer fails the user's request. The producer's job is only to get the message into the queue. A slow email provider, for example, does not stop a user from signing up.
Fan-out
One event can be delivered to several independent consumers. A "user registered" event can trigger a welcome email, an analytics update, and a CRM sync, and the signup code does not need to know any of them exist. This is publish/subscribe, covered in a later chapter.
What a queue costs
A queue is not free. Before adopting one, weigh these costs.
| Cost | What it means in practice |
|---|---|
| Eventual consistency | The work is not done when the producer returns. A user may see stale data until the consumer catches up. |
| Another system to run | The broker needs deployment, upgrades, capacity planning, monitoring, and backups. |
| Duplicate delivery | Most brokers can deliver a message more than once, so consumers must tolerate repeats. |
| Harder debugging | A request's path spans several processes and a time gap. You need tracing IDs and logs that connect them. |
| No direct result | The producer cannot simply read a return value. You need a callback, polling, or a status endpoint. |
| Ordering limits | Strict global ordering is expensive or unavailable once you have multiple consumers. |
The duplicate-delivery and ordering costs have their own chapters because they shape consumer design the most.
When to use a queue
A queue is a good fit when most of these are true:
- The caller does not need the result to continue. Sending email, generating a report, and resizing an image are typical.
- The work is slow, or its duration varies a lot.
- Traffic is bursty, and you want to size for average load.
- The downstream service is unreliable or rate-limited.
- Several systems need to react to the same event.
- You want to deploy or restart producer and consumer independently.
A synchronous call is usually the better choice when:
- The caller needs the answer right now, such as checking whether a username is taken.
- The operation is fast and the callee is reliable.
- The system is small enough that the operational cost of a broker outweighs the benefit.
- You need a simple request/response flow that is easy to trace.
A common hybrid is to accept the request synchronously, validate it, put a message on a queue, and return 202 Accepted with a status URL. The client then polls that URL or receives a notification when the work is done.
A worked example
Consider a photo-sharing service. A user uploads a photo, and the service must create three thumbnails, run content moderation, and update a search index.
Synchronous design. The upload handler calls the thumbnail service, the moderation service, and the search indexer in turn. The user waits for all three. If moderation takes 5 seconds, every upload takes at least that long. If the search indexer is down, the upload fails even though the photo was saved.
Queue-based design. The handler stores the photo, publishes one message {"photo_id": 42}, and returns in milliseconds. Three consumers, one per task, each read the event and do their own work. If the indexer is down for an hour, only indexing is delayed. Thumbnails and moderation continue.
The queue-based design adds real complexity. The handler must make sure that the photo is saved and the message is published together, or one can exist without the other. This is the dual-write problem, and the transactional outbox pattern in a later chapter addresses it. Each consumer must also handle the same message twice without harm, which is the subject of the idempotency chapter.
Common mistakes
- Using a queue to hide a slow service. If the consumer is permanently slower than the producer, the queue grows without bound. A queue smooths bursts. It does not fix a sustained capacity gap.
- Expecting an immediate result. Code that publishes and then immediately reads the outcome will see nothing. Design the user experience around "accepted, processing" states.
- Putting large payloads in messages. Brokers work best with small messages. Store a large file in object storage and send a reference to it.
- Treating the queue as a database. Queues hold work in transit. They are not designed for querying or long-term storage.
- Ignoring failure paths. Plan for retries, duplicates, and poison messages (messages that always fail) from the start.
Where this fits in the tutorial
The rest of the tutorial builds on this motivation. You will meet producers and consumers, then brokers and queues, then acknowledgements, which make delivery reliable. From there, delivery guarantees, idempotent consumers, and dead-letter queues explain how to handle the costs listed above.
Exercise
A checkout service calls a tax-calculation service synchronously during every purchase. Calls take about 200 ms, and the user needs the tax amount to see the order total. A teammate proposes moving this call to a message queue. Is that a good idea? Explain using the criteria from this chapter.
Show answer
Probably not. The caller needs the result to continue, since the order total depends on the tax amount, and the operation is fast. A queue would add eventual consistency, another system to run, and the need for a callback or polling to get the result, with little benefit. A better fix for availability concerns is a timeout, retry, or cached fallback on the synchronous call. A queue would fit better for follow-up work the user does not wait on, such as sending the receipt email.
Exercise
A sale causes 6,000 orders in 10 minutes. Your fulfillment consumer processes 200 orders per minute. Assuming orders arrive evenly during the sale, roughly how many messages are waiting in the queue at the end of the 10 minutes, and how long after that does the queue take to drain if no new orders arrive?
Show answer
Arrivals are 6,000 over 10 minutes, or 600 per minute. The consumer handles 200 per minute, so the backlog grows by 400 per minute. After 10 minutes, about 4,000 messages are waiting. At 200 per minute, draining them takes about 20 more minutes. Without a queue, the extra 400 requests per minute would have to be rejected or would time out.