Skip to content

Scheduled job sends concurrent settlements causing batch nonce conflicts #86

Open

Description

@whoabuddy

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

Activity

  1. tfireubs-ui commented on Mar 29, 2026

    @tfireubs-ui
    Contributor

    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 when settleResult.success is false with errorReason: '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.

  2. secret-mars commented on Oct 31, 2026

    @secret-mars
    Contributor

    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-271 returns sender_nonce_conflict when failure.responsible === "sender", and conflicting_nonce otherwise, meaning the sponsor's nonce. types.ts:68-72 documents that sponsor-fault conflicts on pre-sponsored /settle return conflicting_nonce while 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:

    classifyPaymentError(err, { success:false, errorReason:"conflicting_nonce" })
    → {"code":"invalid_transaction_state","message":"Payment expired, please sign a new payment","httpStatus":402}
    

    The same result comes back with status:"pending" present, because pending has no canonical branch. invalid_transaction_state then maps to nextSteps: "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) are retry_later (+30s) and only sender-category reasons are rebuild_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_conflict and client_bad_nonce → keep invalid_transaction_state / rebuild_and_resign (sender fault, so re-signing is correct)
    • conflicting_nonce → a retryable relay code, retry_later with retryAfter: 30, matching the table

    One caveat for whoever takes it: the relay also emits conflicting_nonce for a node ConflictingNonceInMempool client 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 emit sender_nonce_conflict there 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.

  3. secret-mars commented on Nov 1, 2026

    @secret-mars
    Contributor

    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 /settle never 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 current conflicting_nonce → rebuild_and_resign is therefore the right answer for /settle, in both cases. My suggested retry_later mapping, and the relay change I said I'd open, would not help anyone, so I'm not opening it. The dead branch in settle.ts:266-271 is real, but on /settle today 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 /settle no longer uses.


    Correction to my 2026-10-31 comment above. I said that from the relay, conflicting_nonce means a sponsor-side conflict and sender_nonce_conflict a sender-side one, and I concluded that x402-api should answer conflicting_nonce with retry_later. Reading further into the relay (main @ 078ad02), that split never reaches the response, so conflicting_nonce does not tell you whose nonce it was. Please don't act on my suggested mapping as written.

    Why, all in x402-sponsor-relay @ 078ad02:

    1. src/utils/stacks.ts:10 and :19-23: ConflictingNonceInMempool and BadNonce are in both NONCE_CONFLICT_REASONS and CLIENT_REJECTION_REASONS.
    2. src/services/settlement.ts:911-970: on a 4xx nonce conflict, the result carries responsible (from is_origin, via parseBroadcastOutcome/decideBroadcastAction) and always clientRejection: matchedReason (the comment at :957 says this is deliberate).
    3. src/endpoints/settle.ts:263-272: broadcastFailure checks failure.clientRejection before failure.nonceConflict. So every nonce conflict returns through mapClientRejectionToV2Code (src/endpoints/v2-helpers.ts:340-361):
      • ConflictingNonceInMempool → conflicting_nonce, whether responsible is sender or sponsor;
      • BadNonce → client_bad_nonce ("client must re-sign"), including the sponsor-origin case that parseBroadcastOutcome routes to nonce_too_low, sponsor responsible (src/utils/broadcast-outcome.ts:55-62).
    4. The SENDER_NONCE_CONFLICT / CONFLICTING_NONCE choice at settle.ts:266-271 is unreachable for these two reasons. src/__tests__/settle-responsor.test.ts doesn't catch it, because its fixture makeBroadcastOnlyError (:34-48) builds the result without clientRejection and re-implements the branch condition inline instead of calling the endpoint.

    What that means for this issue: x402-api can't safely turn conflicting_nonce into retry_later. In the sender case, waiting 30 s and resending the same payment fails again. Today's rebuild_and_resign is wrong only in the sponsor case. The fix belongs in the relay: let responsible win for nonce conflicts in broadcastFailure, and test it against a result shaped like settlement.ts returns. Then x402-api can map sender_nonce_conflict → rebuild_and_resign and conflicting_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.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions