A robust design treats every webhook as a change notification, then queries the source system for the current true state.

Key Takeaways

  • Both Stripe and Shopify explicitly state that they do not guarantee ordering and may deliver duplicates. Stripe retries for up to three days; according to Hookdeck, Shopify retries 8 times within 4 hours.
  • A handler that writes the payload directly into the database is betting on arrival order. Instead, query the source again, or compare trustworthy timestamps.
  • Deduplicate by ID, process asynchronously, and reconcile periodically. Miss any one of these layers, and your data will gradually drift.

There is a line in Stripe's webhook documentation that many integration teams skim right past: Stripe does not guarantee that events are delivered in the order they were generated. Shopify puts it even more bluntly: ordering is not guaranteed within a topic, nor across topics for the same resource.

In the field, that line turns into very specific tickets. A user has already canceled their plan, but the system still shows "active". An order has been updated, but the dashboard still shows the old status. Manually fixing the data doesn't solve the problem, because the bug lies in how webhooks are received.

The problem a Forward Deployed Engineer (FDE) faces is clear: the customer's system keeps sending you events, and you must maintain an accurate copy of the state. The design below can withstand the four scenarios the providers' own documentation warns about: events out of order, duplicated, arriving late, and never arriving at all.

The Providers Warned You Long Ago

Out-of-order delivery doesn't only happen between events far apart in time. Smartcar's documentation explains that events are delivered concurrently, so two events just milliseconds apart can arrive reversed.

Duplicate delivery is also in the documentation. Stripe says endpoints occasionally receive the same event multiple times and recommends logging processed event IDs. Shopify requires handling to be idempotent — receiving the same webhook twice must produce only one result.

Delayed delivery has concrete numbers. In live mode, Stripe retries delivery with exponential backoff for up to three days. According to Hookdeck, Shopify retries 8 times within 4 hours, while typical retry windows may be 1 to 3 days. So events arriving days late are the norm, not a rare accident.

Lost events must also be considered up front. GitHub recommends that after your server recovers, you redeliver the missed deliveries yourself. Written as

status = event.data.status

a save-and-process handler is betting that events arrive in order; with so many warnings up front, it will lose sooner or later.

Webhooks Are Just Notifications — the Truth Lives in the Source System

The core idea is simple: an event should be understood as "object X just changed". X's current state lives in the source system, not in the payload.

Stripe points exactly in this direction: when events are out of order, re-fetch the object via the API. Take it one step further — have every incoming event trigger a read of the latest state, and arrival order no longer matters.

If you can't call the API again, say due to rate limits, you need a trustworthy point in time to decide which version is newer.

Smartcar recommends only accepting data newer than the stored state, and Sent also recommends using timestamps to keep state correct. But you must pick the right timestamp: Stripe warns against using the

created

field to determine ordering, or to determine whether an event has been processed.

Worked Example: A SaaS Customer Using Stripe

Consider a hypothetical scenario. The customer wants a

subscriptions

table in the database to toggle features for users. A user upgrades and then cancels within the same second, producing a subscription update event and a subscription deletion event.

The deletion event arrives first, the update event second. A naive handler writes

canceled

first, then overwrites it with

active

— the user canceled but still has access. Re-sorting by

created

is exactly what Stripe tells you not to do. The design below fixes this bug:

# 1) 端点:校验、写入收件箱、立即返回 2xx
@app.post("/webhooks/stripe")
def receive(request):
    event = verify_signature(request)  # 签名无效则拒绝
    db.execute(
        "INSERT INTO webhook_inbox (event_id, type, object_id, raw) "
        "VALUES (%s, %s, %s, %s) ON CONFLICT (event_id) DO NOTHING",
        (event.id, event.type, event.data.object.id, request.body),
    )
    queue.enqueue("process_event", event.id)
    return 200

# 2) Worker:去重、回源查询、覆盖写入状态
def process_event(event_id):
    with db.transaction():  # FOR UPDATE 只在事务内持有锁
        row = db.fetch_one(
            "SELECT * FROM webhook_inbox WHERE event_id = %s FOR UPDATE",
            event_id)
        if row.processed_at:
            return  # 已处理过
        sub = stripe.Subscription.retrieve(row.object_id)  # 当前状态
        upsert_subscription(sub.id, sub.status)
        db.execute(
            "UPDATE webhook_inbox SET processed_at = now() WHERE event_id = %s",
            event_id)

Run the scenario again. The deletion event arrives; the worker reads the subscription back via the API and writes the canceled state. Then the update event arrives; the worker reads from the API again and gets the same state. If Stripe delivers the update event twice, the

