Queues & streams
medium 30 minA message queue stores work between the program that asks for it and the program that does it.
See it run
Follow one message, crash a worker, share the work, copy an event, and set a bad message aside.
Operations
The life of a message
M1, M2 and M3 wait. M4 is sent, and M1 is handled.
Step 1 of 7
The producer sends
Visible
M1 · M2 · M3
Hidden
The producer creates M4 with a payload and metadata.
Step 1: The producer sends
message_id = queue.send(payload) # stored, then confirmedreceipt, body = queue.receive() # hidden, not removedhandle(body)queue.acknowledge(receipt) # now it is removed- Producer waits for
- Storing only
- Result
- Removed after the ack
Two confirmations: the queue to the producer, and the consumer to the queue.
In the real world
The same queues & streams doing real jobs. Pick one and step through it.
864,000 jobs a day, 0.5 seconds for each.
Step 1 of 4
Average
| Average | 10 a second |
|---|---|
| Peak, 3x | |
| Busy workers | |
| At 80% use |
864,000 / 86,400 = 10 a second.
Step 1: Average
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Acknowledging before the work
criticalA crash during the work loses the message.
Wrongqueue.acknowledge(receipt)handle(body)Righthandle(body)queue.acknowledge(receipt)Acknowledging by message id
majorA slow worker can remove a message that another worker now holds.
Wrongqueue.acknowledge(message.id)Rightqueue.acknowledge(receipt) # this delivery onlyCounting only reported failures
majorA crash reports nothing, so poison returns forever.
Wrongexcept Exception: message.retries += 1Right# on receivemessage.receives += 1A file inside the message
minorQueues have size limits, and large messages slow everyone.
Wrongqueue.send(video_bytes)Righturl = store.put(video_bytes)queue.send({"url": url})
Interview tips
How to explain it
- Store, receive, work, acknowledge, remove.
- Receive hides. Silence brings it back.
- Each message goes to one worker.
Memory trick: QUEUE
- Quality of delivery, Uncouple.
- Enable async work, Use buffering.
- Ensure order within a scope.
Best practices
- Idempotent consumers.
- A dead letter queue with an alert.
- Batches, and a link instead of a file.
Watch these
- Age of the oldest message.
- Receives for each message.
- Use of the system behind the workers.