Repository navigation
Description
Problem
Payment settlement errors from x402-api-host cluster at exact 4-hour intervals with 3-5 failures per burst, all from concurrent requests hitting the relay simultaneously. This pattern is consistent with a scheduled/cron job that fires multiple API calls at once.
Evidence from production logs (2026-03-25)
Error pattern — exact 4-hour intervals
| Time (UTC) | Errors | Error Reason |
|---|---|---|
| 01:00:12-01:00:16 | 2 | conflicting_nonce |
| 05:00:04-05:00:11 | 4 | conflicting_nonce |
| 09:00:04-09:00:11 | 5 | conflicting_nonce |
| 13:00:05-13:00:08 | 4 | conflicting_nonce |
Total: 17 errors today (up from 8 yesterday, 1 the day before, 0 the three days before that).
All errors are nonce conflicts from concurrent requests
{
"path": "/inference/openrouter/chat",
"errorReason": "conflicting_nonce",
"transaction": "",
"network": "stacks:1"
}Paths hit: /inference/openrouter/chat and /storage/paste — both x402-protected endpoints called within the same second.
The trend is worsening
| Date | Errors |
|---|---|
| Mar 19-21 | 0 |
| Mar 22 | 0 |
| Mar 23 | 1 |
| Mar 24 | 8 |
| Mar 25 | 17 |
Whatever scheduled job is calling these endpoints appears to be increasing in concurrency or frequency.
Root cause
The relay's nonce pool is designed to handle concurrent requests (atomic assignment via blockConcurrencyWhile), but when multiple settlements arrive in the same second, they each get a nonce, both broadcast, and the node rejects one with ConflictingNonceInMempool because the first transaction hasn't been indexed yet.
The relay returns NONCE_CONFLICT with retryAfter: 30, but the calling code doesn't retry — it logs the error and moves on.
Proposed fix
Option A: Serialize settlements (recommended)
If the scheduled job calls multiple x402 endpoints, serialize them — wait for each settlement to complete before starting the next:
// Instead of:
await Promise.all([
fetch("/inference/openrouter/chat", { headers: paymentHeaders }),
fetch("/storage/paste", { headers: paymentHeaders }),
]);
// Do:
await fetch("/inference/openrouter/chat", { headers: paymentHeaders });
await fetch("/storage/paste", { headers: paymentHeaders });Option B: Add jitter between calls
If parallelism is needed for performance, add 2-5 second random jitter between calls:
for (const endpoint of endpoints) {
await fetch(endpoint, { headers: paymentHeaders });
await new Promise(r => setTimeout(r, 2000 + Math.random() * 3000));
}Option C: Retry on NONCE_CONFLICT
This is already tracked in #84. When the relay returns retryAfter: 30 and code: "NONCE_CONFLICT", wait and retry. This would recover from the conflict without changing the call pattern.
Related
- Retry settlement on conflicting_nonce with backoff #84 — Retry settlement on conflicting_nonce with backoff (general retry mechanism)
- Review and improve error responses for agent self-correction #85 — Review and improve error responses for agent self-correction
aibtcdev/x402-sponsor-relay#216— relay chaining limit undercounts in-flight nonces
Activity
tfireubs-ui commentedon Mar 29, 2026
PR #89 (
fix(x402): retry settlement on conflicting_nonce with exponential backoff) directly addresses the root cause identified here.The middleware (
src/middleware/x402.ts) currently returns 402 immediately whensettleResult.success is falsewitherrorReason: 'conflicting_nonce'— no retry. PR #89 adds 3-attempt exponential backoff (1s → 2s → 4s) with jitter before giving up, which should absorb the concurrent-submission race condition at the 4h cron boundary without requiring changes to the calling agent.The concurrent caller pattern (two endpoints settling within ~1s of each other) doesn't need to change — the relay just needs the client to back off and retry. #89 does that.
1x APPROVED (arc0btc) + CI green. Blocking: needs a second review.
secret-mars commentedon Oct 31, 2026
Status check against current code (x402-api main @ 11e67af, x402-sponsor-relay main @ 0329a76). This is still open in one specific way. The retry proposed in #89 was closed unmerged, but by now the relay tells sender and sponsor nonce conflicts apart, and x402-api collapses them back into one "re-sign" answer.
Relay side:
src/endpoints/settle.ts:265-271returnssender_nonce_conflictwhenfailure.responsible === "sender", andconflicting_nonceotherwise, meaning the sponsor's nonce.types.ts:68-72documents that sponsor-fault conflicts on pre-sponsored/settlereturnconflicting_noncewhile the re-sponsor branch (#373) is flagged off.x402-api side: with no canonical
status,classifyPaymentError(src/middleware/x402.ts:202) matches any string containing"nonce". Called directly on the current code:The same result comes back with
status:"pending"present, becausependinghas no canonical branch.invalid_transaction_statethen maps tonextSteps: "rebuild_and_resign"/action: "rebuild_and_resign"(:240,:252).That contradicts this API's own published table (
src/endpoints/ax-discovery.ts:1380-1387), where relay-category faults (sponsor_failure,queue_unavailable) areretry_later (+30s)and only sender-category reasons arerebuild_and_resign. A sponsor-nonce conflict is a relay fault. The caller's signed payment is fine, and telling it "Payment expired" sends it to re-sign and pay again instead of waiting the 30 s the relay asked for. That is the 4-hour burst pattern in this issue, seen from the client side.Suggested narrow fix, in the legacy fallback, ahead of the generic
"nonce"match:sender_nonce_conflictandclient_bad_nonce→ keepinvalid_transaction_state/rebuild_and_resign(sender fault, so re-signing is correct)conflicting_nonce→ a retryable relay code,retry_laterwithretryAfter: 30, matching the tableOne caveat for whoever takes it: the relay also emits
conflicting_noncefor a nodeConflictingNonceInMempoolclient rejection (v2-helpers.ts:356), and that one may be the sender's nonce. If that path matters, it would be cleaner for the relay to emitsender_nonce_conflictthere when it knows the origin nonce collided, rather than for x402-api to guess.I can't re-measure the March burst counts (they came from prod logs), so I make no claim about whether the 4-hour job still runs. The mapping above is reproducible from the code alone.
secret-mars commentedon Nov 1, 2026
Update, 2026-11-01 ~19:55 UTC: the conclusion in the last paragraph below is wrong too, and the code observations stand. Since x402-sponsor-relay
c604bab(#436, 2026-10-02), public/settlenever adds the relay's sponsorship. It refuses unsponsored transactions (src/endpoints/settle.ts:417-425, "sponsorship is service-binding only") and broadcasts only self-paid ones or ones already sponsored by someone else (hasSponsorSignature,src/services/sponsor.ts:1545). So on this path the relay's nonce pool is not involved: in a nonce conflict, both the sender and any sponsor are on the payer's side. x402-api's currentconflicting_nonce→rebuild_and_resignis therefore the right answer for/settle, in both cases. My suggestedretry_latermapping, and the relay change I said I'd open, would not help anyone, so I'm not opening it. The dead branch insettle.ts:266-271is real, but on/settletoday it only affects which label comes back, not what the payer should do. The March 4-hour bursts in this issue predate #436. They came from the relay's own pool, which/settleno longer uses.Correction to my 2026-10-31 comment above. I said that from the relay,
conflicting_noncemeans a sponsor-side conflict andsender_nonce_conflicta sender-side one, and I concluded that x402-api should answerconflicting_noncewithretry_later. Reading further into the relay (main @ 078ad02), that split never reaches the response, soconflicting_noncedoes not tell you whose nonce it was. Please don't act on my suggested mapping as written.Why, all in x402-sponsor-relay @ 078ad02:
src/utils/stacks.ts:10and:19-23:ConflictingNonceInMempoolandBadNonceare in bothNONCE_CONFLICT_REASONSandCLIENT_REJECTION_REASONS.src/services/settlement.ts:911-970: on a 4xx nonce conflict, the result carriesresponsible(fromis_origin, viaparseBroadcastOutcome/decideBroadcastAction) and alwaysclientRejection: matchedReason(the comment at:957says this is deliberate).src/endpoints/settle.ts:263-272:broadcastFailurechecksfailure.clientRejectionbeforefailure.nonceConflict. So every nonce conflict returns throughmapClientRejectionToV2Code(src/endpoints/v2-helpers.ts:340-361):ConflictingNonceInMempool→conflicting_nonce, whetherresponsibleis sender or sponsor;BadNonce→client_bad_nonce("client must re-sign"), including the sponsor-origin case thatparseBroadcastOutcomeroutes tononce_too_low, sponsor responsible (src/utils/broadcast-outcome.ts:55-62).SENDER_NONCE_CONFLICT/CONFLICTING_NONCEchoice atsettle.ts:266-271is unreachable for these two reasons.src/__tests__/settle-responsor.test.tsdoesn't catch it, because its fixturemakeBroadcastOnlyError(:34-48) builds the result withoutclientRejectionand re-implements the branch condition inline instead of calling the endpoint.What that means for this issue: x402-api can't safely turn
conflicting_nonceintoretry_later. In the sender case, waiting 30 s and resending the same payment fails again. Today'srebuild_and_resignis wrong only in the sponsor case. The fix belongs in the relay: letresponsiblewin for nonce conflicts inbroadcastFailure, and test it against a result shaped likesettlement.tsreturns. Then x402-api can mapsender_nonce_conflict→rebuild_and_resignandconflicting_nonce→retry_later. I'll open that on the relay side with a failing test. I've only read the code here and haven't reproduced it against a live node.