Webhooks and Event-Driven Integration Questions
HTTP push integration between organisations, where a provider notifies subscribers of events by calling their endpoints. Covers outbound webhook delivery systems (subscription management and event matching, at-least-once delivery and why exactly-once is not on offer, retries with exponential backoff and jitter, dead-letter handling, isolating slow or failing destinations with per-destination limits and circuit breakers, batching, push versus pull dispatch workers, delivery dashboards, replay and manual retry), payload signing and verification (HMAC over timestamp and raw body, replay protection, secret rotation, asymmetric signatures), idempotent and deduplicating receivers, handling duplicate, out-of-order and bursty inbound events, thin events and re-fetching state, acknowledgement semantics, relaying received events to browsers, and webhooks versus polling trade-offs. Excludes broker-based publish/subscribe and queue architecture, payment-processor reconciliation, and general API security mechanics.
Can a webhook provider offer exactly-once delivery? Explain what guarantee providers really give, why, and what that means for the engineers who receive their events.
Sample Answer
The idea in plain words
No. A provider calling a receiver over HTTP cannot offer exactly-once delivery, and the reason fits in one sentence: when the provider sends a request and gets no reply, it cannot know whether the receiver never got it, got it and failed, or processed it and the reply was lost. It must pick between sending again (maybe a duplicate) and not sending again (maybe a loss). Reliable providers pick sending again. That guarantee is called at-least-once: every event arrives one or more times. What engineers actually want, "each event has its effect once", is built on the receiver's side by making repeats harmless. That combination is often called effectively-once or exactly-once processing, and it is the receiver's work, not something the network provides.
The three choices a provider has
| Guarantee | On a lost reply | Cost |
|---|---|---|
| At-most-once | Does not resend | Events can be lost silently |
| At-least-once | Resends until acknowledged | Duplicates are possible |
| Exactly-once delivery | Would need both | Not achievable over an unreliable request and reply |
Timeline of the unavoidable ambiguity (illustrative):
- 10:00:00 provider sends event
evt_77to the receiver. - 10:00:01 receiver commits the work and sends
200 OK. - 10:00:02 the connection drops, and the provider never sees the 200.
- 10:00:10 the provider's timeout fires. From where the provider sits, step 2 and "the receiver never got it" look identical.
- The at-least-once provider sends
evt_77again at its next retry time. The receiver now sees the same event a second time.
What this means for the receiving engineer
- Acknowledge only after the event is stored durably. Return 2xx once you have written the event (or its id) to your own database or queue. If you ack first and crash, the event is gone and the provider will not retry. This is the acknowledgement protocol: 2xx means "I have it", anything else means "send it again".
- Deduplicate on the provider's event id. Keep a table of processed ids with a unique constraint and insert the id in the same database transaction as the business change. If the insert violates the constraint, the event is a repeat: skip the work and still return 2xx so the provider stops retrying. Keep ids at least as long as the provider can resend (its retry window plus any manual replay period). If the provider retries for about two days and supports replays for 30 days, a 7-day id table will miss late repeats.
- Prefer naturally idempotent operations. "Set invoice 42 to paid" is safe to run twice. "Add USD 10 to the wallet" is not. Where you must add, record the event id with the ledger entry (a row that records one change to a balance, so the history is kept and not just the total) and enforce uniqueness.
- Expect disorder. Two events about one object can arrive in either order, so compare a version number or timestamp and ignore anything older than what you hold.
A number to see why this matters (assumptions, not measurements): 1 million events a day and 0.5 percent of acknowledgements lost or timed out. That is 1,000,000 x 0.005 = 5,000 duplicates a day. If each duplicate wrongly credits USD 10, that is 5,000 x 10 = USD 50,000 of double credits per day without deduplication.
Why providers do not simply promise more
- Providers can make a stronger promise about their own side: persist every delivery in a database before the first attempt, so a provider crash cannot lose an event. That is a persistent queue, and it beats ephemeral retries held in memory (a restart would drop them). For example, a provider that keeps its pending retries in a memory list loses every one of them when the process restarts, while a provider that writes each delivery to a database row before the first attempt picks the retries up again from those rows after a restart. It makes loss rare. It does not remove duplicates.
- Waiting for the receiver to confirm processing, not just receipt, would require a two-way protocol (a second message in which the receiver reports "finished processing" back to the provider) and a receiver that is always up; it is slower, harder for developers to adopt, and still ends with an ambiguous last message.
- Strict ordering is another optional strengthening: deliver one event at a time per key and wait for the ack. It costs throughput, and one stuck event blocks everything behind it.
- Each extra guarantee costs the provider storage, workers and support effort, and costs developers a harder integration. Most providers choose at-least-once plus an event id plus a replay tool, and document it.
When correctness pushes toward more
For billing, inventory and anything that moves money, do not rely on a single push. Combine the pieces: idempotent handlers, a pull API to list events since a cursor (a bookmark value, such as the id of the last event you saw, that you send back to get only what came after it) so you can reconcile gaps, and a periodic job comparing your records with the provider's. The webhook is then a fast hint and the reconciliation is the safety net. If a feature truly cannot tolerate even a short delay or rare gap, consider a transport designed for it (for example a consumer reading from a durable log: a log in which every event is stored in order and each consumer remembers its own read position, so it can re-read anything it missed; most integrations never need this) rather than HTTP push.
Common mistakes
- Telling a team "the provider guarantees exactly-once" because a marketing page says "reliable".
- Deduplicating in memory, so a restart forgets what it saw.
- Ack before durable write, or doing slow work before the ack so the provider's timeout triggers extra repeats.
- A dedupe-id retention shorter than the provider's retry or replay window.
You ingest event callbacks from several partners who retry on timeout. Duplicates and out-of-order events both happen. How do you decide how long to remember what you have already seen, and how do you make sure an old event never overwrites newer state?
Sample Answer
The idea in plain words
Partners that retry on timeout deliver at-least-once: an event can arrive again, and a later event can arrive before an earlier one. Two different problems follow, and they need two different tools.
- Duplicates are handled by remembering the IDs you have seen (a deduplication store). The memory only has to last as long as the partner can still send the event again, so its lifetime is derived from the partner's retry window, not guessed.
- Out-of-order events are handled by never applying an event unless it is newer than what the record already holds (a version guard). This does not depend on any memory of past events, so it is the correctness backstop even after the dedupe memory has expired.
Treat the dedupe store as protection for side effects (actions that reach the outside world, such as sending an email or charging a card, which cannot be undone by overwriting a row) and the version guard as protection for state. If you only have a minute: the TTL rule, the unique key and the conditional version update are the core of the answer; the other options below are variations.
How long to remember
The rule: keep an ID for at least the longest time the partner can still redeliver it, plus a margin.
TTL≥retry window+longest delivery delay+marginwhere TTL (time-to-live) is how long a stored ID is kept, the retry window is how long the partner keeps retrying after the first attempt, and the margin covers clock differences and slow queues.
Scenario (assumed for illustration, not any real partner): partner A retries 7 times with doubling gaps of 1, 2, 4, 8, 16, 32 and 64 minutes after the first attempt. The last retry is at 1+2+4+8+16+32+64 = 127 minutes. The longest delivery delay is taken as 0 for this partner (it sends at once and your intake records the ID immediately), so with a margin of 1 hour the TTL is 127 + 0 + 60 = 187 minutes. If your own intake could hold an event for up to 10 minutes before its ID is recorded, that delay goes into the formula: 127 + 10 + 60 = 197 minutes. Partner B documents a 24 hour window, so its TTL is 25 hours. Partner C offers a manual "resend" button that works for 30 days; do not size the dedupe store for 30 days, because the version guard and an idempotent write (a write that leaves the same result when it is run twice, shown below) make a late resend harmless to your stored state. A side effect such as an email is not protected by those two, so give it its own idempotency key at the sender you call, or accept that a manual resend after the TTL can repeat it.
Read each partner's documented retry window, set the TTL per partner, and monitor for events that arrive after their TTL.
Store choice and size. If you build only one, build the relational table with a unique constraint; the cache is a speed-up for high volume, and the Bloom filter is an optional pre-check. The key is the pair (partner_id, event_id), because two partners can use the same ID. If a partner sends no event ID, build the key from fields that identify the fact (partner, object ID, event type, object version), not from a hash of the whole body when the body carries a per-attempt field such as a "sent at" time.
- A relational table with a unique constraint is durable and can be written in the same transaction as your state change. It suits moderate volume.
- A cache with set-if-absent and an expiry (Redis
SET key value NX EX seconds, for example:NXwrites only if the key does not already exist, so a failed write means "seen", andEXdeletes the key after the given number of seconds, which is the TTL) is fast for high volume, but entries can be evicted or lost, so it is a filter in front of the guards, not the source of truth. - A Bloom filter (a compact structure that sometimes says "seen" for something never seen) must not be the only gate: a false "seen" would silently drop a real event.
Size, with assumed numbers: 2,000,000 events per day is 2,000,000 / 86,400 = 23.1 events per second on average. With a 5 day TTL that is 10,000,000 live keys; at an assumed 100 bytes per key, 10,000,000 x 100 = 1,000,000,000 bytes, about 1 GB. It fits one modest cache or table.
Never let an old event overwrite a newer state
Every event carries something that orders it: a per-object sequence number, a version, or the provider's updated_at. Store the highest one applied on the record, and make the write conditional. The write has to be an upsert (insert the row, or update it if it already exists), because the first event you see for an object may not be the earliest one, and a plain UPDATE finds no row to change:
INSERT INTO orders (id, status, version) VALUES (:id, :status, :version)
ON CONFLICT (id) DO UPDATE SET status = excluded.status, version = excluded.version
WHERE excluded.version > orders.version
excluded names the row we tried to insert. The final WHERE lets the update happen only if the incoming version is newer than the stored one. If the affected-row count is 0, the event is stale or a duplicate: log it and return 2xx, so the partner stops retrying. The check and the write are one statement, so two concurrent events cannot interleave.
Worked trace for order 77, events created (version 1), paid (version 2), shipped (version 3), arriving as 1, 3, 2, 1:
| Arrival | Event | Stored version before | Rule incoming > stored | Stored state after |
|---|---|---|---|---|
| 1 | created, v1 | none (insert) | applied | created, v1 |
| 2 | shipped, v3 | 1 | 3 > 1, applied | shipped, v3 |
| 3 | paid, v2 | 3 | 2 > 3 is false, ignored | shipped, v3 |
| 4 | created, v1 again | 3 | 1 > 3 is false, ignored | shipped, v3 |
The final state is shipped, v3 for any arrival order, and the duplicate is harmless. The program below tries all six orders of the three events against the guarded upsert and against a plain overwrite (last write wins), and prints how many orders end in the right state.
import itertools
import sqlite3
EVENTS = {1: ("created", 1), 2: ("paid", 2), 3: ("shipped", 3)}
def new_db():
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders(id INTEGER PRIMARY KEY, status TEXT, version INTEGER)")
return db
def last_write_wins(db, status, version):
db.execute("INSERT OR REPLACE INTO orders(id, status, version) VALUES(77, ?, ?)", (status, version))
def guarded_upsert(db, status, version):
cur = db.execute(
"INSERT INTO orders(id, status, version) VALUES(77, ?, ?) "
"ON CONFLICT(id) DO UPDATE SET status = excluded.status, version = excluded.version "
"WHERE excluded.version > orders.version",
(status, version))
return cur.rowcount
def final_state(apply_event, order):
db = new_db()
for v in order:
apply_event(db, *EVENTS[v])
return db.execute("SELECT status, version FROM orders WHERE id = 77").fetchone()
# every possible arrival order of the three events
arrivals = list(itertools.permutations([1, 2, 3]))
for name, fn in (("last write wins", last_write_wins), ("guarded upsert", guarded_upsert)):
ok = sum(final_state(fn, order) == ("shipped", 3) for order in arrivals)
print(f"{name:16} ends at shipped, v3 in {ok} of {len(arrivals)} arrival orders")
db = new_db()
print("rows changed for arrivals 1, 3, 2, 1:", [guarded_upsert(db, *EVENTS[v]) for v in (1, 3, 2, 1)])
Output:
last write wins ends at shipped, v3 in 2 of 6 arrival orders
guarded upsert ends at shipped, v3 in 6 of 6 arrival orders
rows changed for arrivals 1, 3, 2, 1: [1, 1, 0, 0]
The overwrite is right only when version 3 happens to arrive last (2 of the 6 orders). The guarded upsert is right in all 6, including when the first event seen is shipped and the row does not exist yet, and the rows-changed list for arrivals 1, 3, 2, 1 shows the late version 2 and the repeat of version 1 each change nothing.
Cautions:
- This works when each event carries the full new state. If events are deltas ("add 10 credits"), ignoring a stale one loses information. Store the events and compute state by folding them in order, or hold a gap (v3 arrived but v2 did not) in a parking table (a small table where an event that arrived too early waits until the missing earlier one shows up) for a short time and then fetch. Example with a credit balance: the events are version 1 add 10, version 2 add 5, version 3 subtract 3, and they arrive as 1, 3, 2. Applying 1 gives 10. If version 3 is then applied at once the balance is 10 - 3 = 7, and the guard would ignore the late version 2, leaving 7 when the true balance is 12. Instead, version 3 goes to the parking table because version 2 is missing; when version 2 arrives the balance becomes 10 + 5 = 15, then the parked version 3 is applied to give 15 - 3 = 12. Folding means applying the deltas one after another in version order like this.
- Timestamps can tie (same second) and partner clocks can disagree. Prefer a sequence number; with timestamps only, define the tie rule and expect occasional ambiguity.
The alternative: fetch the latest state
Treat the webhook as a hint and call the partner's API for the current object (GET /orders/77), then store what it returns together with its version. Order, duplicates and even lost events stop mattering, because you always read the truth. The costs are one outbound call per event, the partner's rate limits, and the partner's API being up. Coalesce (merge into one): if 20 events for the same object arrive within a few seconds, fetch once.
Make the downstream create idempotent
If an event creates something (a lead in a CRM), do not rely on dedupe alone. Add a unique key on the natural identity and upsert (insert the row, or update the existing row if the key is already there):
INSERT INTO leads (partner_id, partner_lead_id, name, version) VALUES (...)
ON CONFLICT (partner_id, partner_lead_id)
DO UPDATE SET name = excluded.name, version = excluded.version
WHERE excluded.version > leads.version
ON CONFLICT (...) DO UPDATE runs the update branch when a row with that key already exists, excluded names the row we tried to insert, and the final WHERE lets the update happen only if the incoming version is newer. A retry, a replay after the TTL, or a manual resend then cannot create a second lead.
Events that keep failing
Your own processing can fail too (a bad payload, a downstream outage). Acknowledge the partner after the event is stored durably, then retry internally: exponential backoff with a cap and jitter (a random spread so retries do not align), for example a base of 30 seconds doubling to 30, 60, 120, 240 and 480 seconds, which totals 930 seconds (15.5 minutes) over five retries. After the last attempt, move the event to a dead-letter store (a holding area for events that exhausted their retries) with the payload, the error, the attempt count and the first and last failure times. Alert on its size and on the age of its oldest item. After a fix, replay from it; replays go through the same dedupe, version guard and upsert, so they are safe.
Common mistakes
- A dedupe TTL shorter than the partner's retry window, so the last retries are processed twice.
- Using the dedupe store as the only protection against stale state.
- Keying on the event ID alone across partners.
- Holding the partner's HTTP request open while retrying internally, which causes more partner retries.
- Returning an error for a stale event, which makes the partner retry something that can never succeed.
You are building the endpoint that receives callbacks from a partner's system. How do you prove a request really came from them, stop an attacker replaying a captured request, process each event only once, and respond so the partner's retries help rather than hurt? Sketch the handler.
Sample Answer
The idea in plain words
The partner's callback is an HTTP request from the internet to a URL anyone can try, so the URL proves nothing. Four separate jobs, each with its own tool:
- Prove origin: an HMAC signature (a keyed hash of the request that only someone holding the shared secret can produce) over the exact raw bytes of the body.
- Stop replay: a replay attack means an attacker captures a genuine signed request and sends it again later. A signed timestamp bounds how old a request may be, and an event-id check catches a repeat inside that window.
- Process once: a table of already-seen event ids with a unique constraint, written in the same database transaction as the stored payload. The background worker that later does the work must itself be safe to repeat (mark each inbox row done in the same transaction as its effect), because a worker can crash after the effect and before the mark.
- Respond usefully: the status code you return tells the partner whether to retry. 2xx means "stop, I have it", 5xx or 429 means "try again later", and other 4xx means "this request will never be accepted, do not bother".
Assumptions about the partner (illustrative)
The partner signs each attempt fresh, sending X-Partner-Timestamp (Unix seconds), X-Partner-Signature (hex of HMAC-SHA256 over the timestamp, a dot, then the raw body) and the event id inside the JSON body as id. These header names and the scheme are made up for the sketch; use whatever the partner documents. The replay window is 300 seconds. The partner retries on 5xx, 429 and timeouts, with backoff.
The handler, in the order it runs
- Cheap guards first. Reject bodies over a size limit (for example 1 MB) with 413 (content too large), and requests missing the timestamp or signature header with 400. This keeps anonymous garbage from reaching the hashing work.
- Read the raw body bytes. Do not parse the JSON yet.
- Timestamp window. If the absolute difference between your clock and the timestamp is over 300 seconds, return 401. (401 means "this request could not be authenticated". A stale timestamp or a wrong signature both mean the request cannot be shown to come from the partner. 403 would mean the caller is known but not allowed, which is not the situation here.) Using the absolute difference also covers clock skew, the few seconds by which two machines' clocks can disagree, because a timestamp slightly in the future is accepted too. The timestamp is inside the signed string, so an attacker cannot refresh an old request by editing it.
- Verify the signature. Recompute HMAC-SHA256 with your secret over timestamp + "." + raw body, and compare with the header using a constant-time comparison function (an ordinary string comparison can leak, through timing, how many leading characters matched). Try the current secret and, during rotation, the previous one. On mismatch return 401 with a generic message (a fixed short body such as "invalid request" that does not say whether the signature, the timestamp or the format was wrong, so an attacker learns nothing from it).
- Parse the JSON now that it is authenticated. If it will not parse, return 400 and raise an alert: a signed but malformed body is the partner's bug.
- Deduplicate and store in one transaction: insert the event id and the payload into an inbox table (a table that records every received event, keyed by event id, before any processing happens; it is the receiving-side counterpart of an outbox) with a unique constraint on the id, so the database itself refuses a second row with the same id. If the insert hits the constraint, this is a repeat: return 200 and do nothing more. The inbox row is the durable record.
- Acknowledge. Commit, then return 200 (or 204) quickly. A background worker reads the inbox and does the real work, so a slow job never causes a partner timeout and extra retries.
- If your database is down, return 503 with a
Retry-Afterheader (RFC 9110: seconds, or an HTTP date). Never return 200 for an event you have not stored. Unknown event types: return 200 and ignore them, so a partner adding a new type does not trigger endless retries.
A trace through the handler (illustrative, window 300 seconds, now = 12:00:00)
| Request | What arrives | Decision | Why |
|---|---|---|---|
| A | Genuine, timestamp 12:00:00, id evt_5 | 200, work queued | Signature matches, in window, new id |
| B | Exact copy of A sent by an attacker at 12:00:20 | 200, nothing done | Signature is valid and 20 seconds is inside the window, so the id check is what stops the repeat |
| C | Exact copy of A sent at 12:10:00 | 401 | 600 seconds is over 300, rejected before the id is looked up |
| D | A's body with the amount edited, old signature | 401 | The HMAC no longer matches the bytes |
| E | Genuine new event while your database is down | 503 with Retry-After: 30 | Not stored, so not acknowledged; the partner retries and the retry is accepted |
Note what B shows: the timestamp alone does not stop replay inside the window, and the id table alone is not enough over time, so both are used. The id table must remember ids at least as long as the partner can legitimately resend (its whole retry period and any manual replay), not just 300 seconds; the window only decides how old a first-time request may be.
The handler as code
The sketch below implements steps 1 to 8 with the made-up scheme above and replays the requests of the trace (A to E, with E sent a second time after the database recovers) on a simulated clock, where T0 stands for 12:00:00. Requests F to L then exercise the other branches: a signature made with the previous secret, one made with an unknown secret, timestamps ahead of the clock, a missing header, an oversized body and a signed body that is not JSON. It uses an in-memory SQLite table as the inbox. The background worker is left out: stored, work queued is where it would be notified.
import hashlib
import hmac
import json
import sqlite3
SECRETS = [b"current-secret", b"previous-secret"] # new secret first; old one accepted during rotation
WINDOW = 300 # seconds a request may differ from our clock
MAX_BODY = 1_000_000 # 1 MB
T0 = 1_700_000_000 # simulated clock: treat T0 as 12:00:00
def sign(secret, ts, raw):
return hmac.new(secret, str(ts).encode() + b"." + raw, hashlib.sha256).hexdigest()
def make_inbox():
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE inbox(event_id TEXT PRIMARY KEY, payload TEXT NOT NULL)")
return db
def handle(db, raw, ts_header, sig_header, now, db_up=True):
"""Returns (status, extra headers, note)."""
if len(raw) > MAX_BODY:
return 413, {}, "too large"
if not ts_header or not sig_header:
return 400, {}, "missing header"
try:
ts = int(ts_header)
except ValueError:
return 400, {}, "bad timestamp"
if abs(now - ts) > WINDOW:
return 401, {}, "outside window"
good = [hmac.compare_digest(sign(s, ts, raw).encode(), sig_header.encode()) for s in SECRETS]
if not any(good):
return 401, {}, "bad signature"
try:
event = json.loads(raw)
except ValueError:
return 400, {}, "signed but not JSON"
if not db_up:
return 503, {"Retry-After": "30"}, "not stored"
try:
with db: # one transaction: the unique id and the payload are saved together
db.execute("INSERT INTO inbox(event_id, payload) VALUES (?, ?)", (event["id"], raw.decode()))
except sqlite3.IntegrityError:
return 200, {}, "repeat, nothing done"
return 200, {}, "stored, work queued"
db = make_inbox()
raw_a = b'{"id":"evt_5","type":"order.shipped","amount":100}'
sig_a = sign(SECRETS[0], T0, raw_a)
raw_d = raw_a.replace(b'"amount":100', b'"amount":900')
raw_e = b'{"id":"evt_6","type":"order.shipped","amount":50}'
sig_e = sign(SECRETS[0], T0 + 30, raw_e)
raw_f = b'{"id":"evt_7","type":"order.shipped","amount":20}'
sig_f = sign(SECRETS[1], T0 + 40, raw_f) # signed with the previous secret
raw_g = b'{"id":"evt_9","type":"order.shipped","amount":20}'
sig_g = sign(b"unknown-secret", T0 + 40, raw_g)
raw_h = b'{"id":"evt_8","type":"order.shipped","amount":10}'
sig_h = sign(SECRETS[0], T0 + 90, raw_h)
sig_i = sign(SECRETS[0], T0 + 660, raw_h)
raw_l = b"not json at all"
sig_l = sign(SECRETS[0], T0, raw_l)
rows = [
("A genuine, 12:00:00", handle(db, raw_a, str(T0), sig_a, T0)),
("B copy of A, 12:00:20", handle(db, raw_a, str(T0), sig_a, T0 + 20)),
("C copy of A, 12:10:00", handle(db, raw_a, str(T0), sig_a, T0 + 600)),
("D edited body, old signature", handle(db, raw_d, str(T0), sig_a, T0)),
("E genuine, database down", handle(db, raw_e, str(T0 + 30), sig_e, T0 + 30, db_up=False)),
("E retried after recovery", handle(db, raw_e, str(T0 + 30), sig_e, T0 + 60)),
("F signed with previous secret", handle(db, raw_f, str(T0 + 40), sig_f, T0 + 40)),
("G signed with unknown secret", handle(db, raw_g, str(T0 + 40), sig_g, T0 + 40)),
("H timestamp 30 s ahead", handle(db, raw_h, str(T0 + 90), sig_h, T0 + 60)),
("I timestamp 600 s ahead", handle(db, raw_h, str(T0 + 660), sig_i, T0 + 60)),
("J signature header missing", handle(db, raw_a, str(T0), "", T0)),
("K body over 1 MB", handle(db, b"x" * (MAX_BODY + 1), str(T0), sig_a, T0)),
("L signed but not JSON", handle(db, raw_l, str(T0), sig_l, T0)),
]
for name, (status, headers, note) in rows:
print(f"{name:30} -> {status} {headers or ''} {note}")
print("rows in inbox:", db.execute("SELECT COUNT(*) FROM inbox").fetchone()[0])
Output:
A genuine, 12:00:00 -> 200 stored, work queued
B copy of A, 12:00:20 -> 200 repeat, nothing done
C copy of A, 12:10:00 -> 401 outside window
D edited body, old signature -> 401 bad signature
E genuine, database down -> 503 {'Retry-After': '30'} not stored
E retried after recovery -> 200 stored, work queued
F signed with previous secret -> 200 stored, work queued
G signed with unknown secret -> 401 bad signature
H timestamp 30 s ahead -> 200 stored, work queued
I timestamp 600 s ahead -> 401 outside window
J signature header missing -> 400 missing header
K body over 1 MB -> 413 too large
L signed but not JSON -> 400 signed but not JSON
rows in inbox: 4
Read each line against the trace. Request A is stored. B carries a valid signature inside the window, so the only thing that stops it is the unique id: the insert raises IntegrityError, and the handler answers 200 without doing the work again. C is rejected on age before the id is looked up. D has the old signature over different bytes, so the HMAC differs. E gets 503 with Retry-After: 30 while the database is down, nothing is written, and the retry is accepted, which leaves two rows in the inbox (evt_5 and evt_6) so far. F is signed with the previous secret and is accepted, G with a secret that was never issued and is refused, which is the rotation behaviour: both secrets work for a while and nothing else does. H has a timestamp 30 seconds ahead of the receiver's clock and is accepted, while I, 600 seconds ahead, is refused, so the absolute difference covers skew in both directions. J, K and L hit the cheap guards and the malformed-body rule with 400, 413 and 400. The final count is four rows: evt_5, evt_6, evt_7 and evt_8. In the signature line, sign joins the timestamp, a dot and the raw bytes before hashing, which is the exact string the partner is assumed to sign. The list good computes the check against every accepted secret, so a request signed with either the current or the previous secret passes during rotation.
Making the partner's retries help
Return 2xx for anything stored or recognised as a repeat, so retries stop. Return 5xx or 429 only for your own temporary trouble, so retries come back later. Return 401 or 400 for permanent rejection, so the partner does not retry a request that cannot succeed. Replying 200 to everything hides your failures from the partner, and replying 500 to bad signatures makes them retry forged requests for hours.
Monitoring suspicious activity and persistent failures
Count and alert on: signature failures (a sudden rise means an attack or a secret mismatch after rotation), stale timestamps (often clock drift on either side), the duplicate ratio (a spike means the partner is not seeing your acks), your own 5xx rate, and the age of the oldest unprocessed inbox row. Keep a log of rejected requests with source address, header values and a hash of the body, but never the secret. Tell the partner's contact when you see persistent failures, since they will see them from their side too.
What this sketch covers and what a real endpoint also needs
This is an illustration for one scheme: one HMAC, a replay window, an id table and four response classes. A production endpoint must also handle secret storage and rotation, clock skew between the two systems, character encoding and any body transformations a proxy applies before your code sees the bytes (the HMAC must be computed over the bytes exactly as received), retention and cleanup of the id table, per-source rate limits, and any partner rule that differs from the assumptions above (for example retries that reuse the first signature). It is a starting point, not a complete security review.
Common mistakes
- Checking the signature over re-serialised JSON.
- Comparing signatures with
==. - Leaving the timestamp outside the signed string.
- Doing the work before acknowledging, then timing out.
- Expiring the id table after the replay window while the partner can still resend.
Your product depends on callbacks from a third-party service, and they can be late, repeated or out of order. Design how you ingest them so the state you expose to your own clients is always consistent and never goes backwards.
Sample Answer
The idea in plain words
You cannot control the order, the timing or the number of callbacks a third-party service sends. What you can control is the rule by which they change your data. Make that rule a forward-only state machine: every state has a rank, an update is applied only if it moves the record to a higher rank, and a repeated or late callback therefore changes nothing. Your own clients then read a single source of truth that carries its own version number, so they can also refuse to go backwards. When a callback never arrives, ask the provider for the state instead of waiting forever.
Terms used below. A reducer is code that takes the current state and one event and returns the new state. An append-only table only ever gets new rows added; rows are never changed or deleted. An outbox is a table of side effects (emails, notifications) still to be sent, written in the same transaction as the state change. A reconciliation job is a periodic job that compares your records with the provider's and repairs any difference. A terminal state is one from which no further transition happens. An atomic statement is one that happens completely or not at all, with no other statement able to see it half done. An ETag is a response header naming one version of a resource, and If-None-Match is the request header in which a client sends back the ETag it holds. A cursor is a bookmark value that a client sends back to ask for only what changed after it.
Running scenario
Assumed for illustration: your app submits a video to a third-party transcoding service and gets callbacks about the job. States and ranks: queued (1), processing (2), and two terminal states succeeded and failed (both rank 3). Each callback carries the provider's event_id, the job_id, the status and the provider's per-job sequence number seq.
Ingest pipeline
- Verify the callback's signature and timestamp on the raw body.
- Store the raw event in an append-only table with a unique constraint on
event_id. A duplicate is a no-op. This gives an audit trail and lets you replay after a bug. - Reduce the event into the job's current state with one conditional statement:
INSERT INTO jobs (job_id, status, rank, version)
VALUES (:job, :status, :rank, 1)
ON CONFLICT (job_id) DO UPDATE
SET status = excluded.status, rank = excluded.rank, version = jobs.version + 1
WHERE jobs.rank < excluded.rank
The first callback for a job finds no row, so the insert succeeds and creates it at version 1. For a job that already has a row, the ON CONFLICT branch runs the update, and its WHERE applies it only if the stored rank is lower than the incoming one (excluded names the row we tried to insert). PostgreSQL and SQLite both accept this form. Run through the four callbacks of the trace below, it changes a row on arrivals 1 and 3 only, and the other two report 0 rows changed.
The affected-row count says whether anything changed. Because the check and the write are one atomic statement, two concurrent callbacks cannot make the state go backwards. version is your counter, which increases by one on every real change, and is separate from the provider's seq. In the shown statement seq is only stored with the raw event for the audit trail: the rank rule does not need it, because states only move forward. It matters for the first case under "When rank is not enough", where states can repeat: there a stored seq column takes over the job that rank does here (WHERE jobs.seq < excluded.seq).
4. Side effects (an email "your video is ready", a notification) run only for the callback whose update changed a row, written to an outbox in the same transaction. A repeated callback changes no row and so sends nothing.
5. Acknowledge with 2xx, including for stale and duplicate callbacks. Returning an error for a callback that can never be applied only makes the provider retry.
If both terminal states arrive (a provider bug), the first wins because 3 < 3 is false. Log it as an anomaly to investigate rather than silently flipping.
Worked trace
Callbacks for job J1 arrive in this order: processing (seq 2), queued (seq 1), succeeded (seq 3), processing (seq 2) again. Start: no row, version 0.
| Arrival | Callback | Stored rank before | Rule rank < incoming | Stored state after | Our version |
|---|---|---|---|---|---|
| 1 | processing, rank 2 | none (insert) | applied | processing | 1 |
| 2 | queued, rank 1 | 2 | 2 < 1 is false, ignored | processing | 1 |
| 3 | succeeded, rank 3 | 2 | 2 < 3, applied | succeeded | 2 |
| 4 | processing, rank 2 (duplicate) | 3 | 3 < 2 is false, ignored | succeeded | 2 |
The state moved only forward (processing, then succeeded), the version went 1, then 2, and the "ready" email was triggered once, at arrival 3.
When rank is not enough
- Non-monotone states (a job can be reopened, an order can go from delivered to returned): ranks no longer work. Use the provider's per-object sequence number or version and apply an event only if its number is higher than the stored one.
- No ordering information at all: fetch the current object from the provider's API on every callback and store what it returns. This costs a call per event but makes order irrelevant.
- Missing callbacks: a callback that never comes leaves the job stuck, and if every callback for a job is lost your
jobstable never gets a row for it at all. So the reconciliation job does not walkjobs. It walks a smallsubmissionsrecord that your app writes at the moment it calls the provider (job_id,submitted_at, and a flag set once the job has reached a terminal state). For each submission still not terminal after an expected time (assume 15 minutes for this service), fetch the status from the provider and feed it through the same reducer; if nojobsrow exists yet, the reducer's insert creates it. Webhooks give speed; the poll gives completeness.
Exposing the state to your own clients
Clients (including a mobile app that is sometimes offline) must see something consistent and must not be able to regress it.
- Serve
GET /jobs/J1with the stored status andversion, plus anETagheader holding the version as a quoted string (ETag: "2"; an entity tag is always written in double quotes). A client that already holds that version sendsIf-None-Matchand gets 304 Not Modified with no body (RFC 9110). - For lists, expose a cursor. A job's own
versioncannot be the cursor, because it counts changes to that one job and two different jobs can both be at version 2. Give the owning account one counter instead, and stamp every job row that really changes with the next number. In the same transaction as the reducer, and only when the reducer reported one row changed, runUPDATE account_changes SET n = n + 1 WHERE account = :account RETURNING n, then store the returned number in that job'schange_no. The row lock on the counter makes two changes for one account take turns, so a number never becomes visible before a lower one.GET /jobs?changed_since=<cursor>returns the jobs whosechange_nois above the cursor, together with the highestchange_noreturned as the next cursor, so an app that was offline for a day catches up with one request. A timestamp is a weaker cursor: two transactions can commit out of order, and a client that already moved past the later time would never see the earlier row. - The client applies a response only if its
versionis greater than the one it holds locally. This stops an older response that arrives late (two fetches racing) from overwriting a newer one. Example: the phone holds J1 at version 1 (processing). Two fetches are sent; the response with version 2 (succeeded) arrives first, so the phone applies it and now holds version 2. The slower response with version 1 then arrives; 1 is not greater than 2, so the phone discards it. A phone that was offline and still holds version 1 simply applies the first response that carries a higher number. - Treat a push notification as a hint to refetch, not as the data. Delivery of push messages to a phone is not guaranteed in order or at all, so the app always re-reads the state from your API.
- While the state is not terminal, show it honestly ("processing"); do not predict success from a local action.
Consistency you can state
For one job: the exposed rank never decreases and version never decreases (guaranteed by the conditional update and the version rule), duplicates have no effect (unique event_id and the rank guard), and a lost callback, even when every callback for a job is lost, is repaired once the expected time has passed and the next poll over submissions runs (reconciliation). What is not promised: that clients see every intermediate state. A client that is offline may see only queued and then succeeded.
Common mistakes
- Overwriting the row with whatever callback arrived last.
- Using arrival time as order.
- Doing the read, comparison and write as separate statements.
- Triggering side effects on every callback instead of on the one that changed state.
- Letting the client trust whichever response arrived last.
- Answering stale callbacks with an error.
A teammate has never worked with webhooks. Explain what they are, how a receiving service should handle one safely from the moment the request arrives, and what concerns the sending side has to design for.
Sample Answer
The idea in plain words
A webhook is a doorbell instead of a mailbox check. Normally your service asks another service "anything new?" over and over (polling). With a webhook, you give the other service (the provider) a URL on your server in advance, and when something happens, the provider makes an HTTP request to that URL to tell you. The URL is called your endpoint, and the request is the webhook. Examples of "something happens": an invoice is paid, a file finishes processing, a build fails.
The life of one webhook
- Subscribe: you register your endpoint URL with the provider and say which event types you want. The provider gives you a secret, a shared password used for proving requests are really from them.
- Event: something happens at the provider.
- Delivery: the provider sends an HTTP POST to your URL with a JSON body.
- Acknowledgement: you reply with a 2xx status (200 or 204) to say "I have it".
- Retry: if you reply with an error or do not reply in time, the provider tries again later, waiting longer each time (backoff).
Illustrative payload (the shape varies by provider):
{
"id": "evt_1042",
"type": "invoice.paid",
"created": "2026-03-02T09:15:00Z",
"data": { "invoice_id": "inv_88", "amount_cents": 4900, "currency": "usd" }
}
id uniquely names the event, type says what happened, created is when it happened, and data is the details. Some providers send only ids ("thin" payloads) and expect you to fetch the details with an API call. The trade-off: a thin payload carries nothing sensitive and the fetched data is always current, but it costs the receiver one extra API call per event; a full payload saves that call, but it can be stale by the time it is processed, can arrive out of order, and puts the data in the request itself, where logs and proxies along the way can capture it.
How the receiver should handle one, in order
- Read the raw body first, before any JSON parsing. Signatures are computed over the exact bytes sent, and re-serialising the JSON changes the bytes.
- Check it is really from the provider: compute an HMAC (a keyed hash: a fingerprint of the body that only someone with the secret can produce) over the body and compare it with the signature header, using a constant-time comparison. An ordinary
==on two strings stops at the first character that differs, so how long it takes reveals how many leading characters were right, and an attacker who can time many requests can guess a signature piece by piece; a constant-time function (Python'shmac.compare_digest) takes the same time wherever the strings differ. Reject with 401 or 400 if it does not match. Also check the timestamp in the request is recent (for example within five minutes) so an attacker cannot resend a captured request later. - Deduplicate: look up the event
idin a table of ids you have already handled. If it is there, return 2xx and do nothing, because providers deliver at least once and may send the same event twice. - Store the event, then acknowledge quickly. Write the event to your database or a queue, return 200 within a second or two, and do the slow work afterwards in a background job. A slow handler makes the provider think you failed and retry.
- Use the right status codes: 2xx when stored, 4xx for requests you will never accept (bad signature, malformed body), 5xx for your own temporary trouble so the provider retries. An event type you do not handle is acknowledged with 2xx and ignored, so a provider adding a new type does not trigger endless retries or get your endpoint switched off. Providers differ on which non-2xx codes they retry (many retry any non-2xx), so read the documented retry rules for the one you integrate with.
The check on real input
The sketch below uses an illustrative scheme: the provider signs the timestamp, a dot, then the raw body with HMAC-SHA256, and sends the timestamp and the hex signature in headers. The header names and signed format are made up for the demo; use whatever your provider documents. The time is simulated, so nothing waits.
import hashlib
import hmac
import json
SECRET = b"whsec_demo_secret" # shared with the provider when you subscribed
WINDOW = 300 # seconds a request may be old
NOW = 1_700_000_000 # simulated "current time" (Unix seconds)
seen_ids = set() # stand-in for a table of handled event ids
work_done = [] # one entry each time the real work would run
def sign(secret, timestamp, raw_body):
"""HMAC-SHA256 over timestamp + "." + the raw bytes, as lowercase hex."""
message = str(timestamp).encode() + b"." + raw_body
return hmac.new(secret, message, hashlib.sha256).hexdigest()
def handle(raw_body, timestamp, signature, now):
"""Returns the HTTP status the receiver sends back."""
if abs(now - timestamp) > WINDOW:
return 401 # too old: possible replay
expected = sign(SECRET, timestamp, raw_body)
if not hmac.compare_digest(expected.encode(), signature.encode()):
return 401 # not from the provider, or altered
event = json.loads(raw_body) # parse only after it is authenticated
if event["id"] in seen_ids:
return 200 # duplicate: acknowledge, do nothing
seen_ids.add(event["id"]) # a real handler stores the event here
work_done.append(event["id"]) # the slow work would be queued here
return 200 # then does the slow work in the background
body = b'{"id":"evt_1042","type":"invoice.paid","data":{"invoice_id":"inv_88","amount_cents":4900}}'
sig = sign(SECRET, NOW, body)
print("signed text starts:", str(NOW) + "." + body[:24].decode() + "...")
print("signature:", sig)
print("genuine request ->", handle(body, NOW, sig, NOW))
print("same event sent again ->", handle(body, NOW, sig, NOW + 20), "(times the work ran so far: %d)" % len(work_done))
print("body edited in transit->", handle(body.replace(b"4900", b"9900"), NOW, sig, NOW))
print("captured, sent later ->", handle(body, NOW, sig, NOW + 600))
Output:
signed text starts: 1700000000.{"id":"evt_1042","type":...
signature: bee89259baba021fd72b8ced6ab16efdb5806e6f5e5fb8c4033838fd0085c4ca
genuine request -> 200
same event sent again -> 200 (times the work ran so far: 1)
body edited in transit-> 401
captured, sent later -> 401
Read the output line by line. The genuine request passes the age check and the signature check, is new, and gets 200. The same event arriving again 20 seconds later is still signed correctly and inside the five-minute window, so only the id lookup stops it: the receiver answers 200 and does nothing more (the work has run once, and the counter would read 2 if the lookup were removed). The edited body (4900 changed to 9900) no longer matches the signature computed over the original bytes, so it gets 401. The captured request replayed 600 seconds later is rejected on age before the signature is even looked at. A real handler also needs the earlier steps (read the raw body, store, acknowledge quickly) around this core.
What the sending side has to design for
Reliability comes first: if events are lost, nothing else matters. The other four concerns come after that and each has a concrete first step.
- Reliability: persist events before sending, retry with backoff and jitter (randomness so retries do not bunch up), and stop after a limit and keep the failure visible. Example: the event is written to a table first, so a crash after the business action but before the send still leaves a record to deliver.
- Signing and secret rotation, so receivers can trust requests. Rotation means replacing the secret on a schedule or after a leak: for a while the sender signs with the new secret and the receiver accepts both, then the old one is retired.
- Limits: do not overwhelm a small receiver. Rate limit the sends, and cap concurrency per endpoint (for example at most 5 requests in flight to one customer URL at a time, however many events are queued for it).
- Visibility: a log of every attempt and a button to resend, because "did you send it?" is the first support question.
- Compatibility: payload shapes change over time, so give each payload a version (a
versionfield or a dated schema name) and add fields without removing old ones, so receivers written against an older shape keep working.
Three failure modes and a simple fix for each
- Slow consumer: your handler takes 30 seconds, the provider times out and retries, and now you have two copies running. Fix: acknowledge after storing, process later.
- Dropped network: the provider's request never arrives, or your reply is lost. Fix: the provider retries; you dedupe by event id; and for important data, run a periodic job that asks the provider's API for recent events to fill any gap.
- Duplicates and disorder: the same event twice, or an "updated" event before the "created" one. Fix: dedupe by id, and compare timestamps or version numbers so older events do not overwrite newer state.
Common mistakes
- Parsing and re-encoding the body before checking the signature.
- Doing all the work before replying.
- Returning 200 for everything, including failures, so the provider never retries.
- Trusting the payload with no signature check because "nobody knows the URL".
Unlock Full Question Bank
Get access to all 9 Webhooks and Event-Driven Integration interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.