Orchestration infrastructure — study guide
The concept's fragments, read in order.
For your capstone Run a coding agent you don't have to trust
The controller's runs are long, unattended and full of steps with side effects, so it needs the machinery that makes stopping halfway safe. Each step's result goes to a durable store outside the sandbox, which lets a run be stopped, inspected and resumed, or abandoned with a record of exactly what it did. Stopping and undoing an agent leans on that record.
Run r-212 has finished three steps, each model output recorded, when you stop it with step four, writing src/dates.py, in flight. On resume the controller reads the recorded outputs instead of asking the model again, which could take a different branch, and reruns only step four. Writing the recorded content to the same path twice leaves the file as writing it once.
From a script to a job that survives failure
An agent run started from your own terminal has an easy life. You are watching it, so if it crashes, hangs or does something odd, you see it, stop it and start it again. Move the same run into production, where a request or a schedule starts it, it runs for minutes with nobody watching, and it has to finish even when the machine under it restarts, and each of those quiet assumptions breaks. Orchestration infrastructure is the machinery that keeps that kind of work going: the queues that hold it, the workers that pick it up, and the rules for what happens when a step fails.
Agent workloads lean on that machinery harder than most background jobs. Their steps are slow, since one model call can take seconds and a run chains many of them. They fail partway, after some steps have done real work and before others have started. They call tools with side effects, such as sending a message, writing a record or making a payment, which must not happen twice by accident. And a model call is not like an ordinary function: send the identical request again after a timeout and you may get a different answer, so running a step a second time is not the same as running it once.
Despite the name, this is not Kubernetes-style orchestration. That other meaning, a cluster scheduler that decides which machine runs which container and replaces the ones that die, is a separate concept. Queues, retries and idempotency need no cluster scheduler, and you can run an agent pipeline, its queue and its workers on one machine. What gets orchestrated here is the work, the sequence of jobs and steps, not the machines it runs on.
The mechanisms come in a natural order: a queue between the work and the workers, why a queue that never loses work must sometimes deliver it twice, retrying with backoff, idempotency as the property that makes retries safe, timeouts and what they do not tell you, checkpoints that let a run resume, dead-letter queues for jobs that keep failing, and concurrency limits that keep you inside other services' rate limits.
A queue between the work and the workers
A queue sits between asking for work and doing it. A producer, which may be a web request, a schedule or an agent handing off a subtask, puts a job on the queue: a small message saying what to do, carrying its inputs or a pointer to them. Workers, separate processes that do nothing else, take jobs off the queue and run them. The producer does not wait for the work to finish; it moves on as soon as the job is safely stored, and the work happens when a worker is free.
That split suits agent runs well. A run that takes minutes does not fit inside a web request whose caller gives up long before it finishes, and a burst of fifty requests should wait in line rather than start fifty runs at once. The queue absorbs the burst, and you decide how many workers drain it. A worker is usually a container, built by the same CI/CD pipeline as the rest of your code and started with podman like any other, and because it keeps nothing it needs in its own writable layer, any worker can be stopped and replaced; the job, not the worker, is the thing that matters. Handoffs between agents often travel the same road, with a supervisor's handoff becoming a job that a specialist worker picks up. A queue is also an entry point, though: whatever can put a job on it can make your workers act, so treat job contents as untrusted input and limit who may enqueue.
The detail everything else depends on is what taking a job means. In queues built for reliable work, a worker that receives a job does not remove it. The queue hides the job for a set period, often called a visibility timeout or a lease, like a library book on loan: while you have it, nobody else can borrow it, and if it is not returned by the due date it goes back on the shelf for the next borrower. When the worker finishes, it acknowledges the job, and only then does the queue delete it. If the worker crashes, hangs or loses its connection, no acknowledgment arrives, the lease runs out, and the job becomes visible again for another worker to take. A crash costs time, not the job.
Why duplicates are inevitable
A queue that is not sure a job was handled has two choices. It can deliver each job once and never again, so a job whose worker crashed is simply lost; that is at-most-once delivery. Or it can keep delivering until an acknowledgment comes back, so no job is lost but some are delivered more than once; that is at-least-once delivery, like a courier who keeps coming back until someone signs for the parcel, so a signature slip lost on the way back means the same parcel arrives a second time. Queues meant for work that matters choose at-least-once.
The duplicates are not a bug waiting to be fixed. Picture a worker that takes a job, calls a tool that sends an email, and then sends its acknowledgment, which is lost on the way. From the queue's side, that looks exactly like a worker that crashed before doing anything: either way, no acknowledgment arrived before the lease ran out. The queue cannot tell done but unacknowledged from never done, and the only way not to lose the second kind is to deliver both again. So the email goes out twice. Acknowledging before doing the work does not escape the problem; it trades the risk of a duplicate for the risk of a lost job.
This is why exactly-once delivery is not achievable in general across a network: a lost acknowledgment always leaves the sender unsure, and it must either retry, risking a duplicate, or not, risking a loss. What real systems offer instead is at-least-once delivery combined with processing that is safe to repeat, so a duplicate delivery has no further effect. The result is often called effectively-once, or exactly-once processing. When a product advertises exactly-once, check where the guarantee ends. It holds within a defined boundary, typically that system's own records and transactions, and it does not reach an outside tool your worker calls. Making that last step safe to repeat is your job.
Retrying without making it worse
Plenty of failures clear up on their own. A dropped connection, a server restarting, a model service that is briefly overloaded: try again a little later and the call goes through. These transient failures are worth retrying. Others will fail the same way every time, such as a malformed request or a missing permission, and retrying them only wastes time and quota. HTTP status codes give a first sort. A 429 Too Many Requests means slow down and try later, and many 5xx server errors are temporary. Most 4xx client errors, such as 400 Bad Request or 403 Forbidden, mean the request itself is wrong, and sending it again unchanged will not help.
How you retry matters as much as whether. Retry instantly in a tight loop and a struggling service gets hit hardest at the moment it is weakest, by every client at once. The standard fix is capped exponential backoff: wait before each retry, double the wait each time, and stop growing at a cap like calling back a busy line after a longer wait each time, instead of redialing at once along with everyone else who got the busy signal. With an illustrative starting wait of 1 second and a cap of 16 seconds, the waits before retries one to six are 1, 2, 4, 8, 16 and 16 seconds. Then add jitter, randomness in the wait, because clients that failed at the same moment and back off on the same schedule still come back in synchronized waves. With full jitter, each wait is a random time between zero and that ceiling, so a ceiling of 4 seconds means a wait anywhere from 0 to 4 seconds, 2 on average, and the crowd spreads out. If the service sends a Retry-After header, a number of seconds or a date, it is telling you when to come back; wait at least that long.
Bound the retries too, with a maximum number of attempts or a deadline. Retries multiply load, and they multiply again when several layers each retry the same failing call: if three layers in a chain each make up to three attempts, one request at the top can become 3 x 3 x 3 = 27 attempts at the bottom. Retry at one layer, not all of them. And a retry is only safe if repeating the step is harmless. Retrying a read costs nothing; retrying a step that sends, charges or writes, after a failure that may have come after the work was done, risks doing it twice. Making that repeat harmless is what idempotency is for.
Making a step safe to run twice
A step is idempotent if running it twice leaves things exactly as running it once. HTTP's methods already sort themselves this way: PUT and DELETE are idempotent, POST is not. Idempotency is the property that makes at-least-once delivery and retries safe. If a duplicate delivery or a retry has no further effect, you can redeliver and retry as freely as failures demand, and the duplicates that at-least-once delivery allows stop mattering.
Some steps are idempotent by nature, or cheaply made so. Setting a balance to 100 is safe to repeat; adding 10 to it is not. Writing a result to a file named after the job overwrites itself harmlessly; appending to a shared log does not. An upsert keyed on the job's id, which inserts the row or updates it if it already exists, lands in the same state however often it runs. Where the effect itself cannot be repeated, such as an email sent or a payment made, use an idempotency key like quoting your order number at a counter: asking again about order 57 gets you order 57, not a second meal. The caller generates a unique key once for each logical operation and sends the same key with every retry of it. The receiving side records the key with the outcome of the first attempt, and when a request arrives with a key it has already completed, it returns the saved result instead of acting again.
Two details decide whether keys work. The key must belong to the operation, not the attempt: generate it before the first try and store it with the job, because a key made fresh on each retry deduplicates nothing. And the same key does not always mean the same request. An IETF Internet-Draft, still a work in progress, that would standardize an Idempotency-Key header recommends that a server answer 409 Conflict when a retry arrives while the first attempt is still in progress, and 422 Unprocessable Content when the key comes back with a different request body.
Model calls need their own version of the rule. Send the same request to a model twice and you may get two different answers; even with sampling randomness turned down to its minimum, hosted model services do not promise identical output. A retried step that asks again can take a different branch from the attempt whose side effects already happened. So record a model call's output the first time it succeeds, keyed to its step, and reuse that recorded output on any retry or resume instead of asking again.
Deadlines, and what a timeout does not tell you
Every call a worker makes needs a deadline. A model service that stops responding, a tool waiting on a lock, a network connection that silently stalls: without a timeout, any of these holds a worker forever, and enough of them tie up every worker you have while the queue grows behind them. So each call gets a timeout, each step gets one, and the whole job gets one.
The trap is in what a timeout tells you, which is less than it seems. A timeout means you stopped waiting; it does not mean the work failed. The tool may have received the request and done the work, with only the reply slow or lost. A timeout leaves the outcome unknown, exactly like a lost acknowledgment, so retrying after one is safe only if the step is idempotent. Model calls add a twist: the retry is a fresh call, which may produce a different answer from the one that never arrived. Record what you receive, and design for the chance that the slow first attempt landed somewhere after all.
Timeouts also have to nest. A job's own time limit must fit inside the queue's lease on it. If the lease runs out while the job is still working, the queue hands the job to a second worker, and the expired lease does not stop the first one, so you have two copies running before anything has failed. For steps that are legitimately long, the worker can renew its lease while it is still making progress, sending a heartbeat well before the lease ends. That lets the lease stay short enough for a real crash to be noticed quickly. Put a ceiling on the renewals too, so a stuck worker cannot keep a job hidden forever.
Saving progress so a run can resume
A run of many steps that fails at step four should not start again from step one. Starting over wastes the time and the calls already spent, and worse, it repeats steps one to three along with their side effects. The fix is to persist progress. After each step finishes, write its result to durable storage outside the worker, a database or an object store, not the container's own writable layer, which disappears when the container is replaced. When the run resumes, on the same worker or a different one, it reads those saved results back and carries on from the first step that has none, like a save point in a video game: after a crash you start again from the last save, not from the beginning. Only the step that was in flight when the crash came runs again, which is one more reason every step must be safe to run twice.
Durable execution turns this habit into a runtime. A durable-execution engine records each step's result in an ordered history as the run proceeds. After a crash, it runs the coordinating code again from the start against that history: whenever the code reaches a step that already has a recorded result, the engine hands back the recorded result instead of running the step. The code arrives where it left off with its state rebuilt, and continues with the first step that has no record.
That replay works only if the coordinating code is deterministic: given the same inputs and the same recorded results, it must make the same decisions in the same order, or the replay drifts away from the history it is reading. So anything that can come out differently, a model call, a tool call, a database write, reading the clock, generating a random number, belongs inside a recorded step, never in the coordinating code directly. For agent runs the fit is natural: each model call and each tool call becomes a step, and its output is recorded once and reused on every replay. The shared state that several agents read and write, the plan, the handoffs, the intermediate results, belongs in the same durable store, where any worker can pick the run up.
Where jobs go when they keep failing
Some jobs will never succeed. Malformed input, a tool that rejects the request every time, a bug that crashes the worker on one particular job: retried forever, such a job burns worker time and rate-limit budget on every attempt and can hold up the work queued behind it. A job like that is called a poison message.
The defense is a maximum attempt count. The queue counts how many times each job has been delivered without being acknowledged, and once that count passes the limit, it moves the job to a separate queue, the dead-letter queue, instead of delivering it again. One widely used managed queue service, for example, documents a default of 10 receives once a dead-letter queue is configured; others use different defaults, and some do not dead-letter at all unless you set it up. The right limit depends on the workload: high enough that transient failures get their chance to clear, low enough that a hopeless job stops consuming resources. The job is not deleted. It is parked with its contents intact.
A dead-letter queue is a work list for a person, not a trash can. Alert when anything lands in it, because every entry is a job that did not happen, and watch the age of the oldest entry. Inspect the job and the errors from its attempts, fix the cause, whether bad data, a missing permission or a bug, and only then redrive it: move it back to the main queue to run again, a small batch first. Redriving before the fix just sends the job back into the same failure. A redrive is one more delivery, which is harmless when the job's steps are idempotent. The healthy state of a dead-letter queue is empty, and one nobody watches is a slower way of losing work.
Running only as many as the limits allow
The services an agent depends on ration their capacity. A model service commonly limits both how many requests you may send per minute and how many tokens those requests may use per minute, and the limits vary by model and account; tool APIs set limits of their own. Go over and the service answers 429 Too Many Requests, often with a Retry-After header saying when to try again. The limit belongs to the service, but staying under it is your system's job.
The main lever is a concurrency limit: a cap on how many calls to a given service are in flight at once, enforced with a counter, a semaphore, that a worker must acquire before calling and release after. A token bucket does the related job of capping calls per unit of time while allowing a short burst. The arithmetic connects in-flight calls to rate. Suppose, for illustration, a service allows 60 requests per minute, which is 1 request per second, and each call takes 10 seconds. Ten calls in flight, each replaced as it finishes, complete 10 calls every 10 seconds, which is 10 / 10 = 1 request per second, exactly the limit. Thirty in flight would try for 30 / 10 = 3 requests per second, three times the limit, and the extra calls would be refused.
Two habits keep the limit honest. Every attempt passes through the limiter, retries included, because a refused call is still traffic, and a burst of refusals retried at once only draws more refusals: a retry storm. And the limit must be shared across the whole fleet, not set once per worker: ten workers each holding to 10 calls in flight add up to 100. Backoff with jitter, bounded attempts and one shared limiter keep a bad minute from turning into a lockout. How fast and how cheaply a pipeline runs within those limits is a separate question of throughput and batching, and sizing the worker pool for expected load is capacity planning.
Assume every step runs twice or stops halfway
Whether you are building an agent pipeline or taking an app of your own to production, sooner or later there is work that should not happen inside a request: a run that takes minutes, an email that must go out, a report built overnight, an upload that needs processing. The moment that work runs unattended, it meets crashed workers, lost acknowledgments, slow calls and rate limits, and it needs every mechanism here.
Two questions cover most of it, asked of every step. What happens if this runs twice? Queues redeliver and retries repeat, so twice will happen, and the answer has to be nothing new: idempotent steps, keys for effects that cannot be repeated, model outputs recorded once and reused. What happens if this stops halfway? Workers crash and calls time out, so halfway will happen, and the answer has to be that it resumes: leases that expire, retries with backoff and a cap, checkpoints in a durable store. Jobs that cannot succeed land in a dead-letter queue that someone watches, and a shared concurrency limit keeps the whole system inside what other services allow.
None of this needs a cluster. One machine running a queue, a few podman containers as workers and a database for checkpoints and keys is enough to make a pipeline survive its own failures. What it cannot fix is a step that reliably does the wrong thing. Reliable delivery gets the work done; whether the work is right, and the ways an agent's output goes wrong, are a separate study.
Next on your path to Run a coding agent you don't have to trust: Threat model for an agent ▸