Chapter 3 of 4
Queues and retries
When our sensor's reading reaches the cloud, it shouldn't go straight into a database. If the database is slow or down, the reading is lost. Instead, it goes into a queue, and a separate service takes it from there.
At least once, not exactly once#
Most queues promise to deliver every message at least once. That means sometimes twice. Accept this instead of fighting it, and make your processing safe to repeat.
Make processing idempotent#
Idempotent means doing it twice has the same effect as doing it once. Give every reading a unique ID, and skip any ID you've already stored. Duplicates stop being a problem.
- Read the message from the queue.
- Check whether its ID was already processed.
- If not, store it and record the ID.
- Only then mark the message as complete.
Give failures somewhere to go#
Some messages will never process, because they're malformed or point to a device that no longer exists. After a few retries, move them to a dead-letter queue instead of retrying forever. Then look at that queue regularly.
Remember
- Put a queue between devices and storage.
- Assume every message can arrive twice, and handle it.
- Send repeat failures to a dead-letter queue and actually read it.