When the conference ticket API accepts a reservation, a worker prepares a receipt and sends it through an email provider. The reservation needs a reliable response. The email can finish later. Moving email work behind a queue allows the API to respond quickly, but the team now has to decide what “accepted” promises, how a failed attempt is retried, and when waiting jobs become too old to be useful.

You will design a durable handoff, choose between a work queue and a retained log, trace a duplicate delivery, and work out whether an overloaded worker pool can recover. This builds on durable identity from API and Data Model Design and the capacity and overload boundaries in Caching Strategies and Invalidation.

Define acceptance before choosing a broker#

A producer expresses work as a message. A broker accepts and stores that message under a configured durability and retention policy. A consumer receives the message, and a worker executes its operation. A broker publish acknowledgment, a worker delivery acknowledgment, and the result of a business operation are three separate signals.

The ticket API should commit the reservation and a row requesting receipt generation in one transaction. The request row is an outbox record. A relay publishes pending rows, and only marks them published after broker confirmation. If the producer loses the broker's response or crashes before marking the row, it may publish twice. Keep the same event ID on every publish attempt. A consumer must still handle duplicates.

This avoids a split write that could commit the ticket and lose the notification request. A receipt job can reference the ticket ID and data version so workers can load the right data. If processing needs a historical snapshot, preserve it or explicitly store the necessary payload. Validate schema versions at the consumer boundary, and keep sensitive content out of messages when a restricted data reference will do.

An API that accepts a document export can respond with 202 Accepted and a job status resource. Define whether acceptance requires the broker or the outbox to be durable, and persist the job record before replying. The useful status transitions may be accepted → running → succeeded, with visible failed or expired states. A ticket reservation and a receipt delivery are different user-visible facts, so they can have different status fields and deadlines.

Architecture canvasReservation acceptance and receipt processing have separate milestonesThe ticket API commits the reservation and outbox in one database transaction. A relay publishes the receipt job. The worker can process it independently after acceptance.
Reservation acceptance and receipt processing have separate milestonesThe ticket API commits the reservation and outbox in one database transaction. A relay publishes the receipt job. The worker can process it independently after acceptance.commit bothrelay publishesdeliverTicket APIReservation + outboxReceipt queueReceipt worker
Diagram key and text version
  • Entry
  • Data
  • Async
  • Process
  1. Ticket API → Reservation + outbox: commit both
  2. Reservation + outbox → Receipt queue: relay publishes
  3. Receipt queue → Receipt worker: deliver

Choose a work queue or a retained log#

A work queue typically makes a message available to a worker, hides it during the processing attempt, and removes it after acknowledgment. A visibility timeout or delivery lease bounds how long the attempt may hold the message. If the worker dies before completion, delivery can resume once the lease expires. A lease is a recovery mechanism. It does not prove that the first worker has stopped or that the broker can never deliver a second copy.

A retained log gives each record a position, or offset, within its partition. Consumer groups track a position independently, and an offset commit does not remove the record for other groups. Retention policies govern what history remains available. A search indexer can read the same ticket events as an analytics pipeline without sharing its progress or speed. A new indexer can replay history only for records still retained, so long-lived rebuilds may require a source snapshot and subsequent changes.

RequirementWork queue is often a fitPartitioned log is often a fit
Completion consumed once logicallyA competing worker pool handles receipt generationA group can process work, but replay and offsets remain explicit
Several independent readersGive each subscriber its own subscription or queueConsumer groups track progress independently
Historical rebuildKeep a separate authoritative historyReplay retained data from a saved offset, with a snapshot if necessary
OrderingDepends on queue configuration and groupAppend order within a partition

Ordering has a scope. Route events for one ticket to the same partition or message group if the operations require sequencing. Routing all tickets to one group can make a single ordered stream a bottleneck. Delivery order is also separate from effect order. If a worker concurrently handles versions 4 and 5, version 5 can finish first. Use sequential processing for dependent operations, or apply state with monotonic version checks when later snapshots supersede older ones. If committing a log offset for a concurrent batch, advance only beyond a contiguous range of completed offsets. A commit past unfinished work can skip that work after restart.

Design around what retries can prove#

Delivery goalWhat you may observeWhat the design needs
At-most-onceZero or one delivery under the stated scopeAccept possible loss, such as after acknowledging before processing
At-least-onceA retained job can return after ambiguous completionDurable publish, retry policy, and a duplicate-safe effect
Exactly-once effect in a named boundaryA repeated delivery leaves one committed business effectAtomic progress and state, or an end-to-end idempotency protocol within that boundary

