How 10,000 Agents Should Call Each Other: Budgets, Cycles, and Failure Recovery
How 10,000 Agents Should Call Each Other: Budgets, Cycles, and Failure Recovery Task graph + queue design. Counterpart to the "synchronous call" design (Agent calls Agent directly); this document describes the "task g
How 10,000 Agents Should Call Each Other: Budgets, Cycles, and Failure Recovery
Task graph + queue design. Counterpart to the "synchronous call" design (Agent calls Agent directly); this document describes the "task graph" design.
Written for 10,000 agents: registry, selection layer, task graph, concurrency correctness, budget, failure recovery.
One line: A does not call B; A emits a task. The Scheduler dispatches it to a capable Agent; results are written back to the task graph, and A is woken to continue.
Framework: langchainrust β https://github.com/atliliw/langchainrust
1. End-to-end flow
What happens when a request arrives
-
Preparation (at system startup): every Agent registers with the registry: who it is, which capabilities it provides, capability version, which queue it consumes, health status, current load. B is the Agent that registered
order.query. -
Request arrives: the API receives the question, creates a
trace_id, and resolves thetenant_id. -
Create root task: insert T0 into the task table with the question, budget, deadline, status
ready, andpending_children=0. -
Enqueue: T0 is placed in the queue/task table. Default is asynchronous: the API immediately returns
202 + task_id; the client polls or uses SSE. Synchronous is the exception, with a deadline of at most 25 seconds. -
Scheduler claims: a dispatcher queries the registry for an Agent that can handle
handle_request(starting one if necessary), marks T0running, attaches a lease andlease_epoch, and hands the question to A. - A executes: A calls models/tools and discovers it needs order and device data.
-
Selection layer: A does not name
order.querydirectly. It says "I need order/device data", or callssearch_capabilities. A routing Agent / registry search narrows 10,000 Agents down to a few candidates and resolvesorder.query,device.status, and candidates B and C. -
A emits child tasks: code validates capability existence, A's permission, allowed domain edge,
depthlimit,ancestor_keysmiss, deadline, and budget. Then it atomically creates T1 (order) and T2 (device), both parented to T0; T0'spending_childrenis increased by the number of actually created child tasks (cache hits excluded), and T0 becomeswaiting. A returns and releases its lease. -
Scheduler finds an Agent for T1: query the registry β who registered
order.query? Find B. Push mode: the Scheduler CAS-claims T1 fromreadytorunning, then delivers it to B. Pull mode: the Scheduler only writes T1 to the queue; B CAS-claims it and only then setsrunning. Onlytask_idis delivered to B; B readsinput_reffrom the Task Store usingtask_id. For an on-demand worker, put the task inscheduledduring cold start and allow claiming only after it is ready; do not count cold-start time against the lease. - B executes: B reads T1's input, calls models/tools, and produces the order result. If B needs another capability, it goes through the selection layer and emits another child task.
-
B writes the result: B first writes the Result Store, then in the same transaction marks T1
doneand decrementspending_children. Only the caller that decrements it to zero may move T0 fromwaitingback toready. B releases. -
T2 follows the same path: the selection layer resolves
device.status, the Scheduler finds C (or C pulls from the queue), and T0's counter is decremented again on completion. -
Parent is woken: when all children reach a terminal state (
done/failed/cancelled) and the counter reaches zero, T0 returns toready, carrying a failure summary. -
A aggregates: the Scheduler claims T0 again and dispatches it to A (or an aggregator). A reads T1's and T2's
result_reffrom the Result Store, merges the parent'scached_result_refs, adds the failure summary, and produces the final answer. -
Return to user: A writes the answer back to T0 and marks it
done. The synchronous API returns it; an asynchronous client polls bytask_idor reads it over SSE. -
Failure/timeout: the lease expires β the task returns to
ready,attempts+1, and is re-dispatched. Whenattemptsreaches the limit βfailed; the parent receives the failure summary and may replan, switch Agents, or escalate to a human. -
Cancellation: the user disconnects or times out β T0 becomes
cancelled; children are cancelled according to policy.
Control flow and data flow are separate:
- Control flow: the Scheduler passes only
task_id/ capability / tenant / priority; it never passes content. - Data flow: input is written to the Task Store; results are written to the Result Store. Agents read input by
task_idand read results byresult_ref.
Key points:
-
capabilityis resolved by the selection layer (routing Agent / registry search). A only states intent. Code validates before writing the task. The Scheduler does not guess. - A decides only whether to split, which capability to request, and whether to wait for results. It does not care who executes.
- A does not hold a connection waiting for B; it exits after emitting child tasks.
- "Waking A" is not A waiting; it means T0 becomes
readyagain and the Scheduler dispatches it once more. - A must be resumable: either persist a checkpoint, or reconstruct context from "original question + child results".
- Parent counters must be atomic; leases must be renewable and carry a fencing token.
- Write-back order must be: write result first, then mark done, then decrement the parent counter.
What the Scheduler is: it is the "dispatcher" process/consumer in steps 4, 8, and 11 β not a single machine, and not a mysterious service. It loops over four actions:
- Take "pending" tasks from the database/queue;
- Find healthy Agents that provide the required capability;
- Mark the task "running", attach a lease, and hand it to the Agent;
- Reclaim expired leases and re-dispatch.
It does not execute tasks and does not call models; it only routes work orders to the right people. You can run many replicas; database locks or queue consumer groups prevent double dispatch.
2. The core change
From "making a phone call" to "filing a work order": the call stack disappears, the task graph becomes the single source of truth, and the Scheduler only dispatches.
3. Why it can handle 10,000 Agents
| Problem | How this design solves it |
|---|---|
| Call stack too deep | No call stack; A releases after emitting tasks |
| Path grows on every hop | Messages carry only task_id; parent/child links live in the DB |
| Dispatch center overloaded | Scheduler is sharded queue consumers; registry is read-cached; parent counters are sharded by trace |
| Worker dies | Tasks are durable; lease expiry re-dispatches; fencing token prevents stale writes |
| Traffic spike | Queue smooths bursts; workers scale horizontally |
| Cycles |
No cycle detection; termination is guaranteed by bounds (depth / tasks / tokens / deadline) plus explicit domain-level topology |
| Duplicate calls | Unique index dedup; capability metadata distinguishes idempotent read / stateful read / write |
It is not a "faster call"; it is a different execution model.
3.1 Three real pitfalls
The bottleneck moves from the Scheduler to the DB
The Task Store is the single source of truth. Heartbeats, ready polling, counter updates, and status writes for 10,000 Agents all hit one table, and T0'spending_childrenis a hot row.
Fixes: cache the registry; push ready tasks through the queue instead of polling; shard or merge parent-counter updates by trace; physically separate the Result Store from the Task Store.A 300-second synchronous API wait will be cut by the gateway first
Most load balancers / API gateways have a 60-second idle timeout. The synchronous path should either use a 25-second deadline and return202 + task_idfor polling, or use SSE / WebSocket with heartbeats. Do not block synchronously for 300 seconds."Rebuilding context" is not free
If A does not persist a checkpoint and reconstructs context from "original question + child results", it must call the model again. Every fan-out costs at least a plan call and a reduce call. At 10,000-agent concurrency, this token and latency cost dwarfs the queue hop.
4. Registry and selection layer (the key to 10,000 Agents)
4.1 What the registry contains
Each Agent registers at startup:
-
agent_id,tenant_id; -
capability: what it can do, e.g.handle_request,order.query; -
capability_version: v1 / v2; -
input_schema/output_schema; - queue or endpoint;
- health status, heartbeat time;
- current load, max concurrency;
- region / affinity labels.
4.2 How the selection layer narrows 10,000 to a few
- Recall: use embeddings or keywords to retrieve top-50 capabilities out of 10,000;
- Rule filtering: tenant, permission, region, version, health;
- Ranking: semantic similarity, historical success rate, load, latency;
-
Return top-k: usually 3β10 candidates, passed to A or a routing Agent. Return
read_type / max_age / capability_versionwith each candidate; A writes them into the task as-is, and later steps never re-query the Registry; - Per-domain floor: keep at least N candidates per domain, so top-50 does not all land in 2β3 domains and leave zero after filtering.
The root handle_request task follows the same path: at large scale, use the selection layer to pick the orchestrator Agent; at small scale, an agent_id may be specified directly. When a routing Agent is used, account for it per Β§4.7.
4.3 Recall failure / ambiguity
- Empty candidates β do not force a pick; return "no capability available";
- Several candidates with similar scores β let A ask again, return candidates to the user, or escalate to a human;
- Never "guess one" and route to the wrong domain.
4.4 Capability versions and governance
- When
order.query v1andv2coexist, route by schema compatibility; - Incompatible versions β do not dispatch;
- Roll out new versions gradually by tenant or traffic percentage;
- To retire a capability, drain its traffic first, then deregister it.
4.5 Health and circuit breaking
- Registered but unavailable is normal at 10,000 scale;
- Heartbeat expired β remove from the registry;
- Consecutive failures β open the circuit and stop dispatching;
- Recovery β half-open probe.
4.6 Permissions
- Capability allowlists live on domain edges, not on individual Agents;
- Validate at task creation: is domain(A) β target capability allowed?
- This prevents a prompt-injected Agent from emitting arbitrary capabilities and escalating privileges.
4.7 Cost of the selection layer
If the selection layer is a routing Agent, it is itself a model call: it costs latency, tokens, and a task.
If it is only a registry search, it is cheap, but accept that rule-based recall may be inaccurate.
Budget accounting:
- Routing Agent as a separate task β counts as 1 task + actual tokens;
- Routing as an in-process function β tokens are charged to the caller Agent's reservation; no extra task.
5. Components: who does what
Agent A ββemit child taskβββΆ Task Store (DB)
β
βΌ
Queue (notify task_id only)
β
βΌ
Worker / Agent (pull)
β
β CAS claim
βΌ
Task Store (ready β running)
β
ββββββββββββββββββββββΌβββββββββββββββββββββ
βΌ βΌ βΌ
Agent X Agent Y Agent Z
β β β
ββββββββββββββββΆ Result Store βββββββββββββ
β
βΌ
A's task becomes ready again and wakes to aggregate
Push mode: the Scheduler CAS-claims ready β running, then delivers to the Agent.
Pull mode: the Scheduler only writes to the queue; the Worker CAS-claims and only then sets running.
- Task Store: the single source of truth for tasks, parent/child links, status, budget, and result references;
- Registry: capability catalog; read-heavy, must be cached;
-
Queue: carries only
task_id / trace_id / capability / tenant_id / priority; no context; -
Scheduler: a set of stateless consumers; sharded by
trace_id/tenant to avoid global locks; - Agent/worker: stateless; claim tasks, execute, write results;
- Result Store: large results go to object storage / blackboard; tasks store only references; kept separate from the Task Store.
5.1 Push or pull
| Stage | Mode | Why |
|---|---|---|
| Capability routing | Push | Requires instance selection, priority, affinity, gradual rollout |
| Execution dispatch | Pull | Natural backpressure; busy workers pull less; easy to scale |
At large scale: push for routing, pull for execution. In pull mode, queue messages also need tenant_id / priority so consumers can rate-limit and shard.
The diagram shows pull mode; in push mode the Scheduler CAS-claims to running first, then delivers to the Agent.
6. Task table: the single source of truth
A task record should contain at least:
-
task_id: task identifier; -
tenant_id: tenant; the unique index must include it, otherwise tenants collide; -
trace_id: one user request; -
parent_task_id: parent task; -
capability+capability_version: required capability and version; -
input_ref: where the input lives (large inputs in object storage); -
input_hash: dedup key; -
status:scheduled / ready / running / waiting / done / failed / cancelled / budget_exhausted / dead_letter; -
depth: nesting depth; -
ancestor_keys: array of(capability, input_hash)on the ancestor chain; -
dedup_key:input_hashfor reads,task_idfor writes; -
read_type_snapshot: read-type snapshot taken at task creation; -
agent_id: who is executing; -
attempts: attempts so far; -
max_attempts: maximum attempts; -
lease_until: lease expiry; -
lease_epoch/attempt_id: fencing token; prevents stale worker writes; -
priority: priority; -
pending_children: number of unfinished children; -
budget: budget; -
deadline: deadline; -
result_ref: where the result lives; -
cached_result_refs: result references from cache hits that did not create a task row; -
error: failure reason; -
queued_at / started_at / finished_at: timestamps; -
idempotency_key: idempotency key for side effects.
Unique index:
(tenant_id, trace_id, capability, capability_version, dedup_key)
- Read tasks:
dedup_key = input_hash, eligible for dedup; - Write tasks:
dedup_key = task_id, unique per row; writes are never reused; -
read_typeuses the snapshot taken at task creation, not the Registry's live value.
6.1 Dedup cannot be one-size-fits-all
-
Idempotent read (e.g.
order.query): reuse the result; -
Stateful read (e.g.
device.status): may reuse, but only withinmax_age; re-query after that; - Write (refund, shipment): never reuse; every write gets a new task;
- Add
read_type: idempotent | stateful | writeandmax_ageto capability metadata.
7. Task state transitions
| State | Meaning |
|---|---|
scheduled |
Cold start / waiting for a worker to become ready; not claimable yet |
ready |
Pending; can be claimed by the Scheduler |
running |
In progress, with a lease |
waiting |
Waiting for children |
done |
Completed; result in the Result Store |
failed |
Terminal failure |
cancelled |
User or upstream cancellation |
budget_exhausted |
Budget exhausted; cannot continue |
dead_letter |
Poison task; moved to dead-letter |
Transitions:
- Cold start complete:
scheduledβready; - Scheduler claims:
readyβrunning; - A emits children: β
waiting; - All children reach a terminal state (
done/failed/cancelled) βwaitingback toready, with a failure summary; - Worker completes: β
done; - Lease expires:
runningback toready,attempts+1; -
attemptsreaches the limit: βfailed; - Budget insufficient: β
budget_exhausted; - Poison task fails repeatedly: β
dead_letter.
"All children done" is wrong; it must be "all children terminal" β failures and cancellations must also wake the parent.
7.1 Fallback reconciler (every 30 seconds)
-
scheduledtimeout β back toready+ alert; -
waitingwithpending_children=0β setready+ alert; -
readywithqueued_atolder than the queue threshold and remaining time < the capability's P99 Γ 1.5 βfailed(deadline_unreachable)and alertdeadline_unreachable_total.
8. Concurrency correctness (P0)
8.1 Parent counters must be atomic
When T1 and T2 finish at the same time, both workers can read pending_children=1, both decrement to zero, and both set T0 to ready β A is dispatched twice.
The decrement must be bound to the "mark done" CAS:
1. UPDATE tasks
SET status='done', finished_at=now()
WHERE task_id=:child AND status='running' AND lease_epoch=:epoch
RETURNING parent_task_id;
2. If step 1 affected 0 rows: already handled; commit and never decrement.
3. If parent_task_id IS NULL:
root task; commit and skip steps 4 and 5.
4. UPDATE tasks
SET pending_children = pending_children - 1
WHERE task_id=:parent AND pending_children > 0
RETURNING pending_children;
If it affects 0 rows: alert parent_decrement_noop_total; never stay silent.
5. If step 4 returns 0:
UPDATE tasks SET status='ready'
WHERE task_id=:parent AND status='waiting';
If it affects 0 rows: record parent_revive_blocked_total and skip.
- Root tasks have no parent; they must skip the decrement or every root completion will raise a false alert;
- Only a transaction where step 1 affected 1 row may decrement;
-
The decrement must not require
status='waiting', otherwise a re-dispatched parent can hang; -
Setting ready must require
status='waiting', otherwise cancelled/timed-out parents can be revived; - Queues are at-least-once; duplicate consumption must be blocked by the CAS;
- If parent counters are merged/decremented in batches, do not rely on "the caller that reaches zero wakes the parent"; let the Β§7.1 reconciler decide. For immediate wake-up, use bucketed counters.
8.2 Leases must renew, and carry a fencing token
Expiring lease_until and re-dispatching is not enough:
- An Agent's model call can take tens of seconds to minutes;
- Short lease β a healthy worker is declared dead β re-dispatch β two workers run the same task;
- Long lease β a real crash takes a long time to recover.
Add three things:
-
Heartbeat renewal: the worker periodically extends
lease_until; -
lease_epoch/attempt_id: monotonically increasing on every dispatch; - Epoch on writes: the DB accepts only the current epoch; a revived old worker cannot write.
8.3 Write-back order
Must be:
1. Write the Result Store first
2. Then mark the child task done
3. Decrement the parent counter in the same transaction
4. Only when the counter reaches 0, set the parent task ready
Reversing the order (marking done first) β the parent wakes and reads a result that is not yet persisted.
9. Multi-tenant fair scheduling
10,000 Agents do not serve a single tenant. Staying under quota does not mean a tenant cannot saturate the system momentarily.
- Per-tenant concurrent task limit: how many tasks a tenant may run at once;
- Weighted fair queue: weight = plan tier, so free tenants cannot crowd out paid tenants;
- Per-capability concurrency limit: when a capability has many instances, cap total concurrency;
- Priority aging: low-priority tasks gain priority after waiting past a threshold, avoiding starvation;
- Quota vs scheduling: quota is a billing limit; scheduling is momentary fairness. Both are required.
A's autonomy is covered in Β§1: it only decides whether to split, which capability to request, and whether to wait; it does not care who executes.
10. 10,000 Agents: why no cycle detection, and what guarantees termination?
| System | In plain terms | Mechanism |
|---|---|---|
| LangGraph | Defaults differ by entry point/version (LangChain 25, local LangGraph 1000, hosted higher); set it explicitly. State is checkpointed per step and can resume after a crash |
recursion_limit + checkpointer |
| OpenAI Agents SDK | At most 10 turns per task; stop after that; one turn = one model call | max_turns |
| AutoGen 0.2 | An Agent may auto-reply at most N consecutive times | max_consecutive_auto_reply |
| AutoGen 0.4+ | Termination conditions: max messages / keyword match / token usage / timeout / handoff. AutoGen is in maintenance mode; the community fork AG2 keeps the old API |
TerminationCondition; reset after each run |
| Microsoft Agent Framework | Successor formed by merging AutoGen and Semantic Kernel; native MCP/A2A | MAF 1.0 |
| Temporal | Workflow is code; each step can retry with a limit. A single workflow has at most 2,000 unfinished activities, 51,200 event-history entries, 2 MB per Blob, and 200 namespace ops/s β all of these are hit before continue-as-new. The 2 MB Blob limit is a hard error, so large results must go to the Result Store | Workflow + Activity + RetryPolicy |
| Step Functions | Explicit state machine. Standard: 25k event history / 1 year; Express: 5 minutes. Single-state payload 256 KB. Standard concurrency 1M / Express 100k. Standard charges $0.025 per 1,000 state transitions | Explicit state machine |
| Anthropic multi-agent | Lead Agent dispatches sub-agents and allocates effort/budget by task complexity; token usage is about 15Γ a normal chat | orchestrator-worker, not a hard circuit breaker |
Important boundary: these limits are all inside a single process / single graph / single workflow. They cannot govern 10,000 Agents across services.
Cross-service execution must rely on its own depth / tasks / token budget, leases, and task table.
What they have in common, in plain terms:
- Do not guess whether a loop is necessary;
- Set total turns, total tokens, and total time, and stop at the limit;
- Keep a human fallback, and escalate when the budget is exhausted.
Note: not every system "only walks a pre-drawn path". LangGraph / Step Functions use explicit topology; AutoGen can call any registered tool; Anthropic's orchestrator decides at runtime which sub-agents to dispatch.
So "explicit topology" is not true for all six; only "bounded execution" is common.
"At most N times per edge" is not mainstream; most systems use "at most N turns / N tokens in total".
Defaults and APIs change across versions; refer to the corresponding version's documentation.
10.1 The 10,000-Agent solution
The problem:
With 10,000 Agents calling each other, AβBβA can loop forever; but BβA is sometimes legitimate; and you cannot write a rule for each of 10,000 Agents.
Main principles:
- Layering / domain-level topology: split 10,000 Agents into 20 domains of 500 each; write rules only for the 20Γ20 domain relationships;
- Task-based inter-Agent calls: B does not call A directly; it emits a task; the Scheduler dispatches it to A; A writes the result; B is woken;
- Global limits: see Β§11.2; the tenant plan is a hard cap, and topology defaults must fit inside it;
- Human fallback: on exhaustion, return a partial result or escalate.
Concretely for 10,000 Agents:
-
Domains: write only 20Γ20 domain rules:
- order domain β device domain: allowed;
- device domain β order domain: allowed;
- device domain β order-domain refund: not allowed.
-
Task-based: while executing T1 (
order.query), B discovers it needs another device D2 β writes T3:capability=device.status, input=D2, parent=T1.ancestor_keyscontains only(handle_request, h0)and(order.query, h1); the target(device.status, hD2)is absent β allowed. The Scheduler dispatches it to C; C writes the result; T1's counter reaches zero and B is woken. - Global budget: see Β§11.2; this section's domain rules do not set numbers.
-
Legitimate re-entry: allowed by domain rules;
ancestor_keysblocks only "same capability + same input", withdepth β€ 8as a backstop. If re-entry is not needed, do not write that domain edge. - Still unresolved at the limit: return a partial result, or escalate to a human.
Two cheap checks that actually prevent cycles:
-
depth: childdepth = parent.depth + 1; reject above 8; -
ancestor_keys: childancestor_keys = parent.ancestor_keys + (parent.capability, parent.input_hash); if the target(capability, input_hash)is already present β reject. Same capability with a different input is allowed.
Only the ancestor chain is checked, not the whole graph; it is one array-membership test with negligible cost.
input_hash is computed only over normalized business input (excluding timestamps, trace_id, random ordering, temperature, and other volatile fields). Matching has two levels: exact (capability, input_hash) hit β reject; capability-only hit and the domain edge has no allow_reentrant β reject.
Note: this is one implementation of "domain rules + task-based execution + global budget"; the mainstream principles are layering, bounded execution, and human fallback. Concrete rules differ by company.
10.2 Dedup
unique(tenant_id, trace_id, capability, capability_version, dedup_key):
- Read tasks:
dedup_key = input_hash, eligible for dedup; - Write tasks:
dedup_key = task_id, unique per row; writes are never reused; - Idempotent read already
doneβ reuse; - Stateful read already
doneβ checkmax_age; re-query when stale; - Write β never reuse;
- Cache hit β do not create a task row; atomically append the hit
result_refto the parent'scached_result_refsusing a DB-side array append (never an application-level read-modify-write); A aggregates by reading childresult_refβͺcached_result_refs; - Currently
runningβ wait; do not execute again; -
failedβ decide whether to retry by policy.
For the diamond AβBβD and AβCβD, D executes only once (when reuse is allowed).
11. How budgets are controlled
11.1 What the five budgets cover
| Budget | Covers | Does not cover |
|---|---|---|
| depth | Nesting depth; parent +1; reject above 8 | Total volume |
| tasks | Total new tasks per trace | Retries and re-dispatches |
| tokens | Actual model usage: prompt + completion + reasoning | Business database reads/writes |
| deadline | Absolute time; must finish by then | Not "30 seconds per call"; it is the whole-request deadline |
| cost | tokens Γ model unit price | Disabled when no price table exists |
11.2 Where budgets come from
When root task T0 is created, four layers apply:
- No topology declared: depth 8, tasks 2000, 200k tokens, 300 seconds;
- Tenant plan: free 48k, paid 640k; this is a hard cap;
- Topology default: fan-out 500k tokens (50 Γ 8k = 400k, leaving 100k headroom), plan 500k; it can only be allocated within the plan quota;
- Request override: may only lower the budget; it cannot exceed the plan cap.
Composition rule: final budget = min(plan, topology default, request override); later layers do not simply overwrite earlier ones.
Write into the T0 row:
T0: depth=0, tasks_left=2000, tokens_left=500000, deadline=now+300s, cost_left=...
11.3 How budget is divided among children
When A creates T1 and T2, each child reserves a slice:
T1: depth=1, tasks+1, reserve 8k tokens
T2: depth=1, tasks+1, reserve 8k tokens
T0: tasks_left=1998, tokens_left=474k (T0's own plan 8k and selection 2k already deducted)
Rules:
- Each child has a per-task cap; it cannot consume the parent's entire budget;
- Siblings split evenly or by priority, so one branch cannot starve the others;
- Insufficient reservation β do not create the child; return
budget_exhausted; - Reservation + deduction must be atomic: Redis Lua or a DB transaction.
11.4 When to deduct, and how many times
| Moment | Deduct tasks? | Deduct tokens? |
|---|---|---|
| Create task | tasks +1, depth = parent.depth + 1 | Reserve |
| Scheduler dispatch | No | No (already reserved at creation) |
| Re-dispatch / retry of the same task (attempt+1) | tasks unchanged, depth unchanged | Re-reserve (whether or not it executed; full refund if it never ran; unused portion refunded if it ran) |
| Failure before dispatch (connect failure / startup timeout) | tasks unchanged | Full refund |
| Cache hit | No | No |
tasks increases only when a new task is created; retries and re-dispatches only increase attempts.
Each task also needs: max_attempts=3; cumulative cost cap = max_attempts Γ per-task reservation; stop when exceeded. This prevents a task from failing halfway, refunding most of the reservation, and retrying forever.
11.5 Settlement on completion
Success:
Reserved 8k, actually used 3k β refund 5k
tasks is not refunded (the task was created)
Failure:
Failed after execution: tasks is not refunded; tokens settle at actual usage, unused portion refunded
Failed before dispatch (connect failure): task returns to ready, tasks unchanged; tokens fully refunded
Actual usage > reservation:
- Enforce
max_tokens/ output-length limits before the call; - Set the reservation from the P99 output length;
- Do not "reject after exceeding" β the call has already happened; rejection is meaningless;
- Overdraft up to the request's total budget is allowed, but never beyond it.
11.6 What happens when budget runs out
- tasks exhausted: stop creating tasks; let running tasks finish;
- Reserve 10% (or a fixed 8k) at root creation as a wrap-up allowance for plan/reduce, not usable by child tasks;
- tokens exhausted: stop calling models; return existing results;
- deadline reached: cancel unstarted tasks; treat running tasks as timed out;
- cost exhausted: same as tokens;
- Finally: return partial results + what is missing, or escalate to a human.
11.7 What 10,000 Agents add
- Tenant quotas: tokens per tenant per day/month;
- Per-subtree budgets: each domain / branch has its own allowance;
- Per-Agent concurrency limits: how many tasks an Agent runs at once;
- Cost budget: multi-model cost computed from a price table;
- Budget observability: used, remaining, and exhaustion reason per request/tenant.
11.8 A self-consistent example
T0: depth=0, tasks_left=2000, tokens_left=500k
The following uses the paid plan + fan-out tier of 500k tokens.
T0 reserves 8k for plan:
tokens_left=492k
Selection layer performs 2 searches (in-process, 1k each):
tokens_left=490k
Create T1 and T2:
T1: depth=1, tasks_left=1999, reserve 8k
T2: depth=1, tasks_left=1998, reserve 8k
tokens_left=474k
T1 succeeds, actual 3k:
refund 5k
tokens_left=479k
T2 fails, actual 1k:
depth/tasks unchanged
refund 7k
tokens_left=486k
T2 retries (same task, attempt+1):
tasks unchanged
re-reserve 8k
tokens_left=478k
T2 retry succeeds, actual 2k:
refund 6k
tokens_left=484k
A aggregates, reserves 8k for reduce:
tokens_left=476k
actual 5k, refund 3k
tokens_left=479k
Create 48 more tasks (8k each):
tasks_left=1950
tokens_left=479k - 384k = 95k
Continue creating until tokens_left=0 β budget_exhausted
tasks will not reach 0 first
11.9 Common mistakes
- Deducting at task creation and again at dispatch;
- Charging tasks on retries, so actual calls far exceed the budget;
- Multiple instances reading stale values and overspending;
- Reserving at the minimum, so the actual run immediately overshoots;
- Looking only at tokens, not cost;
- Not refunding unused budget, starving the parent;
- Keeping budgets only in memory; a process crash loses everything.
One line: set the total budget at entry, reserve when creating tasks, never deduct again at dispatch, settle at actual usage, and stop when exhausted.
12. Failure, recovery, idempotency
| Situation | Handling |
|---|---|
| Worker crashes |
lease_until expires β task returns to ready, attempts+1, re-dispatched to another worker |
| Repeated failure |
attempts reaches the limit β failed β notify the parent with a failure summary |
| Old worker revives | Writes carry lease_epoch; the DB rejects stale epochs, preventing overwrites |
| Duplicate side effects | Side effects keyed by task_id; write results are never reused |
| Whole process dies | Tasks are in the DB; ready tasks continue; running tasks restart from the beginning after lease expiry β they cannot "continue" |
| Traffic spike | Queue smooths bursts; limit concurrency per capability/Agent |
| Poison task | Move to dead-letter; alert / human |
Idempotency keys need two phases: prepared / committed, with lease_epoch. A worker first claims prepared, performs the side effect, then marks committed. A new worker can take over an old prepared after a crash. But this is only an accelerator, not a correctness guarantee: write operations must bind a business optimistic lock (WHERE status='paid') or pass task_id downstream as an Idempotency-Key. Otherwise, taking over an "executed but not committed" operation can refund twice.
12.1 Partial success
50 child tasks, 47 succeed (paid plan + fan-out tier):
- Wait for all: aggregate after every task is terminal;
- Quorum: continue once a threshold is reached;
- Fail fast: cancel the rest when a critical child fails;
- Decide by topology; do not default to "wait for the slowest one".
12.2 Deadline propagation
Child deadline:
min(parent.deadline, now + per-task limit)
Before dispatch, the Scheduler checks whether the remaining time is enough to finish; if not, it does not dispatch β avoiding a 60-second task launched one second before the deadline.
Cold-start time is accounted separately and does not count against the per-task limit; during cold start the task stays in scheduled, and the lease does not start.
13. Cost and boundaries
| Item | Description |
|---|---|
| Extra infrastructure | DB + queue + Scheduler + Registry + Result Store |
| Latency | One extra queue hop; the bigger cost is the model call to rebuild context when A wakes |
| Eventual consistency | Results are not immediately visible; wait for task state changes |
| Agent changes | Must support suspend/resume, not just synchronous calls |
| Operations | Queue backlog, leases, retries, dead-letter, DB hot rows |
| Cost | Fan-out needs at least plan + reduce model calls; at 10,000 concurrency, token cost far exceeds queue cost |
It is not a silver bullet: it trades "call-stack complexity" for "task-graph / queue / state-machine complexity".
13.1 Risks of rebuilding context
If A rebuilds context with an LLM after waking, it may emit T1/T2 again:
- Dedup keys can block this, but only if
input_hashis stable; - If the context includes timestamps or the message order changes, the hash changes and dedup fails;
- Hard rules:
- Inject the "list of existing child tasks" as deterministic input when waking;
- Allow only one non-terminal child per
(parent_task_id, capability, dedup_key); otherwise vote/debate would be blocked; - This rule applies only to
read_type β write; write-task re-entry is handled by idempotency keys + business optimistic locks, not by a task-table unique constraint; - Before dispatching a parent, reconcile
pending_children = COUNT(*) WHERE parent_task_id=:t AND status NOT IN (terminal)and overwrite with the real value.
13.2 Cross-trace cache and capacity
- Task dedup only covers one request; cross-request reuse goes through the Result Store cache:
capability + capability_version + input_hash + TTL; - Partition the task table by day/tenant; archive cold
donedata; set a TTL on the Result Store; set a retention period for dead-letter.
14. Implementation order
- Task table + state machine +
trace_id/tenant_id; - Queue + Scheduler + leases;
- Instrument observability first: trace aggregation, per-hop latency, tokens, failure rate; without this you cannot tell whether the system is healthy;
- Registry + selection layer (recall / filtering / top-k / health / versions);
- Convert large topologies (fan-out / plan / vote / debate) to task emission first;
- Budgets, retries, idempotency, fencing, dead-letter;
- Keep the "synchronous call" design for small synchronous consultations; do not force a full rewrite;
- Scale workers, scale partitions, load-test.
Minimum metric set: parent_decrement_noop_total (must stay at 0), dedup_hit_total{read_type}, tasks_per_trace distribution, task_lease_expired_total{capability}, budget_exhausted_total{reason}, queue_depth / oldest_ready_age_seconds, cycle_reject_total{reason=depth|ancestor_key}, cached_hit_total, parent_revive_blocked_total.
Let large fan-outs use the task graph while small consultations stay synchronous; the two coexist, not either-or.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.