Your agent run has $0.10 of budget left. Four workers each estimate their next model call at $0.08. They all check the balance before any of them records a cost. Each sees $0.10 and proceeds. If all four calls complete near their estimates, that is $0.32 of work against $0.10 remaining.
Nothing was wrong with any worker's arithmetic. The problem is that a check does not claim the capacity it observed. This is the same check-then-act race that appears in inventory, account balances, and job queues.
The fix for concurrent admission is to reserve an estimate atomically before dispatch. That can stop parallel workers from claiming the same remaining allowance. It is not, by itself, a hard cap on a provider invoice.
The rule: count holds before saying yes
- B be the run budget,
- S be actual cost already reported, and
- H be estimates reserved for calls that have not yet been settled.
A new call with estimate E may be admitted only when:
S + H + E ≤ B
The check and creation of the hold must be one atomic operation. If two workers make that decision concurrently, the second must see the first worker's hold. Otherwise, both can spend the same apparent headroom.
See the race in a small example
This standard-library-only program makes no network or model calls. The first half models a check with no reservation; the second adds an in-process lock around the admission decision.
import asyncio
from decimal import Decimal
BUDGET = Decimal("1.00")
ESTIMATE = Decimal("0.30")
WORKERS = 32
async def check_only():
# Every task reads the same balance before any cost is reported.
available = BUDGET
if available < ESTIMATE:
return False
await asyncio.sleep(0) # Let the other workers check too.
return True
async def reserve_atomically():
held = Decimal("0")
lock = asyncio.Lock()
async def attempt():
nonlocal held
async with lock:
if held + ESTIMATE > BUDGET:
return False
held += ESTIMATE
return True
admitted = await asyncio.gather(*(attempt() for _ in range(WORKERS)))
return sum(admitted), BUDGET - held
async def main():
naive = await asyncio.gather(*(check_only() for _ in range(WORKERS)))
print(f"Check only: {sum(naive)}/{WORKERS} workers proceed")
admitted, remaining = await reserve_atomically()
print(f"With reservations: {admitted}/{WORKERS} admitted; ${remaining} remains")
asyncio.run(main())
Expected output:
Check only: 32/32 workers proceed
With reservations: 3/32 admitted; $0.10 remains
The lock is only a teaching aid: it coordinates tasks in this one Python process, not separate processes or machines, and it disappears on restart. A production reservation needs a shared, persistent ledger that performs the balance check and hold creation atomically.
Apply the pattern to a real run
With AgentTrafficCop's public Python SDK, configure an eligible Pro or Team run budget before the workers start. Then reserve with a stable ID for each logical provider operation:
from agenttrafficcop import Guard
async with Guard(ATC_URL, ATC_API_KEY) as guard:
# Configure the run once before dispatching parallel work.
await guard.set_run_budget(session_id=run_id, budget_usd="1.00")
hold = await guard.reserve_spend(
session_id=run_id,
reservation_id=operation_id, # Persist this ID for this logical call.
estimated_cost_usd="0.08",
)
if hold["duplicate"] or hold["status"] != "held":
# A retry or duplicate is not permission to execute the call again.
raise RuntimeError("Reconcile this operation using your execution ledger")
# Dispatch only after a new hold is confirmed.
result = await call_provider_once()
ATC_URL, ATC_API_KEY, run_id, operation_id, and call_provider_once stand for values and application logic you provide. Do not put credentials in browser code. A rejected reservation means do not dispatch. Persist operation IDs in your own execution ledger, and use a provider idempotency key when the provider supports one.
A budget setting does not connect provider billing automatically. To settle a hold, a trusted backend must report the final incremental cost through the signed usage-reporting path. Keep its signing secret server-side. See the public SDK budget and reservation guide for the supported setup and reporting contract.
What reservations do—and do not—protect
Reservations close one specific gap: multiple workers claiming the same remaining allowance before their costs are reported. Their guarantees stop there:
- An estimate is not an invoice. If actual usage costs more than the estimate, final spend can exceed the budget.
- Admission cannot recall work already started. Calls admitted before the limit is reached may still finish.
- Every spending path must participate. Direct provider calls that bypass the reservation ledger are not covered.
- All workers need the same ledger. Separate local databases do not coordinate, even if workers share other state.
- A timeout leaves an unknown outcome. A timed-out call may have reached the provider. Do not blindly retry it or release its hold as zero-cost; reconcile it first. Holds do not expire automatically because the original operation may still be running.
- The scope is specific. A run budget is scoped to an API key and session; it is not automatically an account-wide or provider-wide limit.
If you need a strict provider-side ceiling, configure the provider's own spending controls too. Treat reservations as concurrent admission control based on estimates, not “this run can never cost more than $1.”
A production checklist
Before relying on a shared budget, verify that:
- The budget is configured before any worker can dispatch.
- The check and reservation are atomic in the shared persistent store.
- Each logical operation has a stable, persisted ID; retries reuse it.
- A failed or duplicate reservation never triggers another provider call.
- Final actual usage is reported exactly once by a trusted integration.
- Timeouts and crashes leave visible, reconcilable operations—not silent free retries.
- Provider-side limits cover estimation errors and work outside the guarded path.
A budget check answers, “Does the ledger look affordable right now?” A reservation answers, “Has this worker claimed room before it starts?” For parallel agents, that distinction prevents workers from spending the same observed headroom—without pretending estimates can control a provider's final bill.
Adding shared budgets to parallel agents?
Review the public SDK's requirements for run budgets, reservations, and trusted settlement.