Consider a worker receiving event-17. It increments a counter in a database and commits. Before it acknowledges the broker, it crashes. The next worker sees event-17 again. A separate “already processed” query followed by an unconditional write allows two workers to pass the check concurrently. Record the event ID using a unique constraint and update the business state in the same transaction. If the transaction rolls back, both changes disappear. If it commits and the acknowledgment is lost, the next attempt can safely acknowledge the already applied event.

Keep deduplication state for the duplicate and replay horizon, and choose the ID scope carefully. A relay should use the same event ID after an ambiguous publish response. Redriving a job should usually keep its business ID while recording a separate attempt ID for telemetry. If independent tenants or sources assign IDs, include the source identity in the key.

A database commit cannot make an unrelated email send atomic. A worker can crash after the provider sends an email but before recording the result, or record success too early and lose the send. Use the provider's idempotency key if it offers a suitable guarantee. Otherwise choose a policy for ambiguous sends, such as reconciliation against provider records, duplicate-tolerant messaging, or manual review. Kafka's transaction mechanism can atomically combine Kafka-produced records with consumed offsets under a supported configuration. That boundary does not include an unrelated email provider.

Architecture canvasA committed effect survives acknowledgment lossA worker commits the event ID and effect, then loses the broker acknowledgment. Redelivery checks the durable event ID and acknowledges the job without applying the effect again.
A committed effect survives acknowledgment lossA worker commits the event ID and effect, then loses the broker acknowledgment. Redelivery checks the durable event ID and acknowledges the job without applying the effect again.before acklease expiresID existsCommit ID + effectWorker crashesRedeliver eventAck existing result
Diagram key and text version
  • Data
  • Process
  • Async
  • Outcome
  1. Commit ID + effect → Worker crashes: before ack
  2. Worker crashes → Redeliver event: lease expires
  3. Redeliver event → Ack existing result: ID exists

Bound retries, lease time, and dead letters#

Classify transient errors separately from permanent failures. A timeout or temporary upstream outage may warrant retry. A malformed payload with a known unsupported schema needs remediation. Retrying that message continuously spends worker slots and may block later work sharing its ordering key. Apply a per-job deadline and attempt budget, schedule retries with capped backoff and jitter, and isolate retry traffic from enough capacity to process new jobs.

Set visibility so ordinary successful work usually finishes before redelivery. If jobs vary widely in length, renew the lease while useful progress continues. A worker whose lease expired can still be running. A downstream lock, fencing token, or transactional deduplication must enforce the effect if concurrent execution would be unsafe. Keep the total lease extension bounded by the job deadline. Longer visibility can delay useful recovery when a worker really is gone.

A dead-letter queue (DLQ) or a durable quarantine records work that exhausted the retry policy or needs inspection. Keep the original ID, reason, schema version, and diagnostic metadata. Alert on rate and age, restrict access to sensitive payloads, and allow controlled replay only after the underlying problem is understood. If a group requires strict sequence, skipping one item into a DLQ may allow later items to run out of order. Decide whether to stop that group, explicitly skip and record the gap, or rebuild its state from authority.

Calculate backlog and recovery by hand#

Let A be the admitted arrival rate and C the effective completion capacity, both in jobs per second. For a duration t in seconds with constant rates, the fluid approximation gives

Ending backlog = max(0, starting backlog + (A − C) × t)

Assume workers can sustain 100 completed receipts per second, including all downstream constraints. A burst admits 160 jobs per second for 20 seconds, starting from an empty queue. It produces (160-100)20=1200 waiting jobs. If arrivals settle at 80 per second, only 100-80=20 completions per second are available to drain the backlog, so recovery takes 1200/20=60 seconds. If new arrivals already use all 100 completions, it never drains at those rates. This calculation ignores retries, worker warm-up, and service-time variability. Real recovery may be slower if old jobs tend to be expensive or a dependency remains degraded.

A job near the end of a 1,200-job FIFO queue waits roughly 1200/100=12 seconds to reach service under constant capacity. This estimates one job's wait. The 60 seconds estimates when the whole queue becomes empty while fresh jobs continue arriving. Distinguish these metrics in alerts and user-facing estimates.

