Eight agent runs raced to remind one customer: a read-then-write check granted 8 of a limit of 2, an atomic reserve granted 2. Per-recipient budgets in a ledger.
Three reminders in one afternoon
Belgavi's Book Store added an agent to its help desk. When a return is waiting on the customer, the agent can send a reminder email, open a follow-up case or grant goodwill points. Each tool has its own check, and each run of the agent behaves sensibly on its own.
Then Geetha received three reminders about the same return in one afternoon. The first came from the original run. The second came from a re-planned run after a tool timeout. The third came from a run for a different case opened by Geetha. No single run did anything wrong. The rule that was broken, "do not email a customer about returns more than twice a day", was never written anywhere that all three runs had to pass through.
That rule is a budget: a limit on effects per recipient over a window of time. Before agents, a scheduled job or a person usually enforced it implicitly, because one process owned the outbound channel. With agents, many independent runs can produce the same effect, and the prompt is the wrong place for the limit. A model can be told "no more than two reminders a day", but it cannot see what other runs did and it cannot be trusted to count. This guide moves the budget into a ledger owned by deterministic code.
What stays deterministic
The agent still decides whether a reminder would help. The code decides whether the store is allowed to send one now. Three things stay outside the model:
- The policy. For each effect kind, a count limit, a value limit or both, over a sliding window, per recipient. In the companion example: two reminder emails per 24 hours, three new cases per 24 hours, and 30 goodwill points per 30 days.
- The ledger. A table of effects with recipient, kind, value, time and status. Status is
reserved,settledorreleased. - The check and the reservation, in one transaction. Counting existing effects and inserting the new one must be atomic, or two runs can both see room for one more.
The flow for every budgeted tool call is reserve, act, then settle or release. Reserve before the effect, because an effect that has already happened cannot be refused. Settle after it succeeds, and release if it fails, so that a rejected email does not use up the customer's allowance.
Why the obvious check loses a race
The first version most teams write reads the count, compares it with the limit and then writes:
count = db.execute("select count(*) from effects where recipient=? and kind=? and at > ?",
(recipient, kind, now - window)).fetchone()[0]
if count + 1 <= limit:
send_reminder()
db.execute("insert into effects(recipient, kind, at) values (?,?,?)", (recipient, kind, now))Run that from eight agent runs at once for the same customer, with a limit of two, and all eight can read a count of zero before any of them writes. The companion example does exactly this, with a barrier that makes every thread read before any writes. The naive version granted 8 of 8. The same eight runs calling the atomic reserve granted 2.
The atomic version opens a write transaction before it reads. In SQLite that is BEGIN IMMEDIATE, which takes the database write lock at the start, so a second run waits until the first has committed its reservation. In PostgreSQL, the equivalent is to lock a per-recipient row (SELECT ... FOR UPDATE on a budget row keyed by recipient and kind), or to use SERIALIZABLE and retry on serialization failures. A unique constraint does not help here, because the rule is about a count over a window, not about one row.
def reserve(db, recipient, kind, now, value=0, idempotency_key=None):
db.execute("begin immediate")
rows = db.execute("""select at, value from effects
where recipient=? and kind=? and status in ('reserved','settled') and at > ?
order by at""", (recipient, kind, now - WINDOW[kind])).fetchall()
if len(rows) + 1 > MAX_COUNT[kind]:
db.execute("commit")
return deny("count_budget_exhausted", next_allowed_at=rows[len(rows) - MAX_COUNT[kind]][0] + WINDOW[kind])
cur = db.execute("insert into effects(recipient, kind, value, status, at, idempotency_key) values (?,?,?,?,?,?)",
(recipient, kind, value, "reserved", now, idempotency_key))
db.execute("commit")
return allow(cur.lastrowid)The full version in the companion code also handles value budgets, returns an earlier reservation when the same idempotency key arrives again, and rolls back on any error.
A day of runs, replayed
The companion example replays six attempts to remind Geetha, with a limit of two per 24 hours:
| Time | Run | Result | Why |
|---|---|---|---|
| 0 h | run-1 | allowed | first reminder |
| 40 s | run-1 (retry) | allowed, same reservation | same idempotency key, nothing new is counted |
| 2 h | run-2 (re-plan) | allowed | second reminder |
| 5 h | run-3 | denied | two already counted; next allowed at 24 h |
| 9 h | run-4, case CASE-4131 | denied | the budget is per customer, not per case |
| 25 h | run-5 | allowed | the first reminder has left the window |
Two details matter. The retry with the same key returns the same reservation, so an ordinary retry costs nothing. The denial at 9 hours comes from a run working on a different case, which is exactly the situation a per-run or per-case check cannot see.
Value budgets work the same way. Jenya was granted 20 goodwill points; a second grant of 15 an hour later was denied because 35 would exceed 30; a grant of 10 was allowed because it fit exactly. The denial reports when enough of the window frees up, here 30 days after the first grant.
What the agent gets back
A denial is not an error to retry. It is information the agent should plan around. The ledger returns a small structure:
{"allowed": false, "reason": "count_budget_exhausted", "limit": "2 per 24 h",
"used_count": 2, "used_value": 0.0, "next_allowed_at": 86400}The tool layer turns this into a tool result such as "Reminder not sent: this customer has had 2 reminders in the last 24 hours; the next is allowed at 09:00 tomorrow." A well-instructed agent then chooses a different action, such as noting the case for follow-up, instead of trying another channel. The reservation identifier is not returned to the model. Settling and releasing are done by the tool code that performed the effect, so the model has no handle with which to free budget.
Make the reason codes part of the tool contract and test them. A model that receives a vague failure will often try again with slightly different arguments; one that receives a clear limit and a time usually stops.
Settle, release and the crash in between
Reserving before acting creates one gap: the process can crash after reserving and before settling. If the effect happened, the reservation should become settled; if it did not, it should be released. Leaving it reserved is the safe default, because it still counts against the budget, so a crash can only make the store send fewer reminders, never more.
A periodic sweep resolves old reservations by asking the effect's system what happened, using the idempotency key the effect was sent with. The email service, the case system and the points ledger each need to accept that key. That is the same reconciliation discussed for timed-out tool calls; the budget ledger adds no new uncertainty, it only records it.
The companion example shows the release path. A reminder to Tanishka was reserved, then the mail service rejected it and the reservation was released. The next two reminders were allowed and a third was denied, so the failed attempt did not consume budget.
Migration steps for an existing system
- Inventory the effects that reach a person or cost money. Emails, messages, cases, refunds, credits and callbacks. Not every tool needs a budget; reading data does not.
- Write the limits down as data. Most stores already have them in support policy or in a marketing preference centre. Put kind, window, count and value in a table or configuration file that is reviewed like code.
- Route every path through the ledger, not only the agent's. If the nightly reminder job and the help-desk agent both email customers, both must reserve from the same budget, or the agent will be blamed for the job's emails.
- Start in observe mode. Record reservations and the decision you would have made, but do not deny. Compare a week of data with complaints and opt-outs before switching to enforcement.
- Expose the denial reason to the agent and to the people reviewing runs. A run that stopped because of a budget should be visibly different from a run that failed.
Failure modes
- Budget keyed by the wrong identity. Keying by email address misses a customer with two addresses; keying by case misses a customer with two cases. Key by the identity your policy is about, usually the customer account.
- Window arithmetic drift. A sliding window over stored times is exact. Daily counters that reset at midnight let a run send two at 23:59 and two more at 00:01. Choose deliberately.
- Clock disagreement. Use the database clock, or one service clock, for
at. Different hosts with skewed clocks can move effects in or out of the window. - Hot recipients. One very active recipient serialises all reservations for that recipient. That is the point of the lock, but keep the transaction short: no network calls between reserve and commit.
- Budgets that never free. If reservations are never settled or released, the sweep must handle them, or the customer is silently blocked forever.
When a plain rate limiter is enough
If the concern is load on a downstream service, a token bucket in front of it is simpler, and it does not need per-recipient state. If only one process ever produces the effect, an in-process counter may do. The ledger earns its keep when several independent producers, agents among them, can cause the same effect for the same person, and the limit is about that person's experience rather than about capacity.
Verification
- Concurrency test: N parallel reservations for one recipient with a limit of k grant exactly k. The companion test runs eight against two.
- Boundary test: an effect exactly one window old no longer counts, and one second younger still does.
- Idempotency test: the same key twice counts once.
- Release test: a failed effect does not consume budget.
- Agent test: given a denial, the agent does not try another channel for the same purpose. This one needs your evaluation set, not a unit test.