Webhooks: retries, duplicates and idempotency
Webhooks are delivered "at least once": on failure or timeout, the provider sends the same event again, sometimes hours later. An idempotent endpoint applies each event exactly once, however many times it is delivered.
Why duplicates are normal
If your server answers with an error, doesn't answer in time, or the response gets lost on the network, the provider can't know whether the event was processed. It sends it again. Your code may have applied it the first time: without care, the order is created twice and the email goes out twice.
What providers do
- Stripe automatically retries failed deliveries for up to three days in live mode, with a growing delay between attempts. Every event carries a stable identifier (evt_…), identical across attempts.
- GitHub doesn't automatically redeliver a failed delivery: redelivery is manual ("Redeliver") or through the API. Every delivery carries a unique identifier in the X-GitHub-Delivery header.
- Order is guaranteed nowhere: an "updated" event can arrive before the matching "created" one. Never infer the final state from arrival order.
Making the endpoint idempotent
Store the identifier of every processed event under a uniqueness constraint. On receipt, try the insert: if it succeeds, it's the first delivery, process it; if it's skipped, it's a duplicate, answer 2xx and do nothing. The database arbitrates, even when two deliveries arrive at the same time.
CREATE TABLE webhook_events (
provider text NOT NULL,
event_id text NOT NULL,
received_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (provider, event_id)
);
-- Returns a row only the first time this event is seen
INSERT INTO webhook_events (provider, event_id)
VALUES ($1, $2)
ON CONFLICT DO NOTHING
RETURNING event_id;Answer fast, process later
The slower your response, the more likely the provider treats the delivery as failed and sends it again. Verify the signature, record the event, queue the processing, then answer immediately. A duplicate must also get a 2xx: an error would trigger yet another delivery.
app.post('/webhooks/github', rawBody, async (req, res) => {
if (!verifyGithub(req.body, req.get('X-Hub-Signature-256'), SECRET)) return res.sendStatus(401)
const deliveryId = req.get('X-GitHub-Delivery')
const first = await db.query(INSERT_EVENT, ['github', deliveryId])
if (first.rowCount === 1) await queue.add('github-event', { deliveryId, body: req.body.toString() })
res.sendStatus(202) // answer fast, duplicates included
})Testing duplicates
Capture a real event with a Tracehook URL, then replay the same request several times against your local server. Check three things: every response is a 2xx, the effect is applied once, and two replays started in parallel don't create a duplicate.