FDE Times dataFDE jobs open 928▲21 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 85Companies hiring 200Remote-friendly 24%Median US pay $200kTop hirer Databricks 107
中文VI

The newspaper of the Forward Deployed Engineer

Guides

Webhooks arrive late and out of order. Your data still has to be right

The safe design treats every webhook as a notice that something changed, then asks the source system what the current state actually is.

ShareLinkedInFacebookX

In brief

  • Stripe and Shopify both say they don't guarantee order and may deliver duplicates. Stripe retries for up to three days; according to Hookdeck, Shopify retries 8 times over 4 hours.
  • A handler that copies the payload straight into the database is betting on arrival order. Ask the source again, or compare a trustworthy timestamp.
  • Deduplicate by ID, process asynchronously and run a periodic reconciliation job. Skip any one of these layers and the data will drift.
Webhook flow diagram: the Stripe API sends an event to the Endpoint, which returns 2xx immediately. The event moves on to an Inbox keyed by event_id, then to the Worker, the block highlighted in orange. The Worker queries the Stripe API again for the current state, then writes to the subscriptions table. A reconciliation job also writes to this table, through the same upsert function.
Whatever event arrives, the worker re-reads the latest state from Stripe before writing, so out-of-order events cannot corrupt the data. The reconciliation job writes through the same upsert function to make up for lost events.

Stripe’s webhook documentation contains a sentence many integration teams skim past: Stripe does not guarantee that events are delivered in the order they were generated. Shopify is blunter still. It guarantees no ordering within a single topic, and none across different topics for the same resource.

At a client site, that sentence turns into very concrete tickets. A user has cancelled a plan but the system still shows “active”. An order has been updated but the dashboard shows the old status. Fixing rows by hand solves nothing, because the bug lives in how webhooks are received.

The FDE’s problem is clear enough: the client’s system fires events at you, and you must keep an accurate copy of its state. The design below survives four things the providers’ own documentation warns about: events that arrive out of order, arrive twice, arrive late, and never arrive.

The providers have already warned you

Out-of-order delivery is not limited to events far apart in time. Smartcar’s documentation explains that events are delivered concurrently, so two events a few milliseconds apart can still arrive reversed.

Duplicates are documented too. Stripe says an endpoint may occasionally receive the same event more than once, and advises logging the event IDs already processed. Shopify requires idempotent processing, so that receiving the same webhook twice still produces exactly one result.

Late delivery comes with numbers. In live mode, Stripe retries delivery for up to three days with exponential backoff. According to Hookdeck, Shopify retries 8 times over 4 hours, and retry windows in general can run from 1 to 3 days. An event arriving several days late is therefore routine, not a rare incident.

Lost events also have to be planned for. GitHub advises that once your server is back up, you redeliver the deliveries you missed yourself. A handler written as status = event.data.status followed by a save is betting that events arrive in order, and with this many warnings it will lose that bet sooner or later.

A webhook is a notice; the truth lives at the source

The core idea is simple. An event should be read as “object X just changed”. The current state of X lives in the source system, not in the payload.

Stripe points in this direction: when events arrive out of order, fetch the object again through the API. Go one step further, so that every incoming event triggers a read of the latest state, and arrival order stops mattering.

When calling the API again is not possible, say because of rate limits, you need a trustworthy point in time to tell which version is newer.

Smartcar advises accepting only data newer than the state you have stored, and Sent recommends using timestamps to keep state correct. But the right timestamp matters: Stripe warns against using the created field to determine ordering or to tell whether an event has already been processed.

A worked example: a SaaS client on Stripe

Take a hypothetical case. The client wants a subscriptions table in its database to switch features on and off for users. A user upgrades and then cancels within the same second, generating a subscription update event and a subscription deletion event.

The deletion arrives first, the update second. A naive handler writes canceled, then overwrites it with active, and the user keeps access despite cancelling. Re-sorting by created is precisely what Stripe says not to do. The following design fixes the bug:

# 1) Endpoint: verify, write to the inbox, return 2xx immediately
@app.post("/webhooks/stripe")
def receive(request):
    event = verify_signature(request)  # reject if the signature is invalid
    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: deduplicate, ask the source again, overwrite the state
