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.
07SYSTEM 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
STEP 1Request handlerAccept durable work
STEP 2QueueRetain pending messages
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
CONCEPTArrivals120 jobs / second
CONCEPTCompletion90 jobs / second
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
STEP 1WorkerStores successful result
STEP 2AcknowledgementLost before broker sees it
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
STEP 1DB transactionBusiness row + outbox row
STEP 2PublisherReads committed outbox
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
Mechanism
Solves
Does not automatically solve
Queue
Separate producer and consumer timing
Infinite capacity or bounded completion delay
Consumer acknowledgment
Broker learns delivery was handled
Exactly-once external business effect
Publisher confirmation
Evidence about publication boundary
Consumer processing completion
Transactional outbox
Business change plus local event intent
Duplicate relay publication
Saga
Coordinated steps and compensations
A universal rollback across all services
Dead-letter queue
Separate repeated failures for review
Diagnosis, 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.
Find a worker count that drains the queue while new jobs keep arriving.
1120 arrivals/s
290 completions/s
330/s backlog growth
The backlog grows; it cannot drain under this load.
Subtract ongoing arrivals from completion capacity before dividing backlog by spare capacity. Do not divide by the full worker rate while new jobs are still arriving.
Chapter review: two questions
Attempt both questions before opening the model answers.
Question 1
Jobs arrive at 80/s. Each worker handles an assumed 25/s. How many workers are needed to drain a 1,800-job backlog within 60 seconds while arrivals continue?
Reveal model answer
Draining requires 30 jobs/s spare, so processing must reach at least 110/s. ceil(110/25) gives five workers, with 125/s capacity and an ideal drain time 1,800/(125-80) = 40 seconds. Four would take 90 seconds and miss the goal. State constant-rate and no-retry assumptions.
Question 2
A worker sends a notification, crashes and never acknowledges. Explain the next likely broker action and design safe handling.
Reveal model answer
The broker may redeliver because completion was not acknowledged. Preserve a stable event/operation identity and coordinate deduplication with the intended effect. For uncertain external sends, use the provider's contract or reconciliation; a separate local flag alone is not a universal exactly-once guarantee.
Answers stay in this tab. Download before leaving. This practice is not graded or saved to your account.