P331 · Tool use

Atomic Budget Admission Before Enqueue

Reserve the permitted budget atomically before accepting expensive queued work.

Editorially reviewed

These examples and illustrative results are independently authored teaching materials, not measured model results.

Use case

A generation service has 10 teaching budget units left. Two simultaneous requests each estimate 6 units. If the front door only reads balance and workers charge later, both can be admitted. In-flight commitments must be handled at the shared budget boundary.

Mechanism

Make checking and reservation atomic in the authoritative store. Successful admission creates a reservation ID carried into the queue; failed admission does not enqueue. Use an idempotent request identity to prevent duplicate reservations on retries. Handle reservation success followed by enqueue failure through compensation or a transactional outbox. Reconcile actual usage on completion with explicit failure and expiry release rules.

Bad example

Let each 6-unit request read a balance of 10 and enqueue. Deduct when workers start; the front-door check will control the budget.

Good example

Atomically check and reserve for these concurrent requests. The first reserves 6 and enqueues with its reservation ID; the second sees 4 available and is denied enqueue. Record request identity and reservation state, compensate enqueue failure under the contract, and reconcile actual worker usage without treating completion as a new charge.

Why the change matters

Separate checking and reservation lets concurrent requests decide against the same old balance. Atomic admission counts unfinished commitments; binding jobs to reservations makes retries and compensation traceable.

Observable expectation

The teaching concurrency test admits one job, reserves 6 and leaves 4 available, with no denied job in the queue. Repeating the same request creates no second reservation. An enqueue failure releases the reservation or leaves a recoverable pending-enqueue state. Actual usage 5 returns 1 and closes the reservation under the chosen contract.

Limits

Estimates are not invoices. Strict spend caps also require bounded execution, coverage of all billable paths and reliable reconciliation. Do not expire a reservation freely while its worker is still running. Partial failure is especially relevant across separate queue and budget systems. These units are not currency or provider pricing advice.

Sources and evidence

Read the editorial criteria