Buildfest Learn System DesignRead and experiment freely · Chapter activities stay in this tab
Practice librarySystem DesignQueues events and asynchronous work

LESSON 07 • SYSTEM DESIGN

Queues events and asynchronous workGive work time to finish.
Keep the backlog under control.

Queues events and asynchronous work. Learn the concepts, explore a model and defend your design.

DEFINITION

Asynchronous work allows acceptance and completion to happen at different times. A producer submits a message, a broker stores or delivers it, and a consumer performs the work. A queue can absorb a bounded burst but cannot create unlimited processing capacity. An event records a fact; a command asks another component to perform an action.

Reply now; finish eligible work later
  1. STEP 1Request handlerAccept durable work
  2. STEP 2QueueRetain pending messages
  3. STEP 3WorkerPerform background task

Move work after the reply only when that delay is acceptable to the user contract.

CONCEPT 1

Some work can happen after the reply

Do not make the student wait for everything

After an order is accepted, the app might send an email and update a statistics dashboard. These tasks may not need to finish before the student receives an order number. A queue holds work so a background worker can process it later. This separates accepting the order from completing each side task, but the product must be honest about what accepted means.

Producer, broker and consumer

The producer creates a job or message. The broker stores and delivers it under its contract. The consumer receives and processes it. A job might say send receipt for order 52. Acknowledgment is the consumer telling the broker that a delivery can be treated as handled. Publisher confirmation concerns the producer-to-broker boundary, which is different from proving the consumer finished its business effect.

A queue buys time, not infinite capacity

A sudden burst can be absorbed while workers catch up, if backlog and delay stay within acceptable limits. If work arrives faster than it can be processed indefinitely, the queue grows without bound until some limit is reached. Limit admission, expire irrelevant work or increase safe processing capacity. Show users whether an action is pending or actually completed.

CONCEPT 2

Calculate whether workers can catch up

Begin with a stable processing rate

Assume new jobs arrive at 120 jobs per second. Each of four workers handles 30 jobs per second for this workload. Four times 30 equals 120, so processing just matches arrival. If an old backlog already exists, these workers do not have spare capacity to remove it. The queue may remain large even though it stops growing.

Add spare capacity deliberately

Five ideal workers process 150 jobs per second. Subtract the 120 arriving each second to get 30 jobs per second of spare work. A backlog of 1,800 jobs then takes 1,800 / 30 = 60 seconds to drain in the model. Six workers give 180 per second, leaving 60 spare and an ideal drain time of 30 seconds.

Watch the right symptom

Real jobs have different costs and may fail or retry. An email provider may limit sends even if you add workers. Measure oldest-message age, new arrivals, completion rate and failure rate. Queue length alone can be misleading: ten very slow jobs can hurt more than a thousand trivial ones. Scaling workers beyond a dependency's safe capacity can make recovery slower.

Backlog grows when arrivals exceed completion
  1. CONCEPTArrivals120 jobs / second
  2. CONCEPTCompletion90 jobs / second
  3. CONCEPTGrowth30 jobs / second

After 300 seconds, this model adds 9,000 jobs. A queue does not create worker capacity.

CONCEPT 3

Why a message can be delivered twice

The crash between two actions

A worker sends an email and then plans to acknowledge the message. It crashes between those steps. The broker may deliver again because it never received the acknowledgment. If the worker instead acknowledged first and crashed before sending, the email might never be sent. These two failure windows explain why acknowledgment timing matters.

Make repeated work safe

A stable event or operation ID can help a consumer remember which effect it has already performed. This is called deduplication. It must be coordinated with the effect at the boundary you care about. A local record does not automatically prevent an external provider from performing an effect twice after an uncertain response. Use provider contracts and recovery checks where appropriate.

Ordering and failed messages

If jobs for one order must be processed in order, define that ordering scope. A global order can limit parallelism unnecessarily; per-order ordering may be enough. A repeatedly failing message may go to a dead-letter queue for investigation. Someone must own the review, correction and safe replay. Moving a message out of sight is not the same as resolving it.

Why a worker can see the same message again
  1. STEP 1WorkerStores successful result
  2. STEP 2AcknowledgementLost before broker sees it
  3. STEP 3BrokerMay redeliver the message

Make the business effect safe to repeat; a broker acknowledgement is a separate step.

CONCEPT 4

Events and multi-step workflows

Facts versus requests

An event describes something that happened, such as OrderCreated. A command asks for an action, such as SendReceipt. Naming the distinction makes responsibilities clearer. Event-driven communication can decouple timing, but introduces delayed observation and recovery. A reader must know whether a dashboard is showing final state or a lagging representation.

The transactional outbox

Saving an order and separately publishing its event can fail halfway. An outbox writes the order and an event record in the same local database transaction. A separate relay later publishes the event. The relay can publish twice if it crashes after publication but before recording completion, so consumers still need safe handling. The pattern closes one local coordination gap; it does not make every downstream effect happen exactly once.

CQRS, event sourcing and sagas

CQRS separates the way data is changed from the way it is read when that helps a workload. Event sourcing keeps domain events as the authoritative history from which state is built. Neither is required merely because messages exist. A saga coordinates a business workflow through steps and compensating actions, such as releasing reserved stock after payment fails. Compensation is a new action, not a magical erasure of every past effect.

Outbox links a database change to later publication
  1. STEP 1DB transactionBusiness row + outbox row
  2. STEP 2PublisherReads committed outbox
  3. STEP 3ConsumerDeduplicates repeated events

The outbox avoids a simple dual-write gap; it does not remove duplicate-delivery handling.

Key learning points

  • Define whether a response means accepted, durably queued or actually completed.
  • Backlog drains only when processing exceeds new arrivals.
  • Acknowledgment timing creates different loss or redelivery windows.
  • Deduplicate at the business-effect boundary and investigate poison messages.
  • Use explicit workflow states when several independently failing effects must be coordinated.

Compare the important ideas

Queues events and asynchronous work: concepts and trade-offs
MechanismSolvesDoes not automatically solve
QueueSeparate producer and consumer timingInfinite capacity or bounded completion delay
Consumer acknowledgmentBroker learns delivery was handledExactly-once external business effect
Publisher confirmationEvidence about publication boundaryConsumer processing completion
Transactional outboxBusiness change plus local event intentDuplicate relay publication
SagaCoordinated steps and compensationsA universal rollback across all services
Dead-letter queueSeparate repeated failures for reviewDiagnosis, correction or safe replay

WORKED EXAMPLE

Drain an old backlog

New arrivals are 120 jobs/s. Four consumers at 30 jobs/s each only match that rate. Five provide 150 jobs/s, leaving 30 jobs/s spare; 1,800 old jobs take 60 seconds to drain in an ideal constant-rate model. Six leave 60 jobs/s spare and take 30 seconds. A downstream quota or retry workload can make the real result worse, so observe oldest-message age and processing outcomes.

Further reading

Original teaching explanations by Buildfest Learn. Check these primary references for the underlying concepts and implementation details.