advanced29 min studyLesson 26 in Engineering

Reliable messaging and backpressure

Design replay-safe consumers, bounded queues, and explicit overload behavior for asynchronous AI workflows.

On this page

What you’ll understand

  • Trace failure windows around effects and acknowledgements.
  • Design an idempotent consumer with a stable operation key.
  • Calculate backlog growth and define bounded overload behavior.

An embedding worker writes a vector and then crashes before acknowledging its message. The broker redelivers the task. If the worker appends another vector or charges a customer again, reliable delivery has produced an unreliable application. Messaging design must specify what can repeat, which effects must appear once, how progress is recorded, and what happens when producers outrun consumers. A broker's delivery label does not answer all four questions.

Draw the effect–acknowledgement failure window

At-most-once handling can discard work if progress is acknowledged before the effect is durable. At-least-once delivery retains the possibility of retries, so a crash after the effect but before acknowledgement can execute the effect again. Neither ordering alone produces exactly one external effect. An acknowledgement can also be lost after successful processing; a retry is then evidence of uncertainty, not proof that the original attempt failed. Treat timeouts as unknown outcomes and make retry safety explicit.

An idempotent operation gives repeated execution the same externally relevant result as one execution. Assign a stable key to the logical operation, not a fresh key for every attempt. In a database-backed consumer, store that key under a uniqueness constraint and perform the business mutation in the same transaction. A check followed later by an unprotected insert is racy: two workers can both observe absence. External services need their own idempotency contract or a carefully designed reconciliation process.

Fk(Fk(s))=Fk(s)F_k(F_k(s))=F_k(s)
Fk applies logical operation k to state s. This algebraic idempotency condition concerns the relevant durable outcome, not whether repeated attempts consume CPU or emit duplicate debug logs.↔ Scroll wide equations horizontally.

Connect transactions without overclaiming guarantees

A transactional outbox stores the business change and a pending event in one local transaction. A relay later publishes the event; because the relay can retry, downstream consumers still need duplicate-safe handling. An inbox or deduplication table records consumed operation keys alongside local mutations. Retention matters: expiring a key before the possible replay horizon reopens the duplication window. Keys must also distinguish genuinely new operations, or deduplication will incorrectly suppress valid work.

Kafka's idempotent producers and transactions address specific log and processing boundaries. They do not automatically make an arbitrary HTTP payment or email part of the same atomic transaction. Define the boundary in the application's contract. For multi-step workflows, durable state machines and compensating actions can expose partial progress rather than pretending a cross-system rollback is always possible. A compensation is a new business operation, which can fail and require retries of its own; it is not time travel.

Make overload finite and observable

Backpressure slows upstream work when downstream capacity is insufficient. A queue absorbs a temporary mismatch; it does not create capacity. Bound queued bytes, item count, and age, since one large request may cost more than thousands of small ones. Choose an overload policy: reject new work, delay producers, spill to a durable tier with a known limit, or shed a lower-priority class. Make that policy visible so clients know whether and when to retry.

Retries can amplify an outage. Apply capped exponential backoff with jitter, a retry budget, and an end-to-end deadline. Distinguish transient errors from poison messages that repeatedly fail validation. Quarantine those messages with enough context to investigate, while preserving privacy and a controlled replay path. Track oldest-message age, attempts per successful logical task, dead-letter growth, and downstream saturation. The fluid queue equation is useful for planning, but burstiness, skew, and variable task duration require load testing.

B(t)=max⁡{0,B0+(λ−μ)t},tfull=Bmax⁡−B0λ−μ  (λ>μ)B(t)=\max\{0,B_0+(\lambda-\mu)t\},\qquad t_{\mathrm{full}}=\frac{B_{\max}-B_0}{\lambda-\mu}\ \ (\lambda>\mu)
B is items, λ and μ are constant items/s, and t is seconds. The fill-time expression assumes the queue begins below its item limit; it omits byte limits, stochastic arrivals, and changing service cost.↔ Scroll wide equations horizontally.

Size the response to a slow embedding service

Tasks arrive at 900/s. A degraded worker pool completes 600/s. The queue holds 120,000 tasks and currently contains 30,000. Every task has a stable document-version key.

  1. Compute backlog growth: 900 − 600 = 300 tasks/s. There are 90,000 remaining queue slots.

  2. The ideal time until full is 90,000/300 = 300 seconds, or five minutes. A larger queue merely postpones overload.

  3. Throttle accepted arrivals to at most the measured completion capacity, or add verified downstream capacity. Keep queue-age deadlines even before the item limit is reached.

  4. For replay safety, atomically record the document-version key with its durable output reference. If the vector store is outside that transaction, use its idempotent upsert semantics or reconciliation; do not claim the database key alone protects the remote effect.

The result

The operator has roughly five minutes before the item bound is reached under constant rates. The capacity fix and duplicate-effect fix are separate requirements.

Explore the model

Interactive lab

Interactive lab · queue

Find the overload boundary

Set arrival rate λ above and below service rate μ. The animated backlog is the fluid model max(0, 4 + (λ − μ)t). The separately labelled M/M/1 residence time assumes Poisson arrivals, exponential service, one server, and λ < μ; it is not measured production latency.

Find the overload boundaryFluid backlog starts at 4 and follows max(0, 4 + (λ − μ)t). The separate M/M/1 residence-time formula assumes Poisson arrivals, exponential service and λ < μ. Current readings: Fluid backlog: 4; Net rate · λ − μ: −1 /s; M/M/1 mean residence: 1 s. All parameters are adjustable with the labeled controls below.02.557.51001.534.56Elapsed time · sFluid backlogλ < μ
Fluid backlogCurrent time
Fluid backlog
4
Net rate · λ − μ
−1 /s
M/M/1 mean residence
1 s
t = 0 s

Fluid backlog starts at 4 and follows max(0, 4 + (λ − μ)t). The separate M/M/1 residence-time formula assumes Poisson arrivals, exponential service and λ < μ. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forA queue grows under sustained excess arrivals; retries must fit within the same finite service capacity.

Check your understanding

A consumer performs an external charge, then crashes before committing its offset. Which design best handles a redelivery?

Try it yourself

A queue contains 48,000 tasks. Arrivals are 200/s and service is 500/s. Estimate drain time. Explain why deleting deduplication keys after one hour is unsafe when broker retention permits a three-day replay.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Use spare throughput for draining. Compare the lifetime of the duplicate-prevention evidence with the longest supported retry or replay interval.

Compare with the solution

Spare throughput is 300 tasks/s, so the ideal drain time is 48,000/300 = 160 seconds. After a one-hour key expiry, a replay from two days earlier can look new and repeat the effect. Retain keys across the supported replay horizon or design the destination operation itself to remain duplicate-safe beyond that horizon.

Take it with you

  • At-least-once delivery requires retry-safe effects and stable logical keys.
  • A transaction's exactly-once claim has a specific boundary.
  • Bound queues and retries; sustained overload needs admission control or more capacity.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.