AlgoViz

Deployment, persistent state and cost

hard 7 min

Long-running agents need durable state, scheduling and explicit ownership of effects.

Video lesson · Chapter 1 of 4

Run seventy-three arrives twice

0:00 / 3:10

Theory

Read or listen first. About 2 min.

What it is

Long-running agents need durable state, scheduling and explicit ownership of effects. A queue or worker can retry a task after losing contact, while the previous attempt may already have committed part of the work. Model calls are only one component of runtime cost.

Why it exists

Trace attempts under a stable run identity. Correlate queue time, model calls, tools, checkpoints and business outcomes to determine whether a slow or expensive task needs a different prompt, a different scheduler or a state-recovery fix.

Resume a queued run after a worker disappears

Job lease → Checkpoint and ledger (deliver run ID). Checkpoint and ledger → Run outcome (emit attempt spans). Run outcome → Job lease (attribute repeated delivery)
Job lease → Checkpoint and ledger (deliver run ID). Checkpoint and ledger → Run outcome (emit attempt spans). Run outcome → Job lease (attribute repeated delivery)

Inside this chapter

Chapter sources
Agent Deployment Models
Short synchronous tasks can run within a request. Long-running or interruptible tasks need durable state and often a queue. Decide what happens when the user disconnects and who owns cancellation. A worker restart should recover a pending task without silently repeating its external effects.

Inline execution is simple but ties the task to one HTTP request: a dropped connection or a server restart loses the work. Queued execution decouples submission from running, which buys durability and retries at the cost of a status API, notifications and checkpointing. Whichever you choose, document who can cancel a run and what happens to effects already made.

Example. Disconnect a client after submitting a long-running job. Verify whether the documented contract cancels the run or allows it to resume.

Another example. A report-generation agent takes up to ten minutes. The API returns a run ID immediately, the browser polls for status, and closing the tab does not cancel the run unless the user presses Cancel.

Synchronous call or queued job

Disconnect behaviour is part of the contract, decided before launch.
State Management in Production
Persist run identity, state version, pending operations and approvals. Use concurrency control so two workers cannot both advance the same checkpoint unchecked. A resumed worker should read the committed operation ledger before deciding whether to retry a write.

Persist enough to resume without guessing: run ID, state version, pending operations, approvals and their expiries. Concurrency control (a version number checked on write, or a lease) prevents two workers from both advancing the same step. Before retrying any external write, the resumed worker reads the operation ledger, because the previous attempt may have committed before it crashed.

Example. Two workers read checkpoint 5. A compare-and-set advance lets only one commit checkpoint 6 with the corresponding business operation.

Another example. Two workers pick up a refund run after a lease timeout. Worker 1 commits checkpoint 6 and issues refund op r-73-4; worker 2's write is rejected, it reads the ledger, sees r-73-4 committed, and moves on without refunding twice.

Compare-and-set lets only one worker advance

The losing worker reloads instead of overwriting, then checks whether the business write already happened.
Cost Control
Budget tokens, tool charges, steps and elapsed time per run. Reserve enough capacity to return a final or partial answer. A cheap individual call can still produce an expensive task if the system delegates repeatedly. Report cost per completed task alongside the completion rate.

Budget along several axes at once: tokens, paid tool calls, steps and wall time. Children draw from the parent's budget as well as their own, otherwise a cheap per-call limit still allows an expensive tree of delegations. Hold back a reserve so the run can always produce a final or partial answer when the budget runs low, and report cost per completed task rather than per call.

Example. Three delegations each consume 500 tokens. Count them against the parent task’s remaining budget as well as each worker’s own limit.

Another example. A research agent spawns sub-agents per source. Capping each at 2,000 tokens looked safe until one query spawned 40 of them; a parent cap of 20,000 tokens turns that into a partial answer with a note about unchecked sources.

Parent budget absorbs delegated spend

