Free Python developer course
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Push events to other systems: signed, retried and deduplicated.
Why can a correctly delivered event arrive more than once?
Senders retry when they cannot confirm delivery. Receivers verify the signature before processing and use a durable event ID to recognize repeat deliveries.
Receive a signed event E7
Verify it and store E7 alongside its effect
A later delivery of E7 produces no second effect
Receive a signed event E7
Verify it and store E7 alongside its effect
A later delivery of E7 produces no second effect
Given Receive a signed event E7 and A later delivery of E7 produces no second effect, write down the missing step that connects them.
Verify it and store E7 alongside its effect
Now take Verify it and store E7 alongside its effect and the result above. Write an input and an implementation that could produce this trace.
Receive a signed event E7. Check that your implementation produces the result shown above.
A receiver commits the event and loses the acknowledgement. What should the retry do?
Confirm the already recorded event and acknowledge it. The durable ID lets the receiver avoid repeating the effect.
Check this when debugging. Verifying the signature against re-serialized JSON instead of the raw body.
Payments succeed, forms get submitted, automated test runs finish, a model batch completes. The systems that know first tell yours by webhook: an HTTP request to a URL you gave them. Webhooks drive most real automations, including AI ones that react to a new email or a closed deal. They're also an open door, because your endpoint is public and anyone can POST to it. This lesson makes it safe and correct.
The provider calls your URL the moment the payment finishes
A webhook flips the direction: the system that knows first sends an HTTP request to a URL you gave it. You must check its signature and handle repeats, which this lesson covers.
This rests on API styles, where a webhook was one of four ways to hear about changes.
On a long car trip, a child keeps asking "are we there yet?" Your code does the same with an ordinary API: "has the payment finished yet?" Asking every few seconds is called polling. It's slow to notice changes, and wasteful when nothing has changed.
A webhook reverses it, like leaving your number so a restaurant can text you when your table is ready. You register a URL with the provider, and when something happens, the provider sends an HTTP POST there:
POST /webhooks/payments HTTP/1.1
Host: shop.example
Content-Type: application/json
Shop-Signature: t=1793001234,v1=ca92d994...9f21
{"id": "evt_8Qz", "type": "payment.succeeded", "created": 1793001234, ...}
Each event has an id, a type, a time, and the data. Your endpoint answers 200 to say "got it".
The provider, to a URL you registered
A webhook reverses the usual direction. When something happens, the provider POSTs to your endpoint, and you answer 200.
Your webhook endpoint is on the public internet. An attacker who finds it can send a fake payment.succeeded and get goods for free. So providers sign each webhook with a secret that only you and they know. Think of a wax seal: only the holder of the stamp can make it, and any tampering shows. A common scheme uses HMAC, a fingerprint that takes a secret to make:
t and the raw body bytes.HMAC-SHA256(secret, f"{t}.{body}") and sends t and the signature in a header.hmac.compare_digest. A mismatch means you reject.Including the time in what's signed blocks replay attacks. An attacker who copies one real webhook could otherwise resend it forever, like photocopying a valid ticket. You reject any message whose t is more than a few minutes from now.
In plain words: the signature proves the message really came from the provider and wasn't changed. The time proves it's recent.
import hashlib, hmac, json secret = b"whsec_demo" raw = b'{"id": "evt_1", "type": "order.created"}' def sign(data): return hmac.new(secret, data, hashlib.sha256).hexdigest() signature = sign(raw) rewritten = json.dumps(json.loads(raw)).encode() print( hmac.compare_digest(signature, sign(raw)), hmac.compare_digest(signature, sign(rewritten)), )
True False
The raw body has two spaces after its comma, and json.dumps writes one. The data is the same and the bytes are not, so the fingerprint differs. A webhook handler has to verify the bytes exactly as they arrived, before any parsing.
A courier who gets no signature comes back with the parcel the next day. Providers do the same. They retry when they don't get a 2xx: after a timeout, a 500, or a network error, often with backoff over hours or days. So delivery is at least once. The same event can arrive two or more times, for example when your 200 was lost on the way back. Events can also arrive out of order, like two letters crossing in the mail: payment.refunded before payment.succeeded.
The receiving rules follow from that:
200 without doing the work again. Answering 200 matters, because it tells the sender to stop retrying.Combined, these make your handler idempotent: processing the same event twice has the same effect as once.
Delivery is at least once. Handling the same event twice must do no harm.
Write a sentence or two, then compare it with a good answer in the lesson.
First the signature, with the time in what is signed. The cell builds a header, then checks it from the raw bytes, and fails it for a body someone edited.
Run the signing and the check once on a known body: the header the sender builds, then the receiver comparing it with its own.
import hashlib, hmac secret = b"whsec_test_secret" # The body of the webhook above, byte for byte body = ( b'{"id": "evt_8Qz", "type": "payment.succeeded", "created": 1793001234, ' b'"data": {"order": "ord_51", "amount": 4900}}' ) def signature(t, body): return hmac.new(secret, f"{t}.".encode() + body, hashlib.sha256).hexdigest() t = 1793001234 header = f"t={t},v1={signature(t, body)}" print(header) # Receiver: recompute from the raw bytes it received, then compare. received_t = int(header.split(",")[0][2:]) print(hmac.compare_digest(signature(received_t, body), header.split("v1=")[1])) print( hmac.compare_digest( signature(received_t, body.replace(b"8Qz", b"FAKE")), header.split("v1=")[1] ) )
json.dumps(parsed)?Re-encoding can change spacing or key order, so the bytes and the signature no longer match
The signature covers exact bytes. Parsing and re-serializing rarely reproduces them, so valid webhooks would fail (or tampered ones could slip through a sloppy comparison).
The stepper runs a complete verify: the time first, since a stale message is rejected without computing anything, then the HMAC compared in constant time. Watch the three calls end three different ways.
handled = set() work = 0 for event_id in ["e1", "e1", "e2"]: if event_id in handled: continue handled.add(event_id) work += 1 print(work)
2
The repeat of e1 still gets a 200, but the work is only done once.
Webhooks arrive at least once, so the same event can come twice. Write handle_batch(events, seen): for each event (a dict with id), skip it if its id is in the set seen; otherwise add the id to seen and record it. Return the list of ids you processed, in order.
def handle_batch(events, seen): return [e["id"] for e in events] seen = {"evt_1"} print( handle_batch( [{"id": "evt_1"}, {"id": "evt_2"}, {"id": "evt_2"}, {"id": "evt_3"}], seen ) )
A receptionist signs for a parcel and opens it later. Providers wait only a few seconds for your reply, and a slow handler, one that sends an email and calls a model before it answers, times out. The provider then thinks delivery failed and sends the event again while your work is still running. So save the event, answer 200 at once, and do the slow work in the background. A list stands in for a queue here, and a loop for the worker.
queue = [] done = [] def receive(event): queue.append(event) # save it, then answer at once return 200 def worker(): while queue: event = queue.pop(0) done.append(event["id"]) # the slow work happens here print([receive({"id": f"evt_{n}"}) for n in range(3)]) print("queued:", len(queue), "done:", len(done)) worker() print("queued:", len(queue), "done:", done)
The three replies went out while nothing had been done yet. The worker then ran all three. Caches, queues and background jobs swaps the list for Redis and the loop for a separate process.
During a secret rotation, the provider signs with both the old and the new secret, sending two v1 values. The receiver accepts the message if any of them matches.
import hashlib, hmac def sig(secret, t, body): return hmac.new(secret, f"{t}.".encode() + body, hashlib.sha256).hexdigest() old, new = b"whsec_old", b"whsec_new" body, t = b'{"id": "evt_1"}', 1793001234 header = f"t={t},v1={sig(old, t, body)},v1={sig(new, t, body)}" parts = [p.split("=", 1) for p in header.split(",")] candidates = [v for k, v in parts if k == "v1"] for mine in (old, new, b"whsec_wrong"): ok = any(hmac.compare_digest(sig(mine, t, body), c) for c in candidates) print(mine.decode(), "->", "accepted" if ok else "rejected")
Receivers that already switched to the new secret and ones still on the old secret both accept. That's how a secret is changed without dropping a single event. Afterwards the provider signs with the new one only.
The provider sends the event again while the first run is still working
The provider thinks delivery failed and retries, so the same work can run twice. Save the event, answer 200 at once and do the slow work in the background, and make the work safe to repeat.
Write a sentence or two, then compare it with a good answer in the lesson.
A batch of model calls, a fine-tuning run or an evaluation takes minutes or hours, so the provider tells you by webhook when it finishes. The event follows this lesson's shape: a signed POST, an id you record, a repeat you answer with 200. Two patterns suit AI work. A thin payload carries only the job id and the type, and your handler fetches the result from the authenticated API, so no data travels by webhook and order stops mattering. And the sending side matters when your product notifies a customer's system, because the customer chooses the URL.
If customers choose where you send webhooks, someone will enter http://169.254.169.254/, a cloud server's metadata address, or https://localhost:6379, hoping your server calls your own internal systems and hands back what it finds. This is SSRF, server-side request forgery. The defense checks the address the name points to, not the name: allow only HTTPS, resolve the host, and refuse any address that is not public. A pretend resolver stands in for DNS here.
import ipaddress from urllib.parse import urlsplit FAKE_DNS = { "hooks.customer.test": "93.184.216.34", "metadata.customer.test": "169.254.169.254", "redis.customer.test": "10.0.0.5", "localhost": "127.0.0.1", } def safe_url(url): parts = urlsplit(url) if parts.scheme != "https" or not parts.hostname: return False address = ipaddress.ip_address(FAKE_DNS[parts.hostname]) return address.is_global for url in [ "https://hooks.customer.test/in", "http://hooks.customer.test/in", "https://metadata.customer.test/latest", "https://redis.customer.test/", "https://localhost/x", ]: print(safe_url(url), url)
Only the first URL is safe. The second is plain HTTP, and the others point at a link-local, a private and a loopback address, even though two of them look like harmless names. Check the address again at each delivery, and connect to the address you checked, since a name can be changed to point inward after you looked.
https://metadata.customer.test/latest as a webhook URL, and that name points at 169.254.169.254. What should your sender do?Refuse it: the address is not public
The name looks harmless but the address is internal. Checking the address the name resolves to, not the name, is what stops the request reaching your own systems.
If your product sends webhooks, you are the provider. Give events a stable shape: id, type (order.created), created and data, and document every type. Retry with backoff for a day or more, then mark the endpoint as failing and tell its owner. Use one secret per endpoint, shown once, with a way to rotate it. Keep each customer's queue separate so one dead endpoint cannot hold up the rest. A published standard, Standard Webhooks, names the headers webhook-id, webhook-timestamp and webhook-signature, so receivers can use ready-made libraries.
A sender shouldn't hammer an endpoint that's down forever. Write endpoint_status(results, max_failures): results lists each delivery attempt in order, True for success. Return "disabled" as soon as max_failures failures happen in a row (a success resets the run), otherwise "active".
def endpoint_status(results, max_failures): return "disabled" if results.count(False) >= max_failures else "active" print(endpoint_status([False, False, True, False, False], 3))
Four failures show up. A signature that never matches because the handler parses the JSON first and verifies a re-encoded copy. Double work because a lost 200 brought a repeat and nothing recorded the id. Timeouts because the handler does the slow work before it answers. A request to an internal address because a customer's URL was never checked. Each is a rule from this lesson, and each is a few lines of code. A good habit is to keep a few real events, signatures included, and replay them in your tests, so you catch these without waiting for the provider to send anything. Goes deeper in: Caches, queues and background jobs adds a real queue and worker, Rate limits, retries and idempotency covers the sender's retries and backoff, and Streaming, interrupts and sessions shows long runs reporting back the same way.
Build the checkout side of an online shop, against a pretend payment provider called FakePay that's included in the starter. The flow is the one real providers use: your service creates an order and asks FakePay for a payment; later, FakePay sends your webhook endpoint a signed event saying whether the payment succeeded.
Everything that makes this hard in real life is here on purpose. Prices come from your own catalog, never from the request. Webhooks can arrive twice, late, or forged. And an order must only become paid when a genuine, recent payment.succeeded event for exactly the right amount says so. Handlers are plain functions, so you can test every case directly.
checkout(cart) prices the items from CATALOG (in whole cents), creates a pending order and a FakePay payment, and rejects unknown SKUs or quantities below 1handle_webhook(headers, body) verifies the signature with hmac.compare_digest and rejects events older than five minutespayment.succeeded event marks the order paid only if the amount matches; payment.failed marks it failedpayment.refunded event moves a paid order to refunded, and nothing elseimport hashlib import hmac import json import time SECRET = "whsec_demo_not_a_real_secret" CATALOG = {"TE-101": 17000, "ST-114": 4500, "LA-102": 3900} # prices in cents class FakePay: """A pretend payment provider. It takes payments, then tells your app what happened in a signed webhook.""" def __init__(self, secret=SECRET): self.secret = secret self.payments = {} self.sent = 0 def create_payment(self, order_id, amount): pid = f"pay_{len(self.payments) + 1:04d}" self.payments[pid] = { "id": pid, "order_id": order_id, "amount": amount, "status": "pending", } return dict(self.payments[pid]) def event(self, pid, kind="payment.succeeded", amount=None): """The webhook FakePay would send: (headers, body) for your handler.""" self.sent += 1 payment = dict( self.payments[pid], amount=self.payments[pid]["amount"] if amount is None else amount, ) body = json.dumps( {"id": f"evt_{self.sent:04d}", "type": kind, "payment": payment} ).encode() t = int(time.time()) signature = hmac.new( self.secret.encode(), f"{t}.".encode() + body, hashlib.sha256 ).hexdigest() return {"FakePay-Signature": f"t={t},v1={signature}"}, body pay = FakePay() orders = {} def checkout(cart): return {"error": "not built yet"} # your code def handle_webhook(headers, body): return 501 # your code: verify, ignore repeats, update the order print(checkout([{"sku": "TE-101", "qty": 1}]))
Write a sentence or two, then compare it with a good answer in the lesson.
Start with a short baseline or choose guided, independent, or AI-assisted practice.
Why do webhook signatures include a timestamp?
575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.
Go from your first line of code to working as a Python developer: projects, testing, data, databases, web apps and APIs, all in your browser.
Design, test, deploy, and operate an HTTP API that another engineer can use.
Never trained an AI? Teach a small one to write, right in your browser. It takes about 20 seconds and needs no account. Teach it to write