def process_event(event_id):
    with db.transaction():  # FOR UPDATE only holds the lock inside a transaction
        row = db.fetch_one(
            "SELECT * FROM webhook_inbox WHERE event_id = %s FOR UPDATE",
            event_id)
        if row.processed_at:
            return  # already processed
        sub = stripe.Subscription.retrieve(row.object_id)  # current state
        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 from the API and writes the cancelled state. The update event arrives afterwards, the worker reads from the API again and gets the same state. If Stripe delivers the update event twice, ON CONFLICT DO NOTHING and the processed_at column stop it.

The transaction in the worker is not decoration. Without it, the FOR UPDATE lock is released straight after the SELECT, and two workers picking up the same event could both see processed_at as empty.

The endpoint is kept thin for a reason. Stripe asks for a fast 2xx before any complex logic that could cause a timeout, and recommends processing events through an asynchronous queue. GitHub sets a 10-second limit, after which the delivery counts as failed. For Shopify, Hookdeck recommends returning 2xx within 5 seconds and doing the work in a background job.

If you would rather write the payload directly without calling the API again, 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 the stored one, so the UPDATE does nothing. A duplicate carries exactly the stored timestamp, and the < comparison skips it as well.

The reconciliation job is the last safety net

The two layers above handle ordering and duplicates, but they cannot rescue an event that was lost. Every retry window ends eventually, and each provider’s is different: three days for Stripe, only 3 attempts for Smartcar, about 2.6 hours for Sent. GitHub’s advice to redeliver missed deliveries yourself makes clear that the gap is your responsibility.

The most reliable approach is a periodic reconciliation job that pulls from the source API the objects changed since the previous run’s checkpoint. How you pull depends entirely on the provider’s API: some let you filter by update time, some do not. Where filtering is not available, the fallback is to rescan active objects on a sparser schedule.

However you pull, the most important detail is that the job writes through the same upsert function the webhook worker uses. On the Stripe path, both fetch state from the source API before writing, and writing the same state any number of times gives one result.

On the direct-payload path, both go through the same ON CONFLICT ... WHERE statement above, so an old version can never overwrite the stored one.

The order of work at a client site

Start with discovery. Ask the client which events the source system emits, whether its documentation guarantees ordering, how long retries last, whether there is an API to read back current state, and whether that API can filter objects by change time.

The question “if this event arrives three days late, what breaks in the business?” often surfaces requirements the spec never wrote down.

Then build the inbox and queue, choose the deduplication key, and choose how to write state (calling the API again or comparing timestamps). The reconciliation job comes last. Before handover, replay real events in shuffled order, with a few duplicates, and compare the resulting table against the source API.

Keep the results of that replay for your portfolio. Instead of “integrated Stripe”, a CV should say you designed an idempotent webhook pipeline with periodic reconciliation, with the drift from the source API before and after. When an FDE job posting mentions “integrations” or “event-driven”, this is the scenario to bring into the design round.

The mistakes that still leave data wrong

The most common mistake is ordering by Stripe’s created, exactly what Stripe warns against. The second is believing that deduplicating by the ID of each individual delivery is enough.

Shopify distinguishes two headers: X-Shopify-Webhook-Id to deduplicate individual deliveries, and X-Shopify-Event-Id to group the deliveries generated by the same merchant action. An inbox keyed only on the delivery ID lets through multiple deliveries from the same action.

The design above stays correct thanks to the idempotent write layer. But if a handler does something that cannot be repeated, such as sending an email or awarding loyalty points, record the key for that specific action before performing it: X-Shopify-Event-Id on Shopify, and on Stripe the event ID that Stripe already advises tracking.

Do not key on the object ID, because every later legitimate update to the same object shares that key and gets wrongly blocked.

The last mistake is processing synchronously inside the request. When processing runs past the deadline, the provider treats the request as failed and retries. And retries, as Hookdeck notes, carry their own risk of duplicate delivery, so you receive extra duplicates just as the system is overloaded.

Every integration looks good in a demo, because demos have no three-day retries. Clients remember you for the table that stayed correct in the week everything arrived in a jumble.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
8 sources
Read next on the roadmap · Stage 2: Broad engineeringNo API docs for the client's portal? A HAR file is your first specRecord one workflow, build an OpenAPI spec from it and write replay tests, provided the session cookies inside the file never leave your hands.