PRACTICAL FIELD GUIDE

Webhook ordering: why events arrive out of order and how to handle it

Webhooks do not guarantee arrival ordering, so the last notification received may not describe the latest record state. Decide whether the consumer should apply events or fetch current state.

MCPBackend editorial team · · Examples are illustrative

The short answer

Almost no webhook system guarantees delivery order, and MCPBackend does not either. Two changes made a few milliseconds apart are sent by independent requests, travel over different connections and can reach your endpoint in either order. If your handler applies whatever arrives last, an older payload can overwrite newer data. The fix is to make your handler order-independent: either treat the webhook as a signal and re-read the current row, or store a version with each row and ignore any event older than what you already have.

Duplicates are the same problem from the other side. A replayed or re-sent event is just an old event arriving late, so the handler that survives reordering (verify, dedupe on the event id, apply current state) also survives duplicates.

When webhook ordering actually matters

  • It matters when the handler copies payload data somewhere: a search index, a CRM, a cache, a second database. An older payload applied last leaves stale data behind.
  • It matters for state machines, such as order status paid then shipped, or subscription active then canceled, where applying steps backwards breaks a rule.
  • It barely matters for one-off side effects keyed to a single event, such as sending a receipt email on orders.created. Deduplication matters more there.
  • It does not matter if the handler only uses the event as a signal and always re-reads the current row before acting.

What out-of-order delivery looks like

Each write request fires its own webhooks after the response is sent. The second write can finish first, its delivery can take a faster path, or the first delivery can be slow to connect. Nothing in the pipeline puts them back in order.

Your app             MCPBackend API              Your endpoint
  |                        |                            |
  |-- PATCH status=paid -->|                            |
  |-- PATCH status=shipped>|                            |
  |                        |-- orders.updated shipped ->|  arrives 1st
  |                        |-- orders.updated paid ---->|  arrives 2nd
  |                        |                            |
  Naive handler:   applies the last event   -> row says "paid"     (wrong)
  Re-read handler: GET /db/orders/42        -> row says "shipped"  (right)

How MCPBackend sends webhooks

  • One HTTPS POST per matching webhook per write, sent after the API response, with a 5-second timeout.
  • One attempt only: no retries and no queue. A delivery that fails or times out is not resent.
  • Payload: id (evt_…), event such as orders.updated, table, operation, projectId, occurredAt and data.
  • data is the full row after the write for created and updated, and only the primary key for deleted.
  • occurredAt is stamped when delivery starts, not when the row was committed, so it is close to but not exactly the write time. Two near-simultaneous writes can carry timestamps in either order.
  • Headers: x-mcpbackend-event, x-mcpbackend-delivery (the same evt_ id) and x-mcpbackend-signature (sha256 HMAC of the raw body).
  • When one write matches several webhooks, they are sent one after another, so a slow endpoint (up to the 5-second timeout) delays the deliveries queued behind it for that write.
  • A DELETE fires a deleted event once the caller is allowed to delete, even if no row with that ID existed. Treat deletes as idempotent.

Three ways to handle ordering

  • Re-fetch current state (simplest, recommended). Verify the signature, then GET the row by ID with a server-side key and use that. The payload only tells you which row changed. A 404 on re-read means the row was deleted.
  • Compare a version. Add an integer version column that your app increments on every PATCH, or an updated_at your app sets. Store the last version you applied per row and skip any event with a lower or equal version.
  • Serialize per record. Push events into your own queue keyed by row ID and process one at a time, re-reading before each apply. Use this when a downstream system cannot handle concurrent updates.
app.post("/hooks/mcpbackend", async (req, res) => {
  if (!verify(req.rawBody, req.get("x-mcpbackend-signature"), SECRET)) return res.sendStatus(401);
  res.sendStatus(200); // answer inside the 5-second timeout, work afterwards
  const evt = JSON.parse(req.rawBody);
  if (await seen(evt.id)) return; // dedupe on the delivery id
  if (evt.operation === "deleted") return removeLocal(evt.table, evt.data);
  const latest = await api.get(`/db/${evt.table}/${evt.data.id}`); // current state wins
  if (latest.status === 404) return removeLocal(evt.table, evt.data);
  await upsertLocal(evt.table, await latest.json());
});

