All posts
·12 min read·Go, AI agents, Payments, Redis, PostgreSQL

Billing AI agents per tool call without losing a cent

How Nexus402 meters every MCP tool call with one atomic Redis Lua script, refuses to forward unpaid work, and settles into an append-only double-entry ledger — including every way it can fail.

On this page
  1. The shape of the problem
  2. The hot path
  3. One script, one slot, no floats
  4. Money is never a float
  5. Failing closed, case by case
  6. Idempotency without storing payloads
  7. A ledger that can't be quietly edited
  8. Reconciliation reports; humans repair
  9. Signing what leaves the building
  10. The numbers, honestly
  11. What I'd tell someone building this

AI agents are starting to call tools that cost real money to run. Somebody has to charge for those calls, and HTTP finally has a use for a status code that has sat "reserved for future use" for decades: 402 Payment Required.

Charging is the easy part. The hard part is everything that can go wrong between taking the money and doing the work — a cache that stops answering, a queue that times out, a server that dies mid-request, a client that retries. Over ten weeks, Pradip Dhungana and I built Nexus402 (case study), a clearinghouse that sits between agents and paid MCP tools, around one rule:

Every call is either paid for and recorded, or it is never forwarded. There is no third state.

This post walks through how that rule is enforced on the hot path, what happens in each failure mode, and how the money ends up in a ledger that can't be quietly edited.

The shape of the problem

A developer prepays a wallet and gets one API key. Their agent calls any published tool through the gateway — no SDK, just the HTTP client it already uses. A creator hosts the actual MCP server and publishes a fixed price per tool version. The gateway has to decide, for every single call, in a few milliseconds:

  • Is this key valid, and is it allowed to call this tool?
  • Can the wallet afford it, and is the key under its 24-hour spending cap?
  • If yes, take the money, make sure that fact is durable, then forward the call.

There are well-known alternatives. Coinbase's x402 protocol pays per request on-chain in USDC. We deliberately chose a prepaid fiat wallet instead. Our design record for that decision describes on-chain payment as "agent-native, compliance-hostile": the businesses most likely to pay for agent tools won't touch it yet, and it would double the compliance surface. A prepaid wallet is just a liability on a ledger, which is a problem accountants solved centuries ago.

The hot path

AI agent Gateway (Go) auth · rate limit · price deduct → publish → forward Creator's MCP server Redis one atomic Lua script AWS SQS CHARGED / VOIDED Worker every 5 minutes PostgreSQL double-entry journal 1 call 402/result 2 deduct 3 publish (sync) 4 signed, only after 3

Scroll sideways to see the full diagram →

The order is the whole design: money moves in step 2, the fact that it moved is made durable in step 3, and only then does step 4 happen.

On a warm key cache a call costs four Redis round-trips: a cached key lookup, a rate-limit script, the deduct script, and a commit script. Everything else — route resolution, the price, the tool's scope — comes from memory, and all of it is checked before any money moves.

Then the order that matters:

  1. Deduct. One Lua script checks and debits the wallet atomically.
  2. Publish. The gateway publishes a CHARGED event to SQS and waits for the publish to succeed.
  3. Commit. A second script marks the intent committed. Only a committed intent is ever forwarded.
  4. Forward. The request goes to the creator, signed.

Publishing synchronously on the hot path is an expensive choice — it's the single biggest latency risk in the system. But the alternative is forwarding work whose payment record might not exist yet, and that breaks the one rule.

One script, one slot, no floats

The entire money decision happens inside a single Redis Lua script, so nothing can interleave between "read the balance" and "debit the balance". Simplified, with generic key names:

-- All keys share one hash tag ({wallet}), so in a Redis Cluster
-- they live in the same slot and one EVAL can touch all of them atomically.
local balance_key, window_key, amounts_key, idem_key, pending_key =
  KEYS[1], KEYS[2], KEYS[3], KEYS[4], KEYS[5]
local price, cap, spend_id, req_hash = ARGV[1], ARGV[2], ARGV[3], ARGV[4]

-- 1. A spend that was already reversed can never debit again.
if is_tombstoned(spend_id) then return {5} end

-- 2. Idempotency: same key + different request is refused before any write.
local seen = redis.call('HGET', idem_key, 'hash')
if seen and seen ~= req_hash then return {4} end
if seen then return {3} end

-- 3. Rolling 24-hour cap, using the server's clock, never the client's.
local now = tonumber(redis.call('TIME')[1])
trim_spends_older_than(window_key, amounts_key, now - 86400)

local balance = redis.call('GET', balance_key) or '0'
local spent   = redis.call('HGET', amounts_key, 'total') or '0'
if dec_lt(balance, price) then return {1, balance, spent} end
if cap ~= '0' and dec_gt(dec_add(spent, price), cap) then
  return {1, balance, spent}
end

