All articles
Reliability··12 min read

Your SDK already retries. That is how you get charged twice.

The OpenAI and Anthropic clients retry twice by default and wait ten minutes before giving up, which is six times longer than your function is allowed to live. What happens at the boundary with someone else's API, in both directions.

If you call OpenAI or Anthropic from your app, their SDK retries failed requests twice by default, and waits ten minutes before deciding a request has failed. You did not write that retry. It is on.

That combination is three attempts of up to ten minutes each. Your Vercel function is killed at five minutes. The retry budget your SDK ships with exceeds the platform ceiling it runs on by a factor of six.

This article is about what happens at the boundary between your app and somebody else's, in both directions. It is the least glamorous part of building on other people's services and the part that charges a customer twice.

What your SDKs actually do

These are defaults read from the published source on 19 October 2026, not from documentation, because several of the docs are out of date about their own behaviour.

  • openai and @anthropic-ai/sdk: 2 retries, 600,000ms timeout. Both retry on connection errors, 408, 409, 429 and anything 500 or above.
  • Vercel AI SDK: 2 retries, no timeout at all.
  • stripe: 2 retries, 80,000ms timeout. Its own README still says 1, which has been wrong since 2024.
  • twilio: retries off by default, 30,000ms timeout.
  • resend: no retries, no timeout. It is bare fetch, so both are yours to set.

There is no consistency here, which is the point. You cannot reason about your app's behaviour under failure without checking each client you installed.

Why an automatic retry is dangerous

Because a timeout does not tell you the operation failed. It tells you that you stopped hearing about it. Stripe's engineering blog puts the ambiguity precisely: the call can succeed, and the connection can break before the server gets to tell you.

So a retry after a timeout is a request to do the thing again, sent in ignorance of whether it has already been done. For anything that charges money or sends a message, that is a second charge or a second email.

The HTTP specification is directive about this, and it is a standard rather than an opinion:

A client SHOULD NOT automatically retry a request with a non-idempotent method unless it has some means to know that the request semantics are actually idempotent, regardless of the method, or some means to detect that the original request was never applied.

· RFC 9110, section 9.2.2

Stripe's client is the well-behaved one here. It generates idempotency keys automatically when it retries a POST, which is why most people never discover this problem through Stripe. Your own retry loop around anything else has no such protection.

Idempotency keys, and the way people get them wrong

An idempotency key tells the provider “if you have already seen this exact operation, return the original result rather than doing it again.”

The mistake is generating the key inside the retry. A fresh UUID per attempt means every attempt is a new operation, which defeats the entire mechanism while appearing to use it. The key has to be a function of the business operation, so it is identical across every attempt.

await stripe.paymentIntents.create(params, { idempotencyKey: `order-charge:${orderId}` })

Retention varies and is worth knowing before you rely on it. Stripe v1 keeps keys for at least 24 hours, v2 for 30 days, Resend for 24 hours, Adyen for 7 to 14 days. Square does not publish a number.

Two Stripe behaviours worth building around. Replays come back with an Idempotent-Replayed: true header, which is a free signal you can log to find out whether this is happening to you. And errors raised before the operation starts, including rate limits, are not cached against the key, so a 429 does not burn it.

The IETF draft for an Idempotency-Keyheader is widely described as “the standard.” It expired and was archived without ever becoming an RFC. What exists is a set of vendor implementations that mostly agree. Check each provider rather than assuming a shared spec.

The part almost nothing teaches

Here is the failure that survives a correct-looking implementation, and it is the reason this article exists.

The standard advice is to add a table of processed event IDs with a unique constraint, so a duplicate request hits the constraint and stops. That advice is correct. It is also insufficient, and nobody says so.

Your unique constraint protects your database. The call to the payment provider happens outside that transaction, over a network, to a system your transaction cannot roll back. So the order of operations on a duplicate request is: charge the card again, then fail on the unique constraint. You end up with one order row and two charges, and your logs show an error that looks like the duplicate was successfully prevented.

Derek Comartin states the boundary exactly:

