Sub topic 2
Producers and consumers
This chapter covers the two roles at the ends of every message queue: the producer that sends messages and the consumer that receives them. It assumes you can write basic Python, know how HTTP request/response works, and understand that threads and networked services can fail. It builds on the previous chapter's case for asynchronous messaging. The next chapter covers the broker that sits between the two roles.
The two roles
A producer is code that creates a message and hands it to a queue. A consumer is code that takes messages from a queue and acts on them. A message is a self-contained piece of data, such as "resize image 42" or "order 981 was paid".
The defining property is that the producer does not wait for the consumer. With a synchronous call, the caller blocks until the callee answers, so the caller's latency and availability depend on the callee. With a queue, the producer's job ends once the message is accepted. The consumer can be slow, busy, or briefly offline without the producer noticing.
| Aspect | Synchronous call | Producer/consumer via queue |
|---|---|---|
| Caller waits for the work | Yes | No, only for the hand-off |
| Caller knows the result | Immediately | Not unless you design a reply path |
| Callee outage | Caller fails or retries | Messages wait in the queue |
| Load spikes | Callee is overwhelmed | Queue absorbs the burst |
| Coupling | Caller knows the callee's address and API | Both sides know only the queue and message format |
The "Caller knows the result" row is the main cost. Once the producer stops waiting, it no longer gets a return value. If the producer needs an outcome, you must add a status record, a callback, or a reply message.
The shape of the pattern in code
An in-process queue shows the pattern without a network. Python's queue.Queue is thread-safe, so one thread can produce while another consumes.
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()Four details matter here, and each has a counterpart in real brokers:
q.putreturns immediately. The main thread is the producer and never waits forprintto run. It only waits atq.join(), which is a deliberate shutdown step.q.getblocks when the queue is empty. The consumer sleeps until work arrives instead of polling in a busy loop.Noneis a sentinel. It is a special message meaning "no more work". Real queues usually have no such thing, because a consumer runs indefinitely and stops only when its process is told to stop.task_donereports completion.q.join()returns only after everygethas been matched by atask_done. This is a small version of acknowledgement: the queue learns that an item was finished, not merely handed out. The chapter on acknowledgements builds on this idea.
The in-process queue has limits. If the process crashes, every queued item is lost, and only threads in the same process can use it. A broker removes both limits, and it is why you reach for one.
The producer's responsibilities
A producer is more than a call to put. It must decide four things.
- What the message means. A message can be a command ("resize image 42"), which asks for a specific action, or an event ("image 42 uploaded"), which states a fact and leaves the reaction to others. Commands usually have one intended consumer. Events may have many. Naming messages accordingly (
image.resizeversusimage.uploaded) keeps the intent clear. - What the message contains. Include enough data for the consumer to work without calling back. Do not include so much that the message becomes stale or huge. For large files, send a reference such as an object-store key instead of the file bytes.
- How the consumer identifies it. Give every message a unique ID. You will need it later for deduplication and tracing.
- What to do when the hand-off fails. If the broker is unreachable,
putmay raise an error or block. The producer must retry, buffer, or fail the user's request.
A small envelope function covers the first three points:
import json
import uuid
from datetime import datetime, timezone
def make_message(kind, payload):
return json.dumps({
"id": str(uuid.uuid4()),
"type": kind,
"created_at": datetime.now(timezone.utc).isoformat(),
"payload": payload,
}).encode("utf-8")
def parse_message(body):
msg = json.loads(body)
for field in ("id", "type", "payload"):
if field not in msg:
raise ValueError(f"missing field: {field}")
return msg
body = make_message("image.resize", {"image_id": 42, "width": 800})
print(parse_message(body)["type"])Running this prints image.resize. The envelope serializes to bytes because brokers carry opaque byte strings. The broker does not understand your JSON. The format is a contract between producer and consumer alone.
The consumer's responsibilities
A consumer has its own set of duties.
- Validate before acting. Messages come from outside your process. A consumer should reject malformed messages, as
parse_messagedoes, rather than crash or corrupt data. - Do the work, then report the outcome. The consumer decides when a message counts as finished. That decision is the subject of the next several chapters.
- Expect repeats. In practice a message can arrive more than once, for example after a consumer crash. Consumer logic that is safe to run twice saves you from many production incidents.
- Stay within its capacity. A consumer that takes more messages than it can handle holds them hostage while they wait.
There are two ways a consumer can receive messages:
- Pull (polling). The consumer asks the broker for the next message, as
q.get()does. The consumer controls the pace. - Push. The broker delivers messages to a registered callback as they arrive. The delivery rate must then be limited by a setting such as a prefetch count, covered in a later chapter.
Both models appear in real brokers, sometimes in the same one. RabbitMQ's basic_consume is push, and basic_get is pull. The call you write differs, but the producer/consumer relationship is the same.
How the roles interact over time
The producer and consumer share no call stack. They meet only through the queue, so the timeline below is the whole interaction.
Notice that put job-2 happens while the consumer is busy. This is the decoupling in action. The producer's rate and the consumer's rate are independent, and the queue's length is the difference between them over time.
Rates and the queue's length
If the producer averages 100 messages per second and the consumer averages 60, the queue grows by 40 per second. It never catches up. A queue hides this mismatch for a while and then makes it worse by storing a large backlog. Messages in the backlog become old, memory or disk fills, and latency for each new message keeps rising.
Three situations are worth distinguishing:
- A burst. The producer spikes briefly, and the consumer drains the queue afterward. This is the case queues handle well.
- A sustained mismatch. The queue length climbs without limit. You need more consumers, faster consumers, or a slower producer. Later chapters cover competing consumers and backpressure.
- A stalled consumer. The consumer is down or stuck, so the queue grows even though rates are normal. This is a failure that monitoring should catch.
Common mistakes
- Assuming the producer sees failures. If a consumer's processing fails, the producer has already moved on. Errors surface in the consumer's logs, a retry mechanism, or a dead-letter queue, not in the producer's request.
- Putting a reply in the queue by accident. Developers sometimes build request/response on top of a queue and then wait for the answer synchronously. That keeps all the coupling and adds the broker's latency. Use a queue when the producer does not need to wait.
- Sharing mutable state through the message. A message should be a snapshot. If the consumer re-reads a database row that changed since publishing, it may act on newer data than the message describes. Decide deliberately which version you want.
- Sending huge payloads. Large messages slow the broker and compete with small ones. Send a reference instead.
- Letting message formats drift. A producer that renames a field breaks consumers that are running an older version. Add fields rather than renaming them, and keep consumers tolerant of unknown fields.
Exercise
A web handler publishes an "email.send" message and immediately returns "Email sent!" to the user. Name the problem with that response and give a more accurate alternative.
Show answer
Publishing only means the broker accepted the message. The consumer may not have processed it yet, and processing could still fail. A more accurate response is "Your email is queued" (or "We're sending your email"). If the user needs to know the final outcome, add a status record or a notification that the consumer updates after it finishes.
Exercise
In the in-process queue example, what would happen if the producer never put the None sentinel on the queue, and why?
Show answer
The consumer thread would block forever in q.get() after the last job, so t.join() would never return and the program would hang. (q.join() would still return, because every item was marked done.) The sentinel is what tells the consumer to exit its loop.
Exercise
A producer averages 50 messages per second and its consumer averages 80. A second producer is added, raising the total to 100 per second. What happens to the queue, and what are two ways to respond?
Show answer
The queue grows by about 20 messages per second, because arrivals exceed the processing rate. It will not drain until the rates change. Responses include adding consumers (or making the consumer faster) so processing exceeds 100 per second, or slowing or limiting the producers.