-- 4. Debit, record the spend, and open a pending intent — all in this EVAL.
redis.call('DECRBY', balance_key, price)  -- integer micro-dollars, done by Redis
record_spend(window_key, amounts_key, spend_id, price, now)
redis.call('HSET', idem_key, 'hash', req_hash, 'state', 'debited')
redis.call('ZADD', pending_key, now, spend_id)
return {0, dec_sub(balance, price), dec_add(spent, price)}

Two details are worth calling out.

The hash tag. Every key for a wallet embeds the same {…} tag, so Redis Cluster places them in one slot. Without that, a multi-key script would either fail with CROSSSLOT or force the keys onto one node by luck.

dec_lt, dec_add, dec_sub. Redis embeds Lua 5.1, whose only number type is a double. Integers stay exact up to 2⁵³ — about $9 billion in micro-dollars — which sounds like plenty. But "exact until it isn't" is not a property you want in a payment path, so the script does all money arithmetic on decimal strings, bounded to the int64 range. No float ever touches a balance.

Money is never a float

That rule runs through the whole system:

  • Internally, every amount is an int64 count of micro-dollars.
  • On the public API, amounts are decimal-dollar strings matching ^[0-9]{1,9}\.[0-9]{1,6}$. A bare "50" is an error, not $50 — an ambiguous amount should fail loudly, never be guessed.
  • On internal events, amount_micro travels as a JSON string, so no JSON parser along the way can round it.
  • A published tool version's price is immutable. Changing the price means publishing @v2. Metered and variable billing are banned outright; the price of a call is known before the call.
  • Fees truncate toward zero, and corrections are computed from cumulative totals so that a fully voided period nets to exactly zero.

When a wallet can't pay, the agent gets a machine-readable answer instead of a stack trace:

HTTP/1.1 402 Payment Required
X-Nexus-Error: Budget_Exhausted
X-Nexus-Required-Amount: 0.05
X-Nexus-Currency: USD

{"error":{"code":"Budget_Exhausted","required":"0.05","currency":"USD"}}

Failing closed, case by case

"Fail closed" is easy to say. Here is what it means for each failure, because each one needs a different answer.

Redis is down, or the deduct result is unknown. The gateway returns 503 with Retry-After. If the deduct might have landed — say the connection dropped after sending — the gateway tombstones that spend ID, so if the script does run late it hits check #1 and refuses. An outage costs availability, never money.

The debit succeeded but the SQS publish failed. This is the dangerous one: money has moved, but the record that it moved hasn't. The gateway marks the intent as reversing, then makes a VOIDED event durable — retrying the queue, then falling back to durable local storage — and only then reverses the debit:

// Simplified. The order of these lines is the point.
if err := events.PublishCharged(ctx, charge); err != nil {
	intents.MarkReversing(ctx, charge.SpendID)

	if err := events.MakeVoidDurable(ctx, charge); err != nil {
		// Can't record the reversal, so don't reverse. A credit with no
		// matching record is worse than a debit that a human must resolve.
		return unavailable(w, 30*time.Second)
	}

	budget.Reverse(ctx, charge.SpendID)
	intents.MarkReversed(ctx, charge.SpendID)
	return unavailable(w, 30*time.Second)
}

If even the VOIDED record can't be made durable, the reversal is withheld. That sounds backwards — why not just give the money back? Because an unrecorded credit is invisible to the ledger, and the ledger is the source of truth. A stuck debit that reconciliation will flag is recoverable; money that silently appeared in a wallet is not.

The gateway process dies between deduct and commit. Every gateway periodically looks for pending intents that never committed. It claims each one with a compare-and-set lease, so only one gateway acts on it, reverses the debit, and emits a VOIDED event with the original timestamp. The money is back in about a minute. Recovery is always void, never charge — the system never decides after the fact that you should have paid.

The creator fails. A connection, DNS, or TLS failure or timeout voids the charge. A non-2xx response before the first byte streams is refunded in full. A 2xx without a valid proof header is voided too. But once the response has started streaming, the charge stands: the gateway is an immutable ledger, not a judge of whether a half-finished answer was useful.

SQS delivers the same event twice. It's a standard queue, so at-least-once delivery is a given. Each event has an ID of correlation_id:status, the worker deduplicates per rollup bucket, and the same ID with a different body is treated as corruption and quarantined rather than guessed at.

The worker crashes mid-rollup. A rollup posts as one database transaction under its own idempotency key, and SQS messages are deleted only after that transaction commits. Redelivered events land as counted no-ops.

Idempotency without storing payloads

Agents retry. Networks make them retry more. The Idempotency-Key header is optional — requiring it would break the "no SDK" promise — but when it's present, the gateway binds it to a request hash: SHA-256 over a version tag, the key ID, the tool, the version, and the canonical request body with the JSON-RPC id removed. So a retry that only changes the JSON-RPC id still matches.