ON CONFLICT DO NOTHING

and

processed_at

columns will block it.

The transaction in the worker is not decoration. Without a transaction, the

FOR UPDATE

lock is released immediately after

SELECT

, and when two workers pick up the same event, both may see

processed_at

as empty.

There's a reason endpoints stay lean. Stripe requires returning a 2xx quickly before running any complex logic that could cause a timeout, and recommends processing events via an asynchronous queue. GitHub sets a 10-second limit; exceeding it counts as a failed delivery. For Shopify, Hookdeck recommends returning a 2xx within 5 seconds and doing the actual work in a background job.

If you'd rather not call the API again and instead write the payload directly, let the database reject stale versions itself:

INSERT INTO orders (id, data, last_changed_at)
VALUES ($1, $2, $3)
ON CONFLICT (id) DO UPDATE
SET data = EXCLUDED.data, last_changed_at = EXCLUDED.last_changed_at
WHERE orders.last_changed_at < EXCLUDED.last_changed_at;
$3

is the change time the provider sends with the event, not the time your server received it. A redelivery arriving hours late carries a timestamp older than what's stored, so

UPDATE

won't take effect. A duplicate delivery carries a timestamp identical to what's stored, so the

<

comparison skips it too.

The Reconciliation Job Is the Last Line of Defense

The two layers above solve ordering and duplication, but they can't recover events that were lost. Every retry window eventually ends, and they differ across providers: Stripe is three days, Smartcar only 3 attempts, Sent about 2.6 hours. GitHub recommends redelivering missed deliveries yourself, which means this gap is your responsibility.

The most reliable approach is to run a reconciliation job periodically, pulling from the source API the objects that have changed since the last run's checkpoint. How you pull depends entirely on the provider's API: some support filtering by update time, some don't. When filtering isn't supported, fall back to rescanning active objects at a lower frequency.

However you pull, the most critical detail is: the reconciliation job must write through the same upsert function as the webhook worker. On the Stripe path, both fetch the state from the source API before writing, so writing the same state any number of times yields the same result.

On the direct-payload path, both go through the same

ON CONFLICT ... WHERE

statement above, so an older version can never overwrite stored data.

The Working Order in the Field

Start with requirements discovery. Ask the customer: which events does the source system emit, does the documentation guarantee ordering, how long do retries last, is there an API to read back the current state, and can that API filter objects by change time.

"If this event arrives three days late, what breaks in the business?" This question often surfaces requirements that never made it into the spec.

Next, build the inbox and the queue, pick the deduplication key, then pick how to write state (call the API again or compare timestamps). The reconciliation job comes last. Before delivery, do a replay with real events shuffled and a few duplicates mixed in, then compare the resulting table against the source API.

Keep the results of that replay in your portfolio. Rather than writing "integrated Stripe" on your resume, write that you designed an idempotent webhook pipeline with periodic reconciliation, and attach the deviation from the source API before and after the fix. When an FDE job description mentions "integrations" or "event-driven", bring this scenario into the system design interview.

Mistakes That Will Still Corrupt Your Data

The most common mistake is sorting by Stripe's

created

, which Stripe explicitly warns against. The second mistake is assuming that deduplicating by per-delivery ID is enough.

Shopify distinguishes between two headers:

X-Shopify-Webhook-Id

is used to deduplicate a single delivery,

X-Shopify-Event-Id

is used to group multiple deliveries generated by the same merchant action. An inbox keyed only by delivery ID will miss multiple deliveries from the same action.

The design above still stays correct thanks to the idempotent write layer. But if the handler does something that cannot be repeated, such as sending an email or awarding points, you need to record a key for that specific action before executing it: on Shopify use

X-Shopify-Event-Id

, and on Stripe use the event ID that Stripe itself recommends tracking.

Do not key by object ID, because all subsequent legitimate updates to the same object share that key and would be wrongly blocked.

The last mistake is processing synchronously within the request. If processing exceeds the timeout, the provider considers the request failed and retries. And as Hookdeck points out, retries themselves carry the risk of duplicate deliveries, so precisely when your system is overloaded, you receive more duplicate events.

Every integration looks beautiful in a demo, because demos don't include three days of retries. What customers remember is the table that stayed correct during a week when all events were in chaos.

Was this article helpful?

Thanks for your feedback!

Next on the roadmap · Phase 2: Full-stack engineering capability The customer portal has no API docs? Record a HAR file first Record a working workflow, generate an OpenAPI spec from it, and write replay tests, provided the session cookies in the file never leak.