If the queue is limited to 500 waiting jobs, the first eight one-second batches build 480. In the ninth second, completing 100 old jobs creates 100 spaces, and there are already 20 unused waiting spaces. Admit 120 of the 160 offered jobs and shed 40. From the tenth to twentieth second, each cohort sheds 60. The system sheds 40+11(60)=700 jobs, completes 2,000, and keeps 500 waiting. This one-second model is what the lab implements. A service should reject such work before promising acceptance, or explicitly define why previously queued best-effort work may expire.

Send pressure upstream#

Backpressure tells producers to slow down based on downstream capacity. A worker with eight execution slots may stop taking deliveries until a slot opens. That protects worker memory. If the producer still accepts unlimited work, the broker backlog continues growing. Add a bound at the API or producer for queue age, reserved capacity, or outstanding tenant work. For internal producers, propagate a feedback signal and enforce demand limits. For external callers, expose a meaningful retry contract.

Load shedding actively refuses work or drops work whose contract allows it. Reject lower-priority arrivals once the queue cannot meet their deadline. Apply a separate policy to essential reservations: preserve the durable outbox for already accepted tickets, reserve receipt-processing capacity, and report delivery lag. Keep bulk exports from overwhelming ticket delivery by limiting per-tenant concurrency or moving the work to a separate pool. Priority can starve low-priority jobs, so reserve bandwidth for work you still promise to complete.

A worker pool with W active workers and a measured safe rate r per worker has an estimated ceiling Wr if work is evenly distributed. Its real safe rate is also limited by partitions or group serialization, connection pools, provider quotas, and expensive jobs. Scaling consumers can swamp a dependency and reduce goodput. Check oldest age, per-partition lag, active work, attempt rates, and downstream saturation before changing concurrency. Track completed work and rejected work separately so a cheap failure never looks like a healthy fast path.

SymptomFirst measurementLikely fix
Depth grows while workers are busySustained admitted and completed ratesSlow producers or add downstream-supported capacity
Oldest age grows while depth looks modestPer-partition or per-tenant ageIsolate a hot key or poison message
Successes fall as attempts riseRetry rate and provider error classesReduce retry pressure and fix the failing dependency
Duplicate effects despite one publishStable ID, receipt lease, and transaction boundaryDeduplicate where the effect is committed
Worker memory rises as provider stallsIn-flight count and deadlinesBound prefetch and concurrency

In a design interview, start with a user-visible commitment and show the durable acceptance, worker effect, and acknowledgment as separate steps. State the retry and ordering scope. Work a burst and a recovery estimate by hand. Finish with overload behavior, failure tests, and signals that tell you whether the budget is holding.

Run the Python lab#

Download the lab and run python3 08-queues-backpressure-workers.py with Python 3.10 or newer. The first section simulates admission, completion, and waiting in one-second ticks. The second applies stable event IDs and a counter update inside one SQLite transaction, then repeats a delivery to simulate a missing broker acknowledgment. It uses an in-memory database for deterministic execution. A production worker would store the same atomic state in a durable database.

Try it yourself

Choose a recovery rate

A queue contains 9,000 waiting jobs. New arrivals cannot be paused and add 150 jobs per second. What completion rate clears the backlog within 90 seconds?

Reveal solution

The system needs 100 completions per second above the continued arrivals, since 9000/90=100. The total is 250 per second. Confirm the dependency can support that rate. If it cannot, meet a longer recovery objective or negotiate a reduced admission rate.

Try it yourself

Choose an offset boundary

A worker group has applied offsets 21 and 23, but offset 22 is unfinished. Which offset can it store as the next position to resume, and what happens to 23 after a crash?

Reveal solution

Assuming everything through 21 is complete, commit 22 as the next offset. A restart can deliver 23 again after 22. Make its effect duplicate-safe. Committing 24 before 22 completes would skip unresolved work.

A worker committed a local effect and lost its acknowledgment. What should the next delivery do?

Why does pausing worker polling fail to bound the broker backlog by itself?

Memory chart#

Accept     define durability and expose pending status
Publish    retry with the same event identity
Execute    acknowledge after the committed effect
Order      name the key, completion rule, and replay horizon
Recover    backlog ÷ (completion rate − new demand)
Protect    bound attempts, concurrency, queue age, and admission

The next lesson applies the same asynchronous handoff to a file catalog. It connects object storage, search projections, and rate limits without making any one component responsible for all three jobs.

References#