ChatGPT Prompt to Write a Webhook Handler That Survives Retries

When a webhook fails, both of Paper Pigeon Prints’ carriers retry it up to eleven times over six hours. The shop ships 700 orders a day, and last March one carrier outage produced 4,100 duplicate “label printed” events, 612 reprints, and 6.40 dollars of wasted label stock per reprint before anyone noticed the pattern on the third day.

The handler that caused it was forty lines long and looked reasonable: parse the JSON, look up the order, update the status, return 200. What it lacked was a reason not to do that work twice. The prompt below asks for the properties that make a handler safe under retry, in the order they matter.

What the Eleven Retries Exposed

Paper Pigeon’s integration with the two carriers is deliberately boring: an HTTP endpoint receives status events for labels, pickups, in-transit scans, and deliveries, then writes to Postgres and queues a customer email. The failure was not in any single line.

  • No event identity. The handler keyed on order number, so two different events for the same order overwrote each other in the wrong order.
  • Signature check after parsing. The handler parsed the body, then verified the HMAC against a re-serialised object, which failed intermittently and, worse, was skipped in one branch.
  • Slow acknowledgement. The handler called the carrier’s label API synchronously. When that call took 9 seconds, the carrier timed out and retried, and the retry ran concurrently with the first attempt.
  • Downgrade writes. A late “in transit” event arriving after “delivered” reset the order to in transit, which triggered a second shipping-notification email.
  • No dead letter path. Events that threw were logged and dropped. Nobody could replay them after the fix shipped.

Each of those is a known pattern with a known fix. The value of the prompt is that it asks for all five in one pass, in a structure you can hand to a reviewer.

The Handler Prompt

Use this as a single message. It is written for a TypeScript service but the constraints transfer to Python or Go with the syntax changed in one line.

You are a senior backend engineer writing a production webhook receiver. Optimise
for correctness under duplicate and out-of-order delivery. Do not write a tutorial;
write code I can review.

Stack:
- TypeScript on Node 20, Fastify, PostgreSQL 15, Redis 7 for short-lived locks.
- Deployment: two containers behind a load balancer, no sticky sessions.
- Existing tables: orders(id, carrier, tracking_number, status, updated_at),
  shipments(order_id, label_url, created_at).

Traffic:
- Two carriers, roughly 700 orders a day, peak 40 events per minute.
- Carrier A retries up to 11 times over 6 hours with exponential backoff.
- Carrier B retries 5 times over 30 minutes and may deliver out of order.
- Carrier signatures: A uses HMAC-SHA256 over the raw body in header
  X-PP-Signature with a per-environment secret. B uses a timestamp plus HMAC in
  a single header of the form t=...,v1=....

Deliver:
1. Route definition that captures the raw request body without JSON parsing
   before verification, and rejects bodies over 64 KB.
2. Signature verification for both carriers as separate functions. Use a
   constant-time comparison. Reject timestamps older than 5 minutes for B.
   Return 401 without logging the secret or the full signature.
3. Idempotency. A webhook_events table with a unique constraint on
   (carrier, event_id) and columns for received_at, processed_at, attempts,
   and payload jsonb. Show the DDL, then the insert-or-ignore pattern that
   returns whether this delivery is the first one.
4. Fast acknowledgement. Persist the event and return 200 in under 300 ms.
   Do all side effects in a separate worker that claims rows with
   SELECT ... FOR UPDATE SKIP LOCKED.
5. Out-of-order protection. A status rank table so a lower-ranked event can
   never overwrite a higher-ranked one. Show the comparison and the SQL guard.
6. Retry and failure handling. Bounded attempts with backoff, a dead-letter
   state, and a replay function that takes a time range and a carrier.
7. Observability. Three counters and two log lines that would have caught the
   duplicate-label incident on day one, not day three.
8. Tests. Table-driven cases for: duplicate event, out-of-order event, bad
   signature, expired timestamp, body over the limit, and a carrier timeout
   during processing.

Rules:
- No side effect may happen before the idempotency insert commits.
- Never trust the event's own status field without comparing ranks.
- Every external call needs a timeout and a bounded retry.
- Comment only where a reader would otherwise assume the wrong thing.
- If a requirement conflicts with another, say which one you broke and why.

The ordering constraint is the load-bearing line. “No side effect before the idempotency insert commits” is what turns a retry storm into a no-op. Everything else in the prompt is defence in depth around that one rule.

Values You Must Fill In

The prompt is specific enough to run as written, but six values decide whether the output matches your integration.

  • Stack and version. Node 20 with Fastify assumes raw-body access through a content-type parser hook. On Express you need express.raw on that route; on Python you need the raw bytes before any framework parsing.
  • Carrier signatures. The two schemes above are the common shapes. If one carrier signs a canonical string rather than the raw body, say so, because re-serialising JSON to verify is the bug that produces intermittent 401s.
  • Event volume and retry schedule. 700 orders and 11 retries set the size of the dedupe window. At 7,000 orders a day you keep 30 days of events, not 7.
  • Status vocabulary. List your actual statuses in order. The rank table is only as good as the ordering you declare, and “exception” needs an explicit position.
  • Side effects. Name them: label purchase, customer email, warehouse picklist, accounting entry. Each one needs its own idempotency story, because a database row is easy to dedupe and an email is not.
  • Retention and privacy. The payload column holds addresses and phone numbers. Set a retention period and say whether payloads are redacted before storage.

What the Response Should Contain

A good return for Paper Pigeon is roughly 250 lines across five files, plus a migration and a test file. Judge it on these six points rather than on whether it compiles.

  • The raw body path is explicit. You should see a route-level parser that keeps the buffer, and a comment explaining why the global JSON parser is bypassed for that path only.
  • Signature comparison is constant-time. Look for timingSafeEqual or an equivalent, with a length check before it. A plain string comparison here is a finding, not a style preference.
  • The idempotency insert is one statement. ON CONFLICT DO NOTHING RETURNING id, and a branch on whether a row came back. Two statements (select then insert) will race under the two-container deployment.
  • Acknowledgement is decoupled. The route writes and returns; the worker does the label call. If you see an await on the carrier API inside the route handler, the timeout problem is still there.
  • The rank guard is in SQL, not in application code. An UPDATE with a WHERE clause on rank is atomic; a read, compare, write in TypeScript is not.
  • Replay is a function, not a runbook step. It should take a carrier and a time range, reset the rows to pending, and log how many it moved.

Ask for the diff against your current handler rather than a fresh file if you already have one in production. The model is better at patching a known shape than at guessing your conventions, and the review is faster when the change is small enough to read in one sitting.

Three Extensions That Earn Their Keep

Once the base handler is merged, three additions cover the failures that survive it. The contract block below is the one to write first, because it is what makes the test suite possible.

Write the event contract for both carriers as a single TypeScript discriminated
union, and a validator for each variant.

For every event type include: carrier, event_id, occurred_at, order_id,
tracking_number, status, and a normalised rank.

Then produce a fixture file with one valid and one malformed example per event
type, and a test that asserts the validator rejects the malformed one with a
specific error code rather than a generic parse failure.
  • Replay drills. Once a month, replay a two-hour window from the previous week into a staging handler and confirm the resulting order states match production. This catches rank-table mistakes that unit tests miss because the fixtures are too clean.
  • A dedupe dashboard. Chart accepted events against unique event ids per carrier per hour. A ratio above 1.3 means a carrier is retrying more than its documentation claims, which is usually the first sign of an endpoint that is too slow.
  • Signed replay requests. If you expose the replay function over HTTP, sign the request and cap the window at 24 hours. An unauthenticated replay endpoint is a way to send 4,000 customer emails by accident.

For the failure paths specifically, the contrast in our error handling prompt comparison is worth reading before you accept the generated retry logic, since the default suggestion is often a retry that duplicates the write it was meant to protect. The review checklist in our code review prompts covers the constant-time comparison and the transaction boundary, and the fixture approach in our unit test prompt guide is what makes the six required cases cheap to write.

Sources & Notes

Paper Pigeon Prints, its two carriers, the 700 daily orders, and the March incident are illustrative. The pattern described here (persist, acknowledge, process asynchronously, guard with a monotonic rank, dead-letter and replay) is a standard webhook ingestion design, not a novel one. Reviewed on 2026-11-02. Carrier retry schedules and signature formats change without notice, so verify both against current carrier documentation before you ship, and load-test the endpoint at three times your peak before the first promotion.

声明:1.本站所有文章,如无特殊说明或标注,均为本站原创发布。本网站中【文本生成/文生图】使用了DeeSseek人工智能生成内容技术, 算法来源说明:本网站未自行开发、训练或部署深度合成算法,所使用的人工智能算法来自:DeepSeek、Chatgpt、Google Gemini。 2.为了网站加载速度优化,本站预览图片进行压缩处理,所以有些不是太清晰,并不影响AI提示词生图、AI设计等内容。3.任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。--GUUNN.COM