Webhooks
Instead of you constantly asking 'anything new?', the other service calls you the moment something happens.
Webhooks in 30 seconds
- What: a reverse API call — the provider POSTs an event to a URL you registered, when something happens.
- Why: avoids constant polling; you hear about events the instant they occur.
- You provide: a public endpoint; they provide: a signed POST with the event payload.
- Verify the signature — anyone can POST to a public URL, so confirm it's really the provider.
- Ack fast, process async: return 200 quickly, do the real work on a queue.
- Expect retries & duplicates — make your handler idempotent.
The courier that texts you
Imagine waiting on a package. Polling is calling the courier every ten minutes to ask 'is it here yet?' — wasteful, and you still hear late. A webhook is the courier texting you the second it's delivered. That's the whole idea: instead of your system repeatedly asking another service for updates, the other service calls you when there's news.
Flip the usual direction of an API call and you've got a webhook. Normally your code calls someone else's server and waits for a reply. A webhook reverses the arrows: the other service's server calls your code. Everything on this page follows from that one reversal — including the three things that make it trickier than it first looks.
Why polling is the problem
Before webhooks, the only way to find out whether a payment cleared on someone else's system was to keep asking. That's polling, and it has no good setting:
- Poll rarely (every few minutes) and you learn about events late — bad for anything a user is waiting on.
- Poll often (every second) and you fire thousands of requests that almost always answer 'nothing changed' — wasteful for you and abusive to the provider's API, which will rate-limit you.
- You still can't win: between two polls, the provider has no way to reach you, no matter how urgent the event.
# Keep asking Stripe whether the payment cleared yet.
while True:
status = stripe.get("/charges/ch_123").status
if status == "succeeded":
fulfill_order()
break
time.sleep(5) # poll every 5s -> up to 5s late, and ~17k empty calls/day
# Multiply by every pending charge: you hammer their API to usually hear 'pending'.A webhook deletes this whole loop. You tell the provider once where to reach you, then stop asking. When the payment clears, they make a single call to you — zero wasted requests, zero lag.
How it works, start to finish
- You register a URL with the provider: 'when a payment succeeds, POST to
https://myapp.com/hooks/payments.' - The event happens on their side (a payment clears, a build finishes, a file uploads).
- They POST the event payload to your URL, usually with a signature header.
- You verify, acknowledge, and process — return 200 fast, then do the real work.
POST /hooks/payments HTTP/1.1
Host: myapp.com
Content-Type: application/json
X-Signature: t=1716249600,v1=5257a869e7ec... # HMAC the provider computed
Stripe-Event-Id: evt_1NXa8c2eZvKY # stable id -> use it to dedupe
{
"id": "evt_1NXa8c2eZvKY",
"type": "payment_intent.succeeded",
"data": { "object": { "id": "pi_3NX", "amount": 4200 } }
}The three things that trip people up
Because a webhook is an inbound call from the outside world, it inherits three problems a normal outbound API call never has. Each has a standard fix, and interviewers love to see all three named.
- Security: your endpoint is public, so anyone can POST fake events. Providers sign each request (HMAC); you verify the signature before trusting it.
- Reliability: your endpoint will occasionally be down, so providers retry — which means the same event can arrive more than once. Make processing idempotent with the event ID.
- Speed: providers expect a fast 200. Don't do heavy work inline — verify, drop the event on a queue, ack, and process asynchronously.
Problem 1 — the gap a public URL leaves open
A webhook endpoint has to be reachable from the public internet so the provider can call it. But that means anyone can call it too. An attacker who guesses the URL could POST a fake payment.succeeded event and trick you into shipping goods for free. The connection being over HTTPS doesn't help — HTTPS proves nobody tampered with the request in transit, not that the request came from the real provider.
The fix is a shared secret and a signature. When you set up the webhook, the provider gives you a secret key that only the two of you know. On every event, the provider computes an HMAC — a fingerprint of the exact request body, keyed by that secret — and sends it in a header. You recompute the same fingerprint with your copy of the secret. If they match, the request genuinely came from someone who holds the secret: the provider. A forger can't produce a valid signature without the key.
import hmac, hashlib
def is_from_provider(raw_body, signature_header):
# Recompute the fingerprint over the EXACT bytes received, with our secret.
expected = hmac.new(WEBHOOK_SECRET, raw_body, hashlib.sha256).hexdigest()
# Constant-time compare so timing can't leak the right signature byte by byte.
return hmac.compare_digest(expected, signature_header)
# A forger who doesn't hold WEBHOOK_SECRET cannot produce a matching signature,
# so a request that fails this check is rejected before any work happens.Problem 2 — retries mean duplicates
Networks and servers are unreliable, so providers assume your endpoint will sometimes fail to answer — and they retry until they get a success. That's good for delivery guarantees but it has a consequence: the same event can arrive two, three, or more times. It can even arrive twice when your processing succeeded but your 200 got lost on the way back. So delivery is at-least-once, never exactly-once.
If handling an event has side effects — charging a card, shipping a box, sending an email — processing it twice is a real bug: a double charge, a double shipment. The fix is idempotency: make your handler produce the same result no matter how many times the same event arrives. The event ID is your natural dedupe key.
def process(event):
# INSERT fails if we've seen this id before -> we already handled it.
inserted = db.insert_if_absent("processed_events", event["id"])
if not inserted:
return # duplicate delivery — safely do nothing
fulfill_order(event) # the side-effecting work runs exactly once per id
# Because the id is stable across retries, a redelivered event is a no-op.Problem 3 — ack fast, work later
Providers give your endpoint only a few seconds to respond before they consider the delivery failed and retry it. If you try to do the real work — generate a PDF, call three other services, send an email — inside the handler, you'll blow that budget, trigger a retry, and end up doing the work twice. The discipline is to make the handler do almost nothing: verify, enqueue, acknowledge. The heavy lifting happens on a worker pulling from the queue.
def handle_webhook(request):
# 1. Verify it's really the provider: recompute the HMAC over the raw body
expected = hmac_sha256(WEBHOOK_SECRET, request.raw_body)
if not constant_time_equals(expected, request.header("X-Signature")):
return 401 # forged request — reject
# 2. Don't do the work inline — enqueue and return 200 immediately
queue.publish("webhook-events", request.json) # process async, idempotent on event id
return 200 # fast ack so the provider won't time out and retryWebhooks vs pub/sub vs polling
| Approach | Who initiates | Best for | Watch out for |
|---|---|---|---|
| Polling | You ask repeatedly | Simple, infrequent checks | Wasteful; laggy |
| Webhook | The provider calls you | Cross-company / third-party events | Security, retries, public endpoint |
| Pub/Sub | Publisher → broker → you | Internal event fan-out | Needs a broker you both share |
Rule of thumb: webhooks connect you to someone else's system across a company boundary (Stripe, GitHub, Twilio); pub/sub connects your own services internally through a shared broker.
The reason the boundary decides it: pub/sub needs both sides to agree on a shared broker (Kafka, a cloud topic) and live inside the same trust zone. You can't make Stripe publish to your internal Kafka. Across companies, a plain signed HTTP POST to a URL is the lowest common denominator everyone can speak — which is exactly why webhooks became the universal integration glue.
Webhooks are the glue of the modern integrated web — the push-based alternative to polling that keeps separate systems in sync.
Why it matters
- They eliminate wasteful polling and cut the delay between an event and your reaction to near zero.
- They're how third-party services (payments, CI, messaging) integrate into your system.
- They turn separate companies' systems into a loosely-coupled, event-driven whole.
If ignored
- You fall back to polling — wasteful, laggy, and it hammers the provider's API.
- Skipping signature verification lets attackers forge events to your public endpoint.
- Ignoring retries means duplicate processing — double refunds, double shipments.
Where it fits
- At the integration boundary between your system and an external provider.
- Feeding a queue, so the public endpoint stays fast and the work happens async.
- As the external-facing cousin of internal pub/sub.
Related topics
- Idempotency: the fix for duplicate webhook deliveries
- Message queues: where you drop events for async processing
- Pub/Sub & CDC: the internal counterpart to external webhooks
- REST vs GraphQL vs RPC: a webhook is just an HTTP call in reverse
Interview lens
Questions it unlocks
- How would you get notified when a payment succeeds on Stripe?
- Polling or webhooks — when would you use each?
- How do you secure and reliably process incoming webhooks?
60-second answer
A webhook is a reverse API call: I register a URL, and the provider POSTs an event to it when something happens, so I avoid polling and hear instantly. The three things I'd nail are security — verify the HMAC signature because the endpoint is public; reliability — expect retries, so make processing idempotent on the event ID; and speed — ack with a fast 200 and push the real work onto a queue. I'd use webhooks across company boundaries and internal pub/sub for my own services.
Common traps
- Trusting incoming webhooks without verifying the signature.
- Doing heavy work inline and timing out, triggering provider retries.
- Not handling duplicate deliveries idempotently.