3893 words
19 minutes
How One Service Gets Pushed Into a Distributed System: Nine Steps From an API Endpoint to Outbox + Inbox
阅读中文版

When people design a backend from scratch, the first instinct is to draw the end state: a message broker, microservices, events, maybe a saga. None of that is wrong. But those are answers, and you don’t have the questions yet. An architecture without the problems that justify it is one where you can’t say why each box exists, and when something breaks you don’t know where to look.

A better start is the smallest service that works. Then you let problems push you. Each step adds exactly one thing, and that thing is always forced by a specific problem in the step below. By step eight you end up with roughly the same picture as the end-state diagram. The difference is that you know what every box is for.

A staircase of nine levels, read from the top down: from a plain API endpoint at the top to outbox plus inbox at the bottom. Each step names what it adds, and an orange note beside it names the problem that forces the next step down.

One example runs through the whole post: a PDF summary service. A user uploads a PDF; the service splits it into chunks, calls an LLM once per chunk, and stitches the answers into a summary. One LLM call takes a few seconds; a whole document can take minutes. Almost all of that time is spent waiting on the LLM provider while the CPU sits idle, which is the shape of most AI applications today.


L0: a plain API endpoint#

@app.post("/summarize")
def summarize(pdf: UploadFile):
chunks = split(pdf)
parts = [llm.complete(c) for c in chunks] # blocking, seconds each
return {"summary": join(parts)}

This is the starting point, and there is nothing wrong with it. One user, ten users, it works. Don’t skip this step because “lots of people might use it someday.”

When it starts to hurt: the second user waits for the first.

Picture a restaurant with one waiter. He takes table one’s order, then stands at the kitchen door until the food is ready, carries it out, and only then walks over to table two. The kitchen isn’t busy and the waiter isn’t working. He’s just waiting.

One detail worth knowing. A plain def endpoint in FastAPI runs in a thread pool (anyio’s default is 40 threads), so in practice you have 40 waiters each standing at the kitchen door, not one.

L1: async / await#

Make the endpoint async def and switch to an async client (httpx.AsyncClient, the SDK’s async flavour). Now the waiter drops off the order and goes to the next table, and comes back when the food is ready.

Two timelines. Top, blocking: while user A waits about three seconds on the LLM, user B sits in line and only starts after A finishes. Bottom, async: the event loop starts B during A's wait, and both finish about three seconds after they arrive. A note at the bottom says that an async def endpoint calling a blocking client behaves like the top picture.

Async doesn’t make any single request faster; A still waits three seconds. What it changes is that waiting no longer occupies a slot. For a service that spends 90% of its time waiting on an LLM, that’s close to free throughput.

When it starts to hurt: it accepts everything.

Before, the restaurant could serve 40 tables at once. Now the waiter can take unlimited orders. A burst of 1,000 requests arrives, and in the same second your service fires 1,000 calls at the LLM provider. You get 429s back, and you’re holding 1,000 PDFs in memory. You’re not protecting the provider you depend on, and you’re not protecting yourself.

L2: a semaphore#

sem = asyncio.Semaphore(50)
async def call_llm(chunk):
async with sem: # no slot free? wait here
return await client.complete(chunk)

At most 50 calls are in flight. Everything else waits on sem.acquire().

L2: the API endpoint gets a waiting line and a semaphore with fifty slots. Only the API box is new; the client and the LLM provider are unchanged. Orange: one machine is the ceiling, and a crash loses the line.

Here’s the realization that matters for the rest of the post: a semaphore plus the coroutines waiting in front of it is already a queue. It has an entrance, a line, and a fixed number of consumers. It does the same job a message queue will do later, except this queue lives in one process’s memory. A lot of what the next steps do is move this queue out of memory, piece by piece.

When it starts to hurt: two things. One machine is now your ceiling. And when the process restarts (a deploy, an OOM kill, a recycled host), everything waiting in line and everything in flight disappears. The user sees a dropped connection.

L3: more instances behind a load balancer#

