Retrying once after a timeout can double-charge a customer; Stripe's recommendation is to use idempotency keys so the server can recognize resent requests.
Key Takeaways
- When you hit a network error or a 500, you cannot know what the server did. Retry with the same idempotency key and the same parameters, then reconcile via webhooks.
- Webhooks can arrive duplicated and out of order. Deduplicate by event ID and never rely on ordering.
- Return 2xx quickly, offload heavy work to a queue, and find out which providers do not automatically resend webhooks.
At 9 a.m. on Monday, the customer's accountant sends a screenshot: the same order was charged twice. The logs show the network was flaky over the weekend, the payment creation request timed out, and your job dutifully retried once as configured.
The code has no syntax errors and never crashed. What went wrong is an assumption: that requests arrive exactly once, in order, and always get a definitive answer. For a Forward Deployed Engineer (FDE), this assumption gets broken almost every day.
Palantir describes the FDE role as embedding engineers in customer teams to solve their most pressing problems. Working inside customer systems also means that sooner or later you will touch the pipes connecting those systems to external ones. Build the pipes solidly, and you earn trust.
Build them carelessly, and you will spend a week explaining why the numbers don't match.
When you receive an error, you don't know what happened
First, accept an uncomfortable fact. Stripe's error handling documentation states it plainly: after a network error, the client cannot know whether the server received the request. A write operation that receives a 500 response must also be treated as having an uncertain outcome—the operation may or may not have executed.
So blindly retrying is dangerous, while not retrying at all can lose orders. The way out is the idempotency key: a client-generated string, up to 255 characters, for which Stripe recommends UUID V4. Attach it to the request, and the server can recognize duplicate submissions.
Stripe's mechanism is simple: for each key, it stores the status code and response body of the first request—even if that request failed—and every subsequent retry returns that result unchanged. If the same key is used with different parameters, the idempotency layer returns an error, preventing that mistake.
There are three details beginners often miss. Keys may be purged after 24 hours, so don't treat them as a permanent record. All POST requests accept idempotency keys, while attaching a key to GET or DELETE has no effect, because those methods are inherently idempotent.
Also, after a network error, Stripe's advice is to keep retrying with the same key and the same parameters until the server returns a result.
Correctly rewriting a payment job
Back to Monday's incident. The most critical change: the idempotency key must be generated only once when the order is created and saved along with the order—never regenerated on each retry. Once regenerated, every retry looks like a new transaction, and idempotency is completely defeated.
def create_payment(order):
key = order.idempotency_key # UUID v4,创建订单时生成,存入数据库
payload = {
"amount": order.amount,
"currency": order.currency,
"metadata[order_id]": order.id, # 供后续对账使用
}
return send_with_retry(payload, key, order)The retry loop is implemented separately, with every attempt using the same key:
def send_with_retry(payload, key, order):
for attempt in range(6):
try:
r = requests.post(PAYMENTS_URL, data=payload,
headers={"Idempotency-Key": key}, timeout=10)
except (requests.ConnectionError, requests.Timeout):
time.sleep(2 ** attempt) # 用同一个键重试
continue
if r.status_code == 429:
time.sleep(retry_after(r, attempt))
continue
if r.status_code >= 500:
mark_indeterminate(order) # 等待 Webhook/对账
return None
return r
mark_indeterminate(order)
return NoneThe 429 branch is worth noting. Rate limiting is a daily reality of integration work; according to MDN, a 429 response may include a Retry-After header telling you how long to wait before sending a new request. If the server gives you a number, wait accordingly—don't guess:
def retry_after(r, attempt):
wait = r.headers.get("Retry-After")
return int(wait) if wait and wait.isdigit() else 2 ** attemptThe 500 branch does not retry blindly. The order is marked as "outcome uncertain," and the truth arrives from another direction: the webhook, plus the
order_id
metadata that maps the transaction to the order. This is also Stripe's recommended approach: reconcile via webhooks and metadata.
Webhooks arrive late, duplicated, and out of order
The reverse direction is harder, because you don't control when others call you. Stripe explicitly states that endpoints occasionally receive the same event multiple times, and events may arrive out of order. Crossmint's documentation says its webhooks guarantee "at least once" delivery, which means receivers must be idempotent.
A good handler does four things in order.
@app.post("/webhooks/payments")
def receive():
raw = request.get_data() # 原始请求体,不做解析
sig = request.headers.get("Stripe-Signature")
try:
event = stripe.Webhook.construct_event(raw, sig, WEBHOOK_SECRET)
except Exception:
return "", 400 # 签名无效或已过期
if not processed_events.insert_if_absent(event["id"]):
return "", 200 # 已处理过:跳过
queue.enqueue(handle_event, event["id"])
return "", 200 # 立即返回 2xxThe first step is getting the raw request body. Stripe signs every webhook with HMAC-SHA256 via the
Stripe-Signature
header, and verification requires the raw request body, byte for byte. If your framework has already parsed and re-serialized it, even a single changed space will break the signature, and you'll waste half a day doubting the secret key.
The signature also includes a timestamp to guard against replay attacks. Stripe's libraries allow the timestamp to differ from the current time by at most 5 minutes by default. In practice, if the customer's server clock drifts enough, all webhooks will be rejected even with a perfectly correct secret.
Next, deduplicate by event ID, then return 2xx before doing any heavy work. Stripe recommends processing events through an asynchronous queue to absorb traffic spikes. In the worker, don't assume the "paid" event always arrives after the "created" event. The safer approach is to read the object's current state first, then update the order.
Every provider's guarantees differ—read carefully
This is where an FDE earns trust: reading each provider's documentation thoroughly and figuring out who is responsible for resending when your system goes down.
| Stripe | GitHub | |
|---|---|---|
| Response deadline | Return 2xx before running heavy logic | Must return 2XX within 10 seconds |
| On delivery failure | Automatic redelivery for up to three days in Live mode, with exponential backoff | Does not automatically redeliver |
| What you must do after downtime | Handle a flood of backlogged old events arriving all at once | Redeliver missed webhooks yourself once the server recovers |
This difference shapes the architecture. With Stripe, two hours of downtime usually self-heals, provided your handler can absorb the incoming events. With GitHub, without a redelivery script or process, missed data is lost forever, and the runbook handed to the customer's ops team must spell out this step clearly.
Recurring mistakes
The most common is generating a new idempotency key inside the retry loop, rendering the protection useless. Close behind is reusing an old key with changed parameters—say, correcting the amount—and then being surprised by the error. Changed parameters mean a new operation, and a new operation needs a new key.
The second is treating a 500 as "definitely failed" and recreating the transaction with a different key. The third is stuffing all business logic into the webhook handler: writing to the database, calling the ERP, sending emails. One slow ERP response causes a timeout, the provider marks the delivery as failed, and the resend loop begins.
The last one gets little attention: no reconciliation mechanism. No matter how good the code is, you need a scheduled job that compares states on both sides via metadata, because sooner or later an event will slip through.
Putting this skill on your resume
When reading job descriptions for FDE or Solutions Engineer roles, watch for terms like "integrations," "webhooks," "customer systems," and "data pipelines." When you see them, have a story ready about idempotency and webhooks that proves you've handled real incidents, not just called APIs.
So don't write "integrated Stripe"—be specific: introduced idempotency keys and webhook-based reconciliation to eliminate duplicate transactions; migrated the webhook handler to queue-based processing with deduplication by event ID. If it comes up in an interview, explain the incident, the cause, and how you proved it wouldn't happen again.
This week's exercise: take an integration you have running, unplug the network cable halfway through a POST, then resend the same Webhook three times. If the data is still correct after both tests, you've completed the part of the work customers never see—and it's exactly that part that determines whether customers trust you.
Was this article helpful?
Thanks for your feedback!