That inbox table protects our internal state. But the moment we cross that network boundary to the payment gateway, all bets are off. We kind of went from exactly once to at least once.

· Derek Comartin, CodeOpinion, Why External APIs Break Idempotency

Brandur Leach calls the underlying thing a foreign state mutation: once you have pushed data into a system outside your boundary, you are committed, because you cannot roll it back and you must not lose track of it.

The fixes, in the order to try them:

  • Let the provider deduplicate. An idempotency key derived from your own entity. Best option whenever it exists.
  • Look it up first. Query the provider for a charge carrying your reference before creating one. Still racy, often sufficient.
  • Serialise per business key. SELECT ... FOR UPDATE on the order row so only one attempt is in flight for that order.
  • Reconcile anyway.A job that compares your records against the provider's. Shopify runs exactly this and tracks the mismatches as a named anomaly.

And the framing to take away, from the same talk:

I don't think the goal is exactly once. A better goal is building a system and designing it that's effectively once.

· Derek Comartin, CodeOpinion

The other direction: your webhook endpoint

A webhook route is a public, unauthenticated POST endpoint that changes your billing state. Stripe also tells you to exempt it from CSRF protection, which means the signature check is not one layer of defence. It is the only authentication on that route.

Without verification, an attacker could send fake webhook events to your endpoint to trigger actions like fulfilling orders, granting account access, or modifying records.

· Stripe documentation, Webhooks

Four ways this breaks specifically in Next.js:

  • Parsed body. Verification runs over the exact bytes received. Use await request.text() in the App Router and read it once, then parse from that string.
  • Middleware. A matcher that catches your webhook path can consume or alter the body first. Exclude it.
  • Wrong function on edge. constructEvent is synchronous and fails on Web Crypto runtimes. Use await stripe.webhooks.constructEventAsync(...).
  • Scheme downgrade. Stripe sends a fake v0 signature for test events. Ignore any scheme that is not v1.

Replay protection is not universal, which surprises people. Stripe and Svix sign a timestamp and enforce a five minute tolerance. GitHub, Shopify and Twilio sign only the body, with no timestamp in the scheme at all, so a captured request stays valid indefinitely.

Your handler is slower than its deadline

Providers give you a response deadline far shorter than most people assume, and exceeding it is counted as a failure:

  • Slack: 3 seconds. Disabled entirely if more than 95% fail in an hour.
  • Shopify: 5 seconds. Eight retries over four hours, then your subscription is removed.
  • GitHub: 10 seconds, and no retries at all.
  • Twilio: 15 second read timeout, one retry by default.
  • Svix and Resend: 30 seconds. Eight retries over about ten hours.

GitHub is the one that inverts the risk. Everywhere else a slow handler causes duplicate work. On GitHub it causes permanent event loss, because nothing is coming back.

One more trap: a redirect counts as a failure. Stripe says so explicitly. If your webhook path picks up a trailing-slash or www redirect, deliveries fail silently while your route looks healthy.

The fix that is wrong on Vercel

The standard advice is to return 200 immediately and finish the work afterwards. The shape is right. The usual implementation on Vercel is not.

Doing the work in waitUntil, or in Next.js after()which is built on it, does not buy you a longer window. From Vercel's own reference: promises passed to waitUntil() have the same timeout as the function, and if the function times out the promises are cancelled.

So it shares one budget, has no retry, and has no durability. It is correct for logging and cache warming. It is wrong for “acknowledge, then do the real work,” which is exactly what everyone reaches for it to do.

The shape that actually works is to make the acknowledgement durable before returning:

  • Verify the signature. Reject immediately if it fails.
  • Insert the event into a table keyed by the provider's event ID. If that hits a unique violation, you have seen it before: return 200 and stop.
  • Hand the ID to a queue, or leave the row for a worker to pick up.
  • Return 200.

Deduplicate on the provider's ID, not yours: event.id for Stripe, X-GitHub-Delivery, X-Shopify-Webhook-Id, svix-id. And do not sort by the event timestamp. Stripe records created in whole seconds, so distinct events share one, and the documentation tells you directly to track IDs rather than using the timestamp to detect duplicates.

