A message queue sits between the part of a system that creates work and the part that does it. The producer drops a message and moves on, and a consumer processes it when it can.
Why use a queue
- Decoupling: the producer does not need the consumer to be up.
- Smoothing spikes: work waits in the queue instead of overloading a service.
- Background work: send email, resize images or call slow APIs outside the request.
- Scaling: add more consumers to drain the queue faster.
Delivery guarantees
- At-most-once: a message is delivered zero or one time. It may be lost, never duplicated.
- At-least-once: delivered one or more times. Never lost, but it may be duplicated.
- Exactly-once: delivered and processed once. It is very hard across a network and is usually built from at-least-once delivery plus idempotent processing.
Acknowledgements
A consumer takes a message, processes it, and then acknowledges it. If it crashes before acknowledging, the queue hands the message to another consumer. That is exactly how duplicates appear.
Idempotent consumers
Because duplicates happen, handling a message twice must be harmless. A simple technique is to record processed message ids.
PROCESSED = {}
def handle(message)
return :duplicate if PROCESSED[message[:id]]
PROCESSED[message[:id]] = true
# ... do the work once ...
:done
end
puts handle({ id: "m1" })
puts handle({ id: "m1" })In a real system the record of processed ids lives in a database, written in the same transaction as the work.
Failures and dead letters
Some messages will never succeed, for example because their payload is malformed. After a limited number of retries with backoff, move them to a dead-letter queue where a person can inspect them, instead of blocking the queue forever.
Ordering. Most queues guarantee order only within a partition or a group. If order matters for one entity, route all its messages to the same partition.
Takeaway
Assume messages can be delayed, duplicated and reordered, and design consumers to be idempotent with retries, backoff and a dead-letter path.
Comments