A retry with the same key gets 422 Idempotency_Conflict: no money moves and the tool doesn't run again. Notably, it does not replay the original result, because the gateway never stores request or response payloads. That's a deliberate privacy trade — the gateway sees tool traffic but keeps none of it. The idempotency record itself lives for 120 hours.

For any agent that retries, sending the header is the way to get exactly-once charging — and it costs one line of code, not an SDK.

A ledger that can't be quietly edited

Redis is the authority at the moment of spending; PostgreSQL is the truth. Every five minutes, the worker rolls charges into a double-entry journal. Simplified:

CREATE TABLE transactions (
  id              BIGSERIAL PRIMARY KEY,
  idempotency_key TEXT NOT NULL UNIQUE,
  request_hash    TEXT NOT NULL,
  reversal_of     BIGINT REFERENCES transactions (id),
  posted_at       TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE TABLE entries (
  transaction_id BIGINT NOT NULL REFERENCES transactions (id),
  line           INT    NOT NULL,
  account        TEXT   NOT NULL,
  amount_micro   BIGINT NOT NULL CHECK (amount_micro <> 0),
  PRIMARY KEY (transaction_id, line)
);

-- Every transaction must sum to zero. Checked once, at COMMIT,
-- so a transaction can insert its entries in any order.
CREATE CONSTRAINT TRIGGER entries_must_balance
  AFTER INSERT ON entries
  DEFERRABLE INITIALLY DEFERRED
  FOR EACH ROW EXECUTE FUNCTION assert_balanced();

-- Append-only: corrections are new reversing transactions, never edits.
CREATE TRIGGER entries_append_only
  BEFORE UPDATE OR DELETE ON entries
  FOR EACH ROW EXECUTE FUNCTION reject_mutation();

Truncation is blocked the same way, so the only way to change history is to add to it.

Charges are bucketed by unix(ts) / 300, and each bucket posts one balanced transaction per wallet, tool, and period. For a bucket where a wallet spent $1.20 on one tool with a 10% platform fee:

Account Side amount_micro
Wallet liability Debit +1,200,000
Creator payable Credit −1,080,000
Platform margin Credit −120,000

Late events post a correction transaction rather than touching the old one. Posting uses INSERT … ON CONFLICT DO NOTHING RETURNING, so the same key with the same hash replays harmlessly, and the same key with a different hash is a loud error.

Reconciliation reports; humans repair

A separate reconciliation tool compares the journal, the PostgreSQL wallet cache, and Redis, and classifies any drift. It is strictly read-only — it writes nothing to the journal, Redis, SQS, or Stripe — and exits non-zero for a person to investigate. Auto-repairing money is how one bug becomes two.

Signing what leaves the building

The gateway calls servers it doesn't control, so creators need to know a request really came from Nexus402, and Nexus402 needs to not become a proxy into somebody's internal network.

Every outbound request is signed with Ed25519 over six newline-joined fields: method, host, path and query, a Unix timestamp, the correlation ID, and a SHA-256 of the body. Creators accept a ±60-second window and verify against the host they registered, not the one in the inbound header. The request is signed only after a connection slot is held, so a signature can't go stale waiting in a queue.

On the way out, an SSRF guard blocks private, link-local, and cloud-metadata ranges, pins the resolved IP to defeat DNS rebinding, allows only HTTPS on port 443, never follows redirects, and refuses IPv4-mapped IPv6 literals — a classic way to sneak 127.0.0.1 past a naive check.

The numbers, honestly

I'll be precise here, because performance claims are where engineering writing most often lies.

  • Measured: about 210 requests per second with a p50 of 100 ms end to end, from Kathmandu to AWS against real SQS. Most of that time is the publish and the creator round-trip, not gateway work.
  • Measured locally: p50 17.4 ms and p99 33.3 ms against LocalStack, with Go's race detector on.
  • Tested for correctness: a double-spend gate runs 10,000 deductions against one wallet with 32 in flight, and the balance has to come out exact.

Nexus402 is live — if you're building or calling paid MCP tools, take a look.

What I'd tell someone building this

  1. Decide what failure costs before you write code. Here, an outage may cost availability; it may never cost money. Every design choice above falls out of that one sentence.
  2. Make the atomic unit genuinely atomic. One script, one slot, one round-trip for the money decision. Anything spread across calls will eventually interleave.
  3. Record before you reverse. A reversal without a durable record is just a second bug.
  4. Never float money, anywhere — including inside Lua, inside JSON, and on your API.
  5. Let reconciliation report, not repair. The tool that finds drift should never be the tool that "fixes" it.
  6. Write down every decision. Two hundred and fifty architecture decision records sounds excessive — until you need to remember, months later, exactly why the publish is synchronous.

If you're building payments for agents — or anything where "probably fine" isn't good enough — I'd like to compare notes. Get in touch.