Skip to content
Engineering Bible
System Design

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.
  1. Redirect request
  2. App serverredirects at once
  3. Queueholds the click event
  4. Workerat its own pace
  5. Analytics database
The user never waits for the click to be counted.

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 readingMessage is deletedEvent stays until retention ends
ReadersEach message goes to one workerMany apps each read every event
Read againNoYes, as often as needed
Best forBackground jobsEvent 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.
System Design in seven pages6 / 7