Reliable HTTP cron and delayed-job scheduling with automatic retries and full run logs — delay.run

If a webhook handler does its work in the request and relies on "the provider will only send this once", you will eventually double-charge, double-email or double-create a record. Providers retry on timeouts, operators replay from a dashboard, and a deploy can make you accept the same delivery twice. The reliable pattern is an inbox: store the event once, keyed on an ID the provider guarantees, and make that insert the only gate.

This is a small, boring version of that inbox.

What you need from the provider

Almost every mature provider sends a unique event ID (id, event_id, X-Event-Id, a delivery UUID). You also need a signature you can verify, and you should store the raw body, not a parsed dict, so you can re-verify and replay.

If a provider has no event ID, you have to make one: a hash of the body, or a tuple like (subscription_id, invoice_id, event_type) that is unique for the work you will do. That is weaker — two legitimate events could collide if you pick a bad tuple — but it is still better than nothing.

The table

CREATE TABLE webhook_inbox ( provider text NOT NULL, event_id text NOT NULL, event_type text NOT NULL, payload jsonb NOT NULL, raw_body bytea NOT NULL, received_at timestamptz NOT NULL DEFAULT now(), processed_at timestamptz, PRIMARY KEY (provider, event_id) ); 

The primary key is the whole design. A second insert of the same event is a unique-violation, not a second subscription.

The handler

Verify the signature first, then insert, then return 200, then do the work (or enqueue it). The order matters.

import os import hmac import hashlib from flask import Flask, request, jsonify import psycopg app = Flask(__name__) SECRET = os.environ["WEBHOOK_SECRET"] def verify(raw: bytes, signature: str) -> bool: expected = hmac.new(SECRET.encode(), raw, hashlib.sha256).hexdigest() return hmac.compare_digest(expected, signature or "") @app.post("/webhooks/provider") def inbound(): raw = request.get_data() if not verify(raw, request.headers.get("X-Signature", "")): return jsonify(error="invalid signature"), 400 event = request.get_json(force=True) event_id = event["id"] event_type = event["type"] with psycopg.connect(os.environ["DATABASE_URL"]) as conn: with conn.cursor() as cur: cur.execute( """ INSERT INTO webhook_inbox (provider, event_id, event_type, payload, raw_body) VALUES ('provider', %s, %s, %s, %s) ON CONFLICT (provider, event_id) DO NOTHING RETURNING event_id """, (event_id, event_type, event, raw), ) inserted = cur.fetchone() conn.commit() if inserted: # enqueue, or call process(event) if the work is very short process_later(event_id) return jsonify(ok=True), 200 

Points worth keeping:

  • Return 200 for duplicates as well as new events. If you return 500 on a unique-violation, the provider will retry, forever, a delivery you already have. The duplicate is success: you already know about this event.
  • ON CONFLICT DO NOTHING plus RETURNING tells you whether this process is the one that should enqueue work. No RETURNING row means someone else already did.
  • Do not do the slow work in the request if you can help it. A timeout after you inserted but before you finished the side effect is fine, because a later worker will pick up processed_at IS NULL. A timeout before you insert is also fine: the provider retries, you insert then.
  • Verify on the raw bytes, not on a re-serialized JSON object. Adding a space during parse-and-dump will break signatures.

Processing exactly once

A second worker drains the inbox:

def drain(): with psycopg.connect(os.environ["DATABASE_URL"]) as conn: with conn.cursor() as cur: cur.execute( """ SELECT event_id, event_type, payload FROM webhook_inbox WHERE processed_at IS NULL ORDER BY received_at FOR UPDATE SKIP LOCKED LIMIT 20 """ ) rows = cur.fetchall() for event_id, event_type, payload in rows: handle(event_type, payload) cur.execute( "UPDATE webhook_inbox SET processed_at = now() WHERE event_id = %s", (event_id,), ) conn.commit() 

FOR UPDATE SKIP LOCKED lets you run more than one worker without two of them handling the same new event. handle itself still has to be idempotent for the rare case where it succeeds and the processed_at update does not — for example, "create subscription if not exists", not "always insert a subscription".

The inbox gets you 'stored once'; the follow-up work still needs a safe retry if your process dies mid-handle. delay.run is a fit for that second step: one delayed HTTP job per new event_id, retried with backoff, with a run log, while the webhook request itself returns 200 in milliseconds.

What to log and what to alert on

Log every delivery: event ID, type, whether it was inserted or a duplicate, and how long you took to 200. Alert if processed_at IS NULL rows get older than a few minutes, or if the duplicate rate suddenly spikes (a provider bug or a replay). Keep raw bodies long enough to replay after a bad deploy, then expire them so the table does not grow without bound.

The dashboard "replay event" button becomes boring: it hits the same endpoint, the unique key holds, and either a missing processed_at is retried or you have a separate "force reprocess" that you only use on purpose.

Event IDs you should not invent badly

If the provider really has no event ID, hash the raw body and a stable timestamp or delivery header if one exists. Do not hash a parsed-and-reserialized object (key order will bite you). Do not use "the user id plus the event type plus today's date" unless you are certain that provider will only send one of those per day — invoice.updated often fires more than once, and you would drop the later, real change. When in doubt, store the delivery and make the side effect unique (subscriptions unique on provider_subscription_id), even if the inbox might contain two rows for one business event.

Related reading

Do you already key webhooks on the provider's event ID, or are you still trusting "they won't retry if we 200 quickly"?