LOAD-BEARINGfree
Architecture labTier 13 · unit 16 of 31

Async invoicing pipeline

Every order must be registered with a government e-invoicing portal that returns a reference number before the invoice is legally valid. The portal is slow, rate-limited, and least reliable at exactly the hours you need it most. Checkout cannot wait for it, and no invoice may ever be filed twice.

Envelope10M invoices in a 6-hour sale · portal times out on 30% of calls · zero duplicate filings

What the design must do

  • Checkout returns immediately; registration happens after
  • A timed-out call never produces a second filing
  • Transient failures retry with backoff; permanent ones do not
  • An hour of portal downtime loses nothing
  • Invoices that exhaust their retries land where a human will see them

The worked envelope

Assumed. 2M invoices a day steady, 10M during a six-hour sale. The portal answers in ~400 ms when healthy, and at peak 30% of calls hit the 30 s timeout instead. Invoice payload ~2 KB.

Worked envelope
Steady rate2M ÷ 86,400 s ≈ 23/s
Sale rate10M ÷ 21,600 s ≈ 463/s — 20× steady
Mean call0.7 × 0.4 s + 0.3 × 30 s ≈ 9.3 s
Calls in flight463/s × 9.3 s ≈ 4,300 concurrent (Little's law)
Same, 3 s timeout463/s × 1.2 s ≈ 550 — one config line, 8× less
Retry amplification3 attempts at 30% failure = 1.42 calls per invoice
Dead letters0.5% permanent × 10M = 50,000 ≈ 420 person-hours

What the numbers decide. Two rows carry this entire design. The first is 4,300 concurrent calls: the timeout value, which looks like a config detail, is what sets how much of your fleet is parked inside a stranger's slow request — and dropping it from 30 s to 3 s removes seven eighths of that cost without touching a line of application code. Timeouts are a capacity decision (Lesson 6.06).

The second is 1.42 calls per invoice. Your retry policy adds 42% more load to the portal precisely when it is already failing, which is Lesson 9.04's retry storm aimed at somebody else. That is why the breaker and the backoff are not optional garnish here — they are what stops your recovery attempt from being the reason recovery does not happen.

And note the last row is measured in person-hours. Fifty thousand dead letters is not a queue depth, it is ten person-weeks of someone reading rejection codes, which is a design input as real as any latency budget.

The decisions, and what each one costs

Persist the invoice and its outbox row in one transaction, then return 202

Because
The order is already committed and the customer is already gone; the only thing that must be atomic is "this invoice exists and something will file it", and a row plus an outbox row in the same commit gives that with no distributed transaction
The cost
A relay process now has to move outbox rows to the queue, and its lag is a metric someone owns
Rejected
Publishing to the queue inside the request, which loses the filing whenever the broker blips after the database commits — the exact gap Lesson 6.05 exists to close

A caller-generated idempotency key on every portal call, stored before the attempt

Because
A timeout tells you nothing about whether the portal acted (Lesson 6.06), so the retry is the dangerous path: without a key the second attempt files the same invoice twice and the duplicate is a legal document, not a log line
The cost
You depend on the portal honouring the key — and on storing it <em>before</em> the call, so a worker that dies mid-flight still knows what it was doing
Rejected
Checking "does this invoice already have a reference number?" before retrying, which is the same race one round later and fails when the portal is the thing that is down

A 3-second timeout with exponential backoff, jitter, and a circuit breaker per portal endpoint

Because
The mean call is 9.3 s only because the timeout allows it; a tight timeout converts a hung call into a fast, cheap, retryable failure, and the breaker stops 463 workers a second from queueing against something that is already down
The cost
A slow-but-succeeding call gets cancelled and retried, so the timeout must sit above the portal’s healthy p99 or you manufacture the failures you are defending against
Rejected
Retrying immediately on failure, which synchronises every worker into the same thundering millisecond and is why jitter exists

Sort failures into transient and permanent before deciding to retry

Because
A 503 and a malformed tax identifier are the same exception object and opposite situations — one clears on its own, the other will fail identically 10,000 times and burn the budget that transient failures needed
The cost
You are now maintaining a classification table against somebody else’s error codes, and it goes stale silently when they add one
Rejected
A single retry policy for all errors, which retries the unretryable forever and dead-letters the recoverable

Dead-letter after N attempts, with the original payload and the full failure history

Because
Half a percent of ten million is fifty thousand invoices that need a human decision, and a queue with nowhere to put them either blocks the partition or drops them silently
The cost
The dead letter queue is now a workload with an owner, an SLA and a burn-down, not a dumping ground — an unwatched DLQ is a data loss bug with extra steps
Rejected
Retrying forever, which keeps the poison message at the head of the partition and stops every healthy invoice behind it

Components in the reference design

Client
Browser or mobile app
Load Balancer
L7 routing, TLS termination, health checks
App Service
Stateless business logic
SQL DB
Relational, ACID, joins
Queue
Work distribution, one consumer per message
Worker
Async consumer, background jobs
Third-Party API
A dependency you cannot scale, fix or page — someone else's uptime
Dead Letter Queue
Where a message lands after N failed attempts, so the line can move

What not to draw

  • WS Gateway — Holding a client connection open until the portal answers converts their bad afternoon into your outage — and the arithmetic below says that is 4,300 sockets whose entire content is "still waiting". Registration status belongs on a polled endpoint or an email, not a held connection.

The reference design

The unreliable dependency is the requirement, not an obstacle to it. You cannot make the portal faster or more available, and no amount of design will change its 30% timeout rate. What you can decide is whether their bad afternoon becomes your outage, your duplicate filings, or merely your backlog. This lab is the third answer.

Why the queue is load-bearing here. It is not a performance optimisation. It is the thing that decouples an event that must not be lost (an order was placed) from an action that cannot be relied upon (a portal call). Once the intent is durably recorded, every subsequent failure is a retry rather than an incident, and a portal outage becomes queue depth — visible, bounded and survivable — instead of failed checkouts.

The timeout is the capacity dial. This is the thing most designs never say out loud. Every in-flight call to a slow dependency holds a worker, a connection and a slot; Little's law turns their latency directly into your fleet size. A 30-second timeout against a portal whose healthy p99 is under a second is not caution, it is 4,300 workers volunteering to wait. Set it just above their healthy p99, and let the retry handle the rest.

Idempotency has to be end-to-end. Lesson 6.07's point, with a legal consequence attached. Your queue is at-least-once, so the worker will run twice; the portal is a stranger, so it cannot see your transaction. The only thing that makes redelivery safe is a key that travels with the request and that they deduplicate on. Generate it when the invoice is created — deterministically, from the invoice id, never from a timestamp or a UUID minted at call time — so that the retry and the original are provably the same operation.

Reconciliation is the step everyone forgets. Some calls will end in a state no code can resolve: you timed out, the key was accepted, and you never learned the reference number. If the portal offers a status-by-key lookup, a sweeper that polls for these is worth more than any amount of retry tuning. If it does not, you need a daily reconciliation against their filing report, and you should say so in the design review rather than discovering it in an audit.

What changes at 10×. Nothing in the topology, and everything in the negotiation. At 4,600/s the portal's own rate limit becomes the binding constraint, and the worker pool has to be throttled to their quota rather than to your capacity — the queue drains at their speed, and a sale simply produces a longer backlog. At that point the design question stops being technical and becomes "what does the business do about an invoice registered six hours after the sale", which is a product decision the architecture should surface early rather than absorb quietly.