Every payment and exchange integration I have been asked to repair had the same
three-line bug somewhere in it:
app.post("/webhook", (req, res) => {
verify(req.body); // after parsing, sometimes after writing
db.save(req.body); // no idempotency key
res.send("ok");
});
It works in staging, where every request arrives once. In production the provider
retries, your load balancer retries, and a user double-taps. You find out three weeks
later when someone's balance is wrong and nobody can say by how much.
Here is the shape that actually holds up, in the order the checks have to happen.
1. Verify the signature over the raw bytes
Not over JSON.parse output, not over a re-serialised object. JSON.stringify(JSON.parse(body))
looks identical to a human and is not byte-identical to a computer: whitespace, unicode
escapes and number formatting all move. That is the entire reason "signature mismatch in
production only" exists as a class of bug.
In Node, keep the raw body:
app.use("/webhook", express.raw({ type: "*/*" }));
Then hash timestamp + "." + rawBody with HMAC-SHA256 and compare with
crypto.timingSafeEqual. Compare lengths first, because timingSafeEqual throws on
mismatched lengths and a throw inside a webhook handler is a 500 the provider will retry
forever.
2. Reject old timestamps inside a bounded window
A signature proves who sent it, never when. Without a freshness check, a captured
request is valid forever. Take the signed timestamp and reject anything outside ±300
seconds of your clock.
Two details that bite:
- Accept both seconds and milliseconds, because providers disagree and you will not win that argument.
- Compare with
Math.abs, notnow - ts > 300000. The second form happily accepts a timestamp in the year 2099.
3. Claim the event id before you touch a balance
This is the part people skip. Verification and idempotency are different problems, and
checking "have I seen this?" after the write does nothing at all.
The order is:
- Extract a stable event id from the body.
-
INSERT ... ON CONFLICT DO NOTHING(or RedisSET NX PX) to claim it. - Only the winner runs the side effect.
- On failure, release the claim so the provider's retry can work.
INSERT INTO processed_events (event_id, status, received_at)
VALUES ($1, 'processing', now())
ON CONFLICT (event_id) DO NOTHING
RETURNING event_id;
-- zero rows returned => duplicate, return 200 and do nothing
Return 200 for duplicates. A 409 makes the provider retry with backoff, which turns a
harmless duplicate into a retry storm.
4. Release on failure, do not swallow
If the handler throws, delete the claim. Otherwise a transient database error permanently
marks a legitimate event as processed and the money never lands. That failure is silent,
which is the worst kind.
5. Log the decision, not just the request
Write one line per webhook: event id, verdict (processed / duplicate / stale /
bad_signature), and latency. When a client asks why a deposit is missing, this log
answers in seconds instead of a two-hour archaeology session. In a trading system I
maintain, this single log line has replaced most of the "can you check my account" tickets.
What this does not solve
- It is not a distributed lock. If two processes can both claim the same key, your store
must be the referee — a
UNIQUEconstraint, not application code. - It does not deduplicate semantically identical events with different ids. If the provider
sends
evt_1andevt_2for the same settlement, you need a business-level key (order id + amount + type), not the transport id. - It does not retry. Retries belong to the sender.
The full runnable module — signature verification, freshness window, claim/release store
and six test cases — is on GitHub:
gist.github.com/Sundry007.
I build payment and trading back-ends for cross-border businesses: fixed-price milestones,
integer-minor-unit ledgers, full unencrypted source handover. Details and pricing are at
keston.dev.
Top comments (0)