System Design on queues and events
A queue lets slow work happen later
- The request handler puts a message on a queue and answers the user right away.
- Worker processes take messages off the queue and do the work in the background.
- Use it for email, image resizing and reports. For the shortener: counting clicks.
- Redirect request
- App serverredirects at once
- Queueholds the click event
- Workerat its own pace
- Analytics database
A queue absorbs bursts and outages
- If traffic spikes, the queue grows and the workers catch up afterward.
- If workers crash, messages wait. The part users see keeps working.
- Watch the age of the oldest message. A growing backlog means too few workers.
Messages can arrive twice
- Most queues deliver at least once: a message is resent until a worker confirms it.
- So the same message can be processed twice. Workers must be idempotent.
- Idempotent means twice has the same effect as once. Record the message IDs handled.
Order is not free
- Amazon SQS standard queues can deliver out of order. Its FIFO queues keep order.
- Kafka keeps order within a partition. Events with the same key share a partition.
- So key by the thing that needs order, such as the account ID.
A log keeps events for many readers
- A queue hands each message to one worker and deletes it when done.
- A log such as Kafka keeps events for a set time, read or not.
- Many services can read the same events: one counts clicks, another spots abuse.
| Queue (such as SQS) | Log (such as Kafka) | |
|---|---|---|
| After reading | Message is deleted | Event stays until retention ends |
| Readers | Each message goes to one worker | Many apps each read every event |
| Read again | No | Yes, as often as needed |
| Best for | Background jobs | Event streams with many consumers |
Messages that keep failing need a side exit
- A message that always fails would be retried forever and waste workers.
- After a set number of tries, move it to a dead-letter queue (DLQ).
- Alert on the DLQ, fix the bug, then send the messages back.
Write the event with the data, not after it
- Saving to the database and then publishing an event is two writes. One can fail.
- Outbox pattern: insert the event into an outbox table in the same transaction.
- A separate relay reads the table and publishes. It may send twice, so dedupe.