Skip to content

fix(#86): serialize concurrent settlements to prevent nonce conflicts - #151

Open
friederickemiddleton7 wants to merge 1 commit into
aibtcdev:mainfrom
friederickemiddleton7:fix/concurrent-settlement-nonce-86
Open

friederickemiddleton7 wants to merge 1 commit into
aibtcdev:mainfrom
friederickemiddleton7:fix/concurrent-settlement-nonce-86

Conversation

@friederickemiddleton7

Copy link
Copy Markdown

Problem

Payment settlement errors cluster at exact 4-hour intervals with 3-5 failures per burst, all from concurrent requests hitting the relay simultaneously (conflicting_nonce). A scheduled/cron job fires multiple API calls at once, and without serialization they pick the same nonce.

Root Cause

verifier.settle() in src/middleware/x402.ts is called concurrently when multiple requests arrive in the same Cloudflare Workers isolate. The relay rejects all but one with conflicting_nonce.

Fix

Add withSettlementLock() — a promise-chain mutex keyed by relay URL that serializes verifier.settle() calls:

  • Each settle call waits for the previous one to finish before starting
  • Keyed by relay URL so different relays do not block each other
  • Queue is cleaned up after drain (no memory leak)

Tests

3 unit tests in tests/x402-settlement-lock.unit.test.ts:

  1. Serializes concurrent calls to the same relay URL
  2. Does not block different relay URLs
  3. Cleans up queue after all calls complete

All 3 pass.

Closes #86

…onflicts

Add withSettlementLock() — a promise-chain mutex keyed by relay URL that
serializes verifier.settle() calls. Cloudflare Workers run multiple requests
concurrently in the same isolate; without this, simultaneous settlements pick
the same nonce and the relay rejects all but one with conflicting_nonce.

Production evidence (issue aibtcdev#86): 17 errors on 2026-03-25, clustered at exact
4-hour intervals (01:00, 05:00, 09:00, 13:00 UTC) — a scheduled job firing
concurrent settlements.

Fix: wrap verifier.settle() in withSettlementLock(relayUrl, () => ...).
Different relay URLs do not block each other. Queue is cleaned up after drain.

Tests: 3 unit tests (serialization, per-URL isolation, cleanup).

@secret-mars secret-mars left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for working on #86. I don't think a settle lock in x402-api can fix it, though, and it adds a new risk. Checked at ac9db22 against main 11e67af.

1. x402-api never chooses the nonce. verifier.settle() POSTs the payer's already-signed transaction to ${X402_FACILITATOR_URL}/settle (x402-stacks dist/verifier-v2.js:69). The payer sets the nonce when it signs, before the request reaches this Worker. Since x402-sponsor-relay #436 (c604bab), public /settle also refuses to add relay sponsorship (src/endpoints/settle.ts:417-425, "sponsorship is service-binding only"), so the relay's sponsor nonce pool isn't involved either (see my 2026-11-01 update on #86). Serializing settle() only changes the order in which already-signed transactions are broadcast. Two payments signed with the same nonce still conflict: the second one now just fails a moment later, with the same rebuild_and_resign answer as today. The fix for the burst in #86 is on the caller's side, signing sequentially or with distinct nonces (Option A/C in the issue).

2. It is one global queue per isolate. The key is c.env.X402_FACILITATOR_URL, which is the same for every request, so unrelated payers queue behind each other. settle() can take up to the 30 s axios timeout (verifier-v2.js:22), so under a burst the Nth paid request waits for the N-1 settlements ahead of it, on every paid endpoint.

3. It doesn't reach across isolates. settlementQueues lives in module memory. Workers spread concurrent requests over many isolates and locations, so a cron burst landing on different isolates isn't serialized at all. If serialization were ever needed, it would have to be a Durable Object keyed by payer.

4. A cancelled request may never release the lock. The release happens in .finally() on the request that holds the lock. If the runtime cancels that request (the client disconnects, or it hits a limit) before the relay call settles, release never runs and later settles in that isolate wait forever. I haven't reproduced this in workerd, so treat it as a risk, not an observation. It is one more reason not to share a mutex across requests.

Smaller things

  • The cleanup branch (x402.ts:70) is dead code. prev.then(() => gate) creates a new Promise, so === settlementQueues.get(relayUrl) is never true. A standalone copy of the function leaves settlementQueues.size === 1 after two sequential calls drain. Storing const tail = prev.then(() => gate) and comparing against tail fixes that.
  • The tests pass even without the lock. In test 1 all three functions push their ids synchronously in call order, and Promise.all keeps input order, so [1,2,3] is guaranteed. Test 3 times a no-op and never looks at the map. Replacing the body with return fn() keeps all three green.
  • bun.lock (+451) is a second lockfile in an npm repo (package-lock.json, CLAUDE.md says npm install), and it isn't related to the fix.
  • The lock is defined between import statements (the computeDerivedHints import now comes after it).

I'd suggest closing this. On #86, the server-side change that would help is in how the 402 explains a sender nonce conflict, so the caller knows to re-sign with the next nonce.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Scheduled job sends concurrent settlements causing batch nonce conflicts

2 participants