Plan for missed events too

Ordering is half the problem. Because MCPBackend makes a single delivery attempt, an event lost to a deploy, a cold start or a slow handler is gone. If your copy of the data must be complete, run a periodic reconciliation that lists rows changed since your last sync (filter or sort on a timestamp column your app maintains) and repairs anything the webhooks missed. Treat webhooks as a fast hint, and the data API as the source of truth.

Test your handler with events in reverse order

Don't wait for production to reorder events for you. Sign two fixtures for the same row with your webhook secret and send the newer one first. A correct handler ends with the newer state no matter which arrives last, and sending either fixture a second time changes nothing.

// node test-order.mjs  (point URL at your local or staging handler)
import { createHmac } from "node:crypto";
const URL = "http://localhost:3000/hooks/mcpbackend", SECRET = process.env.WEBHOOK_SECRET;
const evt = (id, status) => ({ id, event: "orders.updated", table: "orders", operation: "updated",
  projectId: "test", occurredAt: new Date().toISOString(), data: { id: "42", status } });
async function send(payload) {
  const body = JSON.stringify(payload);
  const sig = createHmac("sha256", SECRET).update(body).digest("hex");
  const res = await fetch(URL, { method: "POST", body, headers: { "content-type": "application/json",
    "x-mcpbackend-event": payload.event, "x-mcpbackend-delivery": payload.id,
    "x-mcpbackend-signature": `sha256=${sig}` } });
  console.log(payload.id, res.status);
}
await send(evt("evt_2", "shipped")); // newer change arrives first
await send(evt("evt_1", "paid"));    // older change arrives last
await send(evt("evt_1", "paid"));    // duplicate
// Then check: your copy of order 42 must say "shipped".

Put it into practice

  1. Identify whether the downstream task needs historical changes or the latest record.
  2. For current-state synchronization, re-read the API using an authorized server credential.
  3. Test reversed event arrival and avoid overwriting newer state with stale payload data.

What this looks like

ILLUSTRATIVE EXAMPLE

An updated event arrives after a later change was already processed. Fetching current state can prevent the old payload from becoming authoritative.

A boundary to keep clear

An occurredAt field is useful context but does not create an ordering guarantee or a durable history by itself.

MCPBackend context

MCPBackend webhooks currently make one delivery attempt with a five-second timeout and no retry or ordering guarantee. Treat them as change notifications, not a durable event ledger. For workflows that must complete, use a durable processing system you operate and reconcile its state against the data API.

Take the next step

Inspect the current project contract, try the change with disposable data, and verify the result through the same credentials your app will use. Record the expected response and one denied-access case before release.

Frequently asked questions

Do webhooks guarantee delivery order?

Generally no. Most providers do not promise order; Stripe, for example, documents that events can arrive out of order. MCPBackend makes no ordering guarantee either, so handlers should re-read current state or compare versions.

Can I sort webhook events by occurredAt?

Only as a rough guide. On MCPBackend occurredAt is set when delivery starts, so near-simultaneous writes can carry timestamps in either order. Use a version column your app controls, or re-fetch the row.

Does MCPBackend retry failed webhooks?

No. Each webhook gets one attempt with a five-second timeout. Respond with a 2xx quickly, do the work asynchronously, and reconcile periodically against the data API.

How do I make a webhook handler idempotent?

Store each processed delivery ID (the evt_ id in the body and the x-mcpbackend-delivery header) and skip repeats, and make the apply step an upsert of current state rather than an increment.

What are the best practices for webhooks in an MCP-built app?

Verify the HMAC signature on the raw body, answer 2xx within five seconds and do the work afterwards, dedupe on the evt_ id, re-read current state instead of trusting payload order, and run a periodic reconciliation against the data API because MCPBackend does not retry. Create the webhook with the create_webhook MCP tool and test it with signed fixtures before going live.

Are several webhooks on the same table delivered in parallel?

No. For a single write, MCPBackend sends matching webhooks one after another, each with a five-second timeout. Separate writes are delivered independently, which is why their events can arrive in either order.

Sources and further reading

These references explain the underlying protocols and design principles. For supported MCPBackend operations and exact request shapes, inspect your project’s generated API contract.