Scheduled jobs have the same property and it is easy to miss. Vercel documents cron delivery as best effort, including occasionally invoking the same run twice. Their own illustration is the clearest version of the rule. Safe: “set user status to active.” Unsafe: “increment user credit by 10,” because running twice doubles the credit.

Retries multiply down a stack

Worth knowing even though it mostly bites larger systems, because the arithmetic is unintuitive. From Google's SRE Book: if four layers each retry three times, one user action becomes 4³, that is 64 attemptson the database. AWS's version with five layers reaches 243 times the load.

At solo scale the realistic version is smaller and still real: the AI SDK's two built-in retries inside your own retry loop is up to nine calls per user action, on a metered API.

Jitter is the standard mitigation, and the canonical source is Marc Brooker's AWS post. His later correction is the more useful half: backoff helps in the short term, but is only valuable long term if it reduces total work. A million users pressing refresh do not benefit from each other's backoff. His summary is worth keeping: backoff is not a substitute for a good retry policy. Bound the number of attempts and stop.

Skip circuit breakers

A circuit breaker trips after a threshold of failures and fails fast instead of calling the dependency. It is on every systems-design list. A solo builder should not build one, and the evidence for that is unusually strong because it comes from the people who popularised it.

  • Netflix retired Hystrix, the canonical implementation. It is in maintenance mode, and the stated reason is a move toward adaptive approaches rather than pre-configured thresholds, which is precisely the model every tutorial teaches.
  • AWS cautions against them by name, saying breakers introduce modal behaviour that is difficult to test and can add significant time to recovery, and that they limit retries with a token bucket instead.
  • They can make things worse.Marc Brooker's objection is structural: circuit breakers are designed to turn partial failures into complete ones.
  • It is a code path that never runs.AWS's writing on fallback logic makes the decisive point for small apps: this code may not execute for years, and then executes for the first time during an incident. Their worked example turned a partial outage into a full site outage.

Do the four cheaper things instead. Set timeouts. Bound retries. Add jitter to anything periodic. Make operations idempotent, which is what makes every other mechanism safe.

What I could not establish

I wanted to claim this cluster is the most likely source of money-losing bugs in small apps. There is no ranking data for that, so the honest version is weaker: it is a category that reliably produces money-losing bugs, and the mechanisms are documented by the vendors themselves.

I also wanted to say this is absent from AI-generated code. No study, benchmark or audit supports that, so it is not in this article either.

What is checkable is the teaching gap. The two most-watched webhook tutorials on YouTube have 460,737 views between them. Searching their transcripts for signature, HMAC, verification, duplicate, replay or idempotency returns nothing relevant in either. The longer of the two runs two and a half hours. If this material feels unfamiliar, that is not a gap in you.

A few things that circulate as fact and did not survive checking. The AWS jitter post is frequently cited for a results table comparing strategies, and that post contains no tables, only graphs. Slack's well-known “Very Bad Day” postmortem is cited constantly as a retry-storm incident, and it does not mention retries at all. And “Node's fetch has no timeout” is imprecise: it has 300 second inactivity timeouts but no total deadline, so a server trickling one byte every few minutes holds your connection open indefinitely.

The checklist

  • Look up the retry and timeout defaults for every API client you installed. You have behaviour you did not choose.
  • Set a timeout below your function's limit, and a retry count you actually picked.
  • Use an idempotency key derived from the operation, never generated inside the retry.
  • Remember your unique constraint does not protect the remote call. Reconcile.
  • Verify webhook signatures over the raw body, before doing anything else.
  • Persist the event, then return 200. Not waitUntil.
  • Deduplicate on the provider's event ID, in the database, never in memory.
  • Make scheduled jobs safe to run twice.

Find out which of those apply to you

Fourteen questions, about three minutes, runs entirely in your browser. You get a ranked list of what's actually open, with the fix for each.

Run the free check

Sources

Quotations from the two interviews are transcribed from the published videos and lightly condensed for readability.