Put a load balancer in front, run N identical instances behind it, and add an autoscaler that adds or removes instances based on CPU or request count.

L3: a load balancer spreads requests over N identical API instances. The load balancer and the instances are new. Orange: a crash loses progress and nothing can be queried later.

Adding instances is this easy because each one is stateless. A request comes in, gets handled, gets answered, and leaves nothing behind. It doesn’t matter which instance takes it.

There’s a side effect people miss: every instance has its own semaphore. Three instances with 50 each means 150 globally. If your LLM quota is 100, you either set each semaphore to quota / instance_count (while the autoscaler keeps changing the instance count), or accept that your limit is approximate.

When it starts to hurt: an instance dies on chunk three, and the results of chunks one and two die with it. The user refreshes and everything starts over. The deeper problem is that this request never had an id. The user can’t come back and ask “is my summary ready?”, and nothing in the system remembers the request ever existed.

L4: state goes into a database#

CREATE TABLE requests (
id uuid PRIMARY KEY,
user_id text NOT NULL,
status text NOT NULL, -- queued / running / done / failed
step text, -- extract / summarize / ...
result jsonb,
updated_at timestamptz NOT NULL DEFAULT now()
);

Every request writes a row the moment it arrives, and updates status and step after each step finishes.

L4: a database table called requests holds the state, and the API instances read and write it. The database is new. Orange: the caller still holds the HTTP connection for minutes.

The key shift: the instances are still stateless, but the system is now stateful. State moved out of process memory and into the database. If an instance dies, its row survives and another instance can pick it up. And the user finally has an id to come back with.

Once state lives in one place, concurrency conflicts get a referee too. Two instances both want r3; who wins? Let the database decide:

  • A conditional update: UPDATE ... WHERE id=$1 AND status='queued'. Whoever gets one row back wins; whoever gets zero backs off.
  • When you need to read before you write, lock the row with SELECT ... FOR UPDATE.
  • For anything that must not happen twice (same user, same file, processed once), use a unique constraint.

Don’t do “check if it exists, insert if it doesn’t” in application code. Two instances will both see “doesn’t exist.”

One practical trap: a database only accepts so many connections (Postgres, for example, defaults to max_connections = 100). Ten instances, each with a 20-connection pool, is already 200. Once you have more than a handful of instances, put a pooling proxy in front.

When it starts to hurt: the user’s HTTP connection stays open for minutes. Load balancers commonly drop a connection after 60 seconds with no data, and a phone switching cell towers drops it too. Once the connection is gone, the user never sees the result even if the server finishes. So they resubmit, and the same document gets processed twice.

L5: job mode, return 202 and let a worker do it#

Split “accepting the request” and “doing the work” into two kinds of process:

  • API endpoint: receives the request, inserts a row with status='queued', and immediately returns 202 Accepted with a job_id. Tens of milliseconds.
  • Worker: a loop that claims a row from the table, does the work, writes back the result.

With a job_id in hand, the client either polls GET /jobs/{id} every few seconds, or registers a webhook URL ahead of time and gets called back when the job is done.

L5: the API answers 202 at once and workers take jobs from the table and call the LLM provider. The 202 answer and the workers are new. Orange: you now hand-write the lease, retries, dead state and polling.

It’s the ticket machine at a bank. You don’t stand at the counter while your paperwork gets done; you take a number and sit down, and they call you when it’s your turn. The paperwork takes exactly as long as before. What changed is that waiting no longer ties up a counter.

The worker’s claim query is the heart of this step:

UPDATE jobs
SET status = 'running',
locked_until = now() + interval '5 min',
attempts = attempts + 1
WHERE id = (
SELECT id FROM jobs
WHERE status = 'queued'
OR (status = 'running' AND locked_until < now()) -- previous worker died; lease expired
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1
)
RETURNING id;

SKIP LOCKED lets many workers grab work at once: each skips rows someone else has locked, so they neither block each other nor take the same row. locked_until is a lease: if a worker dies mid-job, the row becomes claimable again five minutes later.

The lease brings a new problem. If a job fails every time, say the input is bad, the LLM provider always rejects it, or the worker crashes on it, then each time the lease expires it gets claimed again, fails again, and loops forever, tying up workers. This is called a poison message. So you count: each claim adds one to attempts, and past N you mark the row dead, stop claiming it, and hand it to a person. Once the cause is fixed, set it back to queued to rerun. dead is for “this one job is broken”. If the LLM provider is down entirely, every job fails; the right move then is to back off and pause claiming until it recovers, not to mark every job dead.

This step also buys an architectural benefit: the API endpoint and the workers scale independently. The API endpoint follows request rate; workers follow how many rows are waiting. Before, both lived in one process and could only scale together.

原子能’s talk 《如何在架构层面解决90%的问题》 (a Chinese-language video on async architecture) ends with a minimal async architecture the author uses a lot, and it is basically this step. The client calls the API endpoint over HTTP; the API endpoint writes one row with SQL and returns. That part is synchronous. Then a database trigger sends a notification that wakes a set of workers, and the workers call an external API (in this post, the LLM provider). That part is asynchronous. The author’s trade-off: if the project has no message queue yet, don’t stand one up just for this; use the database you already have. I agree with that as a starting point.

L5, minimal version: the API saves a job row; a database trigger sends NOTIFY to wake the workers; the workers claim rows from the table and call the LLM provider. Orange: NOTIFY can be lost, so it only wakes the workers.

One thing to add: the trigger’s notification can only be a wake-up signal. Once awake, a worker still claims work from the table with the SKIP LOCKED query above. If a notification gets lost, a worker that also scans the table every so often still picks the row up. The note at the end explains why.

When it starts to hurt: look at what you just wrote. A lease, a retry counter, a dead status after N attempts, workers polling the database asking “anything new?” You are hand-building a message queue out of a table. A bit more code is not a reason to replace it. By the rule above, if the database can serve as the queue, don’t add RabbitMQ or SQS for it; every extra piece of stack is one more thing to deploy, monitor and debug. What actually forces the switch is one of these signals. First, queue traffic starts hurting the database itself: lots of workers polling nonstop, constant updates bloating the table, and normal queries slowing down. Second, the backlog or throughput grows past what one table can handle. Third, one message has to fan out to several services (L7), each getting its own copy, which a table does awkwardly. If none of these show up, stay at L5.

L6: a real message queue#

The table keeps holding state; the queue takes over the work to be done. After inserting the row, the API endpoint sends a message to the queue. Workers receive messages, process them, and ack them. SQS, RabbitMQ and the like all fit; this section sticks to the ideas they share.

L6: a message queue sits between the API and the workers. The queue is new; the database still holds state. Orange: duplicates, dual write, and one service doing every step.

Every piece you hand-wrote in L5 has a ready-made counterpart:

What you wrote in L5What the queue gives you
locked_until leasevisibility timeout: a received message is hidden for a while and reappears if not acked
attempts counterdelivery count: how many times this message has been received
status = 'dead'past the max delivery count it moves to a DLQ (dead-letter queue); once fixed, redrive it back
workers polling the tablelong polling or push: the worker waits for a message instead of spinning

The scaling signal changes too. Workers spend most of their time waiting on the LLM, so CPU stays low. Scaling on CPU gets you “10,000 messages backed up, CPU at 5%, autoscaler thinks everything is fine.” The right signal is queue depth: add workers when the backlog grows, remove them when it empties.

When it starts to hurt: three problems show up together.

  1. Duplicates. Most message queues guarantee at-least-once delivery by default. If a worker finishes but dies before acking the message, the message comes back and the same chunk gets summarized twice.
  2. Dual write. The API endpoint commits the database transaction, then sends the queue message. Crash between the two, and you have a queued row with no message that will ever pick it up. That row sits at queued forever.
  3. One service does every step. Extraction, summarization, notification and indexing all live in one worker. Their latencies, failure rates and scaling needs differ wildly, and gradually different teams start owning them.

L7: a service per step, each with its own queue#

Split extraction, summarization, notification and indexing into separate services. Each gets its own queue, its own database, and its own scaling signal.

The messages between services come in two kinds, and they travel on different channels:

  • Commands: “do this.” Exactly one receiver. They go over a point-to-point queue, for example extract.cmd.
  • Facts (events): “this happened.” Whoever cares subscribes. They go to a pub/sub topic that fans out to each subscriber’s own queue, for example doc.extracted.

L7: an intake service sends a command to the extract service&#x27;s queue; extract publishes a fact to a topic, which fans out to the summarize, notify and search index services. Orange: duplicates and dual writes at every hop.

This is where you meet a classic choice:

  • Orchestration: a central coordinator sends explicit commands step by step: extract, summarize, notify. The flow lives in one place, so it’s easy to read and debug, but the coordinator knows about everyone.
  • Choreography: no center. Each service just publishes what it finished, and other services decide for themselves whether to react. Coupling is low and adding a new consumer touches nobody else, but the flow isn’t written down anywhere; you reconstruct it by tracing events.

Neither one wins outright. With few steps, a fixed order, and a need for an overall timeout or compensation, orchestration is easier. With many downstream consumers and new teams regularly asking to “also listen to that event,” choreography fits better. Plenty of systems mix the two.

When it starts to hurt: L6’s duplicates and dual writes didn’t go away; they got multiplied by the number of hops. Every arrow is a hop, every hop can deliver twice, and every sender faces “commit the database first or send the message first?” And a new problem appears: silent stalls. A message for some step is lost, or a service just never processes it. Nothing throws. The request sits in some middle state forever.

L8: outbox + inbox#

This step uses two matching patterns, one for dual writes and one for duplicates.

Outbox (fixes dual write): stop doing “commit, then send.” Instead, in the same database transaction, write the business data and an outbox row that says “I need to send this message.” A separate relay process reads the outbox table, publishes to the queue or topic, and marks rows as sent. The transaction guarantees both rows exist or neither does; if the relay crashes, it restarts and sends again. The cost is that a message may go out twice. The outbox turns “maybe lost” into “maybe duplicated.”

Inbox (fixes duplicates): the consumer records each processed message_id in an inbox table with a unique constraint. When a duplicate arrives, it’s found and skipped. The inbox turns “maybe duplicated” into “effectively once.”

Put together, at every hop the sender guarantees the message isn’t lost and the receiver guarantees it only takes effect once.

L8: inside one service, a message passes gate 1 (is its id in the inbox?), then the LLM call, then gate 2, one transaction that writes the inbox, the result and the outbox. A relay publishes the outbox to the topic. A sweeper scans the requests table. Left over: silent stalls.

In code, the consumer has two gates:

async def handle(msg):
# Gate 1: before the expensive LLM call, check whether we've seen this
if await db.fetchval("SELECT 1 FROM inbox WHERE message_id = $1", msg.id):
return await ack(msg)
summary = await llm.summarize(msg.chunk) # expensive; under a race it can run twice
# Gate 2: inbox, result and outbox in one transaction
try:
async with db.transaction():
await db.execute("INSERT INTO inbox (message_id) VALUES ($1)", msg.id)
await db.execute(
"UPDATE requests SET result = $2, status = 'done', updated_at = now() WHERE id = $1",
msg.request_id, summary)
await db.execute("INSERT INTO outbox (topic, payload) VALUES ('doc.summarized', $1)", event)
except UniqueViolationError:
pass # another worker committed first; whole transaction rolled back
await ack(msg)

Why two gates? Gate 1 saves money: most duplicates stop there and never pay for a second LLM call. But it can’t stop the race where two workers receive the same message at once and both see “not processed yet.” Gate 2 is the actual guarantee: the unique constraint makes the later transaction fail and roll back as a whole, so the result isn’t written twice and no extra outbox row appears. Gate 1 is there to save money; gate 2 is what keeps the result correct.

What’s still left: silent stalls. Outbox and inbox guarantee messages aren’t lost or doubled. But if a service has a bug and never processes anything, or an external dependency stays down, a request still stops halfway. Nothing reports an error, because nothing is waiting on it.

The fix is surprisingly plain: put a timeout on each step, and run a sweeper on a schedule that scans the state table:

SELECT id, step FROM requests
WHERE status NOT IN ('done', 'failed')
AND updated_at < now() - interval '30 min';

For each row it finds, either alert a human or re-send that step’s command (re-sending is safe, since the consumer has an inbox). This is also where the L4 state table pays off one more time: it isn’t only for users checking progress, it’s the ledger you reconcile the whole system against.

A multi-step workflow platform I work on has the outbox and the dedup, but not the sweeper yet. It’s the kind of thing you never notice is missing until something stalls and someone has to dig through logs by hand.


Scaling once you have state#

Each step scales a different thing on a different signal. Seeing them side by side helps:

StepWhat scalesSignal
L3instances of the whole serviceCPU, request count
L5API endpoint and workers separatelyAPI endpoint: request rate; workers: rows waiting in the table
L6workersqueue depth
L7each service on its ownits own queue depth, and the age of its oldest message

The stateless parts (API endpoint, workers) are easy: add instances. The hard part is the stateful part, the database. Database scaling usually goes in this order, moving on only when the previous step runs out:

  1. Vertical: a bigger machine. The simplest option, and it usually lasts longer than you’d expect.
  2. Read replicas: send reads like progress checks and list pages to replicas. Replicas lag, so a status you just wrote may not show up there yet.
  3. Caching: put hot data in something like Redis.
  4. Sharding: split data across databases by a key like user_id. The most expensive option; cross-shard queries and transactions get painful. Avoid it as long as you can.

Don’t skip steps#

Looking back over the nine steps, each one solves a specific problem, and each solution brings its own cost. L4 adds a database to run. L6 adds a queue and a DLQ to watch. L7 adds a set of services and the event contracts between them. L8 adds two tables, a relay and a sweeper.

If your service has a few dozen users and requests return in seconds, building the L7 architecture means paying the full cost of problems you don’t have yet. And if you’re already seeing connection timeouts, resubmissions and documents processed twice while still sitting at L3, you’re paying for the missing step every day.

So rather than memorizing what the end state looks like, two things are more useful: knowing which step you’re on, and knowing what the signal for the next one looks like.

  • Users wait behind each other’s requests: time for async.
  • The LLM provider starts returning 429s: time for a semaphore.
  • One machine can’t keep up: time for more instances.
  • A restart loses work and users can’t check progress: state goes into a database.
  • Requests run longer than a minute: switch to job mode.
  • The table-as-queue starts slowing the database, or one message has to fan out to several services: use a real queue. More code alone doesn’t count.
  • Steps start needing different scaling and different owners: split services by step.
  • Logs show duplicate processing and rows that exist in the table but never reached the queue: add outbox and inbox.
  • A request is stuck halfway and nothing alerted: add a sweeper.

Plus: delivery semantics (next post)#

“At-least-once”, “at-most-once” and “exactly-once” come up throughout this post. The next post covers them properly. The short version:

  • The only difference is when you ack. Ack, then process: a crash mid-processing loses the message, which is at-most-once. Process, then ack: a crash before the ack brings the message back, which is at-least-once.
  • True exactly-once delivery between two machines is not possible. What you can get is effectively-once: at-least-once delivery plus deduplication on the consumer, which is the inbox in L8.
  • Two claims in 原子能’s video need correcting. Payment webhooks are retried, so they are at-least-once, not at-most-once. RabbitMQ acks on both ends still give at-least-once; the consumer still has to deduplicate.
  • Postgres LISTEN/NOTIFY is at-most-once: a notification sent while nobody is listening is gone for good. That is why in L5 it can only be a wake-up signal.