AlgoViz

Queues & streams

medium 30 min

A message queue stores work between the program that asks for it and the program that does it.

When it comes up

The moments this idea belongs in a design interview, and the moments it does not.

Signals

When to bring it up

You hearSayBecause
Email, thumbnails, reportsStore a job and answerThe user does not need the result in the response
Traffic comes in burstsQueue and size for an acceptable drain timeA line is cheaper than capacity for the peak
Several teams react to one eventA stream or fan-outThe producer should not know its readers
Rebuild an index from historyA log with retentionA work queue has already removed the messages
The balance must be right after the clickDo it synchronouslyA queue adds delay, and the user is waiting

In the interview

  • Say which guarantee and which scope of order
  • Make the handler idempotent in the same breath
  • Add a dead letter queue and the alert
  • Give the backlog and the drain time

Avoid

  • "We put Kafka in between" without a reason
  • Promising exactly-once delivery
  • Adding workers beyond the partitions
  • Forgetting what happens to the failed message

A payment worker sometimes crashes after charging and before acknowledging. What do you do?

BreaksAcknowledge first
How
Remove the message before the charge.
Limit
A crash during the charge loses the payment.
Choose when
Data that you may lose, such as a sample of metrics.
WorksCheck a processed list
How
Look up the id, charge, then store the id.
Limit
Two workers can both pass the check, and a crash after the charge forgets it.
Choose when
Duplicates are rare and harmless.
StrongIdempotency key at the effect
How
Send the message id as the idempotency key of the charge, and record the result in one transaction. Then acknowledge.
Limit
The payment provider must support keys, and they must be kept longer than messages can return.
Choose when
Money, stock, or anything that must not happen twice.