EventTokens usedParent remaining (of 3,000)Reserve for final answer
Planning4002,600500 held
Delegate 15002,100500 held
Delegate 25001,600500 held
Delegate 35001,100500 held
Stop delegating600 usablewrite final or partial answer
Illustrative budget. Each delegate also has its own cap, but the parent counts all of them.
Observability
Connect model calls, tool executions, checkpoints and handoffs using a shared trace identity. Preserve safe input and outcome summaries and version identifiers. A slow task may be dominated by queue time rather than generation. Inspect spans before changing the model or prompt.

Give every run one trace ID and make model calls, tool calls, checkpoints and handoffs child spans with start times and durations. Record model, prompt and tool versions on the spans, plus safe summaries of inputs and outcomes. Read the critical path rather than summing durations, since parallel branches overlap. Teams often swap models to fix latency that was actually queueing.

Example. Join spans from the request, retrieval, model and write. Compare their wall times and account for branches that run concurrently.

Another example. A support agent feels slow at peak. The trace shows 4 seconds waiting for a worker and 1 second of generation, so the fix is worker capacity, not a smaller model.

Wall time versus summed span time

SpanStart (ms)Duration (ms)On the critical path?
Queue wait01,200yes
Retrieval A1,200300parallel
Retrieval B1,200300parallel
Model call1,500800yes
Write2,300100yes
Illustrative trace. Wall time is 2,400 ms; summing all spans gives 2,700 ms. Queue wait dominates, not the model.
Leases and heartbeats
A queue hands a job to a worker under a time-limited lease. The worker renews it with heartbeats while it runs; if the lease expires, the queue redelivers the job to another worker. Redelivery is normal, so every step must be safe to see twice.

Choose the lease length longer than a typical step but short enough that a crashed worker's job is picked up promptly. Attach a fencing token (a number that increases with each new lease) to writes, so a slow worker that wakes up after losing its lease cannot overwrite the new owner's progress.

Example. Worker A stalls on a long model call and misses two heartbeats. The lease on run 73 expires, worker B receives it, and worker A's late write is rejected because its lease token is stale.

Lease lifecycle for one job

The expiry edge is why at-least-once delivery is the default assumption.
Backpressure and concurrency limits
Limit how many runs, model calls and tool calls are in flight at once, per tenant and globally. When limits are reached, queue or reject new work explicitly instead of letting latency grow without bound or exhausting a provider's rate limits.

Example. A batch import submits 5,000 agent runs at once. A per-tenant cap of 50 concurrent runs keeps interactive users' requests flowing while the batch drains over time.

Admission with a concurrency cap
  1. 1New run arrivestenant T, batch import
  2. 2Check in-flight count50 of 50 for tenant T
  3. 3Hold in tenant queueposition reported to caller
  4. 4Slot freesa run completes
  5. 5Admit next runqueue drains steadily

Illustrative cap. The point is a visible queue rather than unbounded fan-out.

How it works

Step through the idea, or press Play.

Step 1 of 3

Job lease. run 73 delivered twice

Understand it

Worked example

Resume a queued run after a worker disappears

  1. 1

    run 73 delivered twice

    Delivery can repeat if a worker loses its lease. Attach a run identity, deadline and step budget to the job.

  2. 2

    Step 4 already committed

    Acquire or compare the state version before advancing. Recover prior external results using the operation ledger.

  3. 3

    One effect · two deliveries

    A trace connects both attempts to the same run. Compare queue dwell, model time and tool time before optimizing the slowest path.

Follow the handoffs

Trace attempts under a stable run identity. Correlate queue time, model calls, tools, checkpoints and business outcomes to determine whether a slow or expensive task needs a different prompt, a different scheduler or a state-recovery fix.

Run 73: two deliveries, one effect

The ledger check turns a duplicate delivery into a harmless retry.

Counting the right thing

SignalCount for run 73What it tells you
Queue deliveries2redelivery happened
Log lines for the usermanynothing about effects
Committed effects for op 73-41the business action happened once

Summary

The whole topic in one minute.

Several attempts can belong to one run, but the durable business ledger reveals whether the action happened once or twice.

Trace attempts under a stable run identity. Correlate queue time, model calls, tools, checkpoints and business outcomes to determine whether a slow or expensive task needs a different prompt, a different scheduler or a state-recovery fix.

Sources