DEV Community

Zero Heartbeat
Zero Heartbeat

Posted on Edited on Originally published at delta1labs.com

Why stale billing webhooks must not win

Your billing provider sends a webhook when a subscription changes: subscription.updated when a customer upgrades, subscription.canceled when they churn. Your Keyright webhook handler receives it, updates the license, and the customer gets what they paid for. On the happy path.

Off the happy path, webhooks arrive out of order. A customer upgrades from basic to pro and, a moment later, your retry-heavy provider redelivers an earlier event that had timed out. Two events were emitted in one order; the network delivered them in the other. If your handler applies whatever it receives, the older event wins, and a customer who just paid for pro is silently downgraded to basic by an event that was already obsolete when it landed. No error is logged. The next time they sign in, a feature is gone.

The real question

The instinct is to reach for idempotency — "I must be processing the same event twice." Sometimes you are, and that is a real and separate problem. But out-of-order delivery is not duplication. The two events are genuinely different: different ids, different payloads, different intents. Deduplicating by event id does nothing to stop a stale but distinct event overwriting a newer one. These are two concerns that look alike and need different mechanisms:

  • Deduplication answers have I seen this exact event before? — keyed by the provider's event id.
  • Ordering answers is this event newer than the state I already have? — keyed by a monotonic version.

This post is about the second one. The mechanism is small: stamp every inbound event with a version, store that version per license, and apply an event only when its version is strictly greater than what you already stored.

The race, and the gate that settles it

Give each event a monotonic version — the provider's own sequence number or event timestamp — and give each license a event_version column holding the version of the last event you applied to it. Then every write becomes a compare-and-set: apply the event only if incoming > stored.



Event B (the upgrade) is the newer truth. It lands first and sets the license to pro at version 5002. The older event A arrives late carrying version 5001; the gate sees it is not greater than 5002 and discards it, so the paying customer is never downgraded.

The gate is one line of SQL. In Postgres:

UPDATE licenses
SET    edition       = @edition,
       status        = @status,
       event_version = @incoming
WHERE  id = @license_id
  AND  event_version < @incoming;
Enter fullscreen mode Exit fullscreen mode

If event_version is already greater than or equal to @incoming, the WHERE matches no row, the statement updates nothing, and the stale event is a no-op. The comparison and the assignment happen atomically under the row lock, so even two handler instances racing on the same license cannot both win: Postgres serialises them, the newer one updates one row, the older one updates zero.

The handler

The handler's job is to pull the version out of the event and run the conditional update. With Dapper, the rows-affected count tells you exactly what happened:

public async Task HandleAsync(BillingEvent evt, CancellationToken ct)
{
    // The provider's monotonic token for this subscription. Prefer a sequence;
    // fall back to the event timestamp (see caveats) if that is all you get.
    long incoming = evt.SequenceNumber ?? evt.CreatedUnixMs;

    const string Sql = """
        UPDATE licenses
        SET    edition       = @Edition,
               status        = @Status,
               event_version = @Incoming
        WHERE  subscription_id = @SubscriptionId
          AND  event_version   < @Incoming;
        """;

    int affected = await _db.ExecuteAsync(new CommandDefinition(Sql, new
    {
        Edition        = MapPlan(evt.Plan),
        Status         = MapStatus(evt.Status),
        Incoming       = incoming,
        SubscriptionId = evt.SubscriptionId,
    }, cancellationToken: ct));

    if (affected == 0)
        _log.LogInformation(
            "Ignored stale event {EventId} (v{Incoming}) for {Sub}: not newer than stored state",
            evt.Id, incoming, evt.SubscriptionId);
}
Enter fullscreen mode Exit fullscreen mode

An affected of zero is not an error — it is the mechanism working. It means either the event was stale or the row did not exist yet. Log it and return 200 so the provider stops retrying; raising a 500 here just invites another out-of-order redelivery.

If you prefer EF Core, the same guard is a concurrency token. Map event_version as IsConcurrencyToken() and load-set-save; a stale write throws DbUpdateConcurrencyException, which you catch and treat as "already superseded." The raw conditional UPDATE is leaner because it skips the read entirely and never materialises the entity, so it is the better fit for a high-volume webhook endpoint. Both are correct; neither does a read-compare-write in application code, which is the one approach that reintroduces the race.

Choosing the version token

The whole scheme rests on a version that is monotonic per subscription. Where it comes from:

{
  "id": "evt_1Nc8s2",
  "type": "subscription.updated",
  "created": 1766001002,
  "data": { "subscription": "sub_8842", "plan": "pro", "status": "active" }
}
Enter fullscreen mode Exit fullscreen mode

A dedicated per-object sequence number is the gold standard: strictly increasing, never tied. Many providers do not expose one, so the event created timestamp is the usual fallback — workable, with one sharp edge. If two changes to the same subscription happen inside the same clock tick, their timestamps tie, 5001 < 5001 is false, and the gate drops the second one. Second-granularity timestamps make this plausible; millisecond precision makes it rare. Use the finest precision the provider gives, and if the only token is coarse, do not pretend it orders — reconcile instead (below).

Composing with idempotency

Ordering and deduplication are complementary, not alternatives. A redelivered duplicate of event B carries version 5002 again; the gate's strict < already makes re-applying it a no-op, so ordering gives you some dedup for free on the license row. But it does not dedup the side effects — a welcome email, a metering reset — that you only want to fire once. For those, keep a separate processed-events table keyed by the provider event id:

INSERT INTO processed_events (event_id) VALUES (@EventId)
ON CONFLICT (event_id) DO NOTHING;
Enter fullscreen mode Exit fullscreen mode

If that insert affects zero rows, you have seen this exact event before — skip the side effects entirely. Run the dedup check first (same event twice), then the version gate (different events, wrong order). They answer different questions and you want both answered.

When ordering is impossible

Sometimes the provider simply gives you nothing reliable to order by — no sequence, and timestamps too coarse or non-monotonic to trust. Do not invent an ordering you cannot defend. Fall back to reconcile on event: treat the webhook purely as a nudge, ignore its payload, and fetch the authoritative current state straight from the provider's API before you write.

public async Task ReconcileAsync(string subscriptionId, CancellationToken ct)
{
    // The webhook told us "something changed" — go read the truth, don't replay a delta.
    Subscription current = await _billing.GetSubscriptionAsync(subscriptionId, ct);

    await _db.ExecuteAsync(
        "UPDATE licenses SET edition = @Edition, status = @Status WHERE subscription_id = @Sub",
        new { Edition = MapPlan(current.Plan), Status = MapStatus(current.Status), Sub = subscriptionId });
}
Enter fullscreen mode Exit fullscreen mode

Fetch-on-event converges to the right answer no matter what order the webhooks arrive, because you always read the latest state rather than replaying a possibly-stale change. It costs one extra API call per event and depends on the provider's read endpoint being current, but it sidesteps ordering entirely. When you do have a trustworthy version token, the conditional UPDATE is cheaper and avoids the round trip; when you do not, reconcile is the honest choice.

Takeaway

Out-of-order and redelivered webhooks are not an edge case you might hit — they are the documented behaviour of every at-least-once billing integration. A stale subscription.canceled or an obsolete downgrade will eventually land after the event that superseded it, and if your handler writes blindly, a paying customer loses access with nothing in the logs. Stamp each event with a monotonic version, store it per license, and let UPDATE ... WHERE event_version < @incoming decide the winner atomically. Keep deduplication as its own keyed check for side effects. And when the provider hands you no ordering token, stop guessing and refetch. The newest truth should win — never the last packet to arrive.

See the Keyright webhook documentation for the inbound event contract, and the companions on verifying inbound billing webhook signatures and idempotency keys for retry-safe license operations.

Top comments (1)

Collapse
 
krusenas profile image
Karolis •

Refetching on every event, meaning you ignore the event payload and fetch the subscription from the provider's API instead, still doesn't escape ordering. Two events trigger two fetches, and the older fetch's write can land after the newer one, undoing it. The fetched subscription's updated_at needs a guard in the WHERE clause too. fwiw I built Webhook Relay, and its retries are exactly why stale events can arrive late, so the guard still matters.