Skip to content
Index Ai Academy
Phase 8 · Security & reliability

Webhooks and events

Push events to other systems: signed, retried and deduplicated.

About 45 minutes · A free account opens the whole lesson.
Already have an account? Sign in to open this lesson

What it covers8

First principles

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.

  1. Starting point

    Receive a signed event E7

  2. What changes

    Verify it and store E7 alongside its effect

  3. Result

    A later delivery of E7 produces no second effect

Compare all three steps
  1. Starting point

    Receive a signed event E7

  2. What changes

    Verify it and store E7 alongside its effect

  3. Result

    A later delivery of E7 produces no second effect

Complete and reverse the trace

Given Receive a signed event E7 and A later delivery of E7 produces no second effect, write down the missing step that connects them.

Compare with the worked step

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.

Check one starting point

Receive a signed event E7. Check that your implementation produces the result shown above.

Try it on a new case

A receiver commits the event and loses the acknowledgement. What should the retry do?

Show worked reasoning

Confirm the already recorded event and acknowledge it. The durable ID lets the receiver avoid repeating the effect.

Run, change, and build

Check this when debugging. Verifying the signature against re-serialized JSON instead of the raw body.

Trace the cause · HTTP request, job, and result
  1. Identify the request, response, and any durable state. Predict the status or stored result before following the trace.
  2. Change one request property and keep the client contract visible. Compare the response and job state to explain the observed behavior.
  3. Try the same reasoning on this case. A receiver commits the event and loses the acknowledgement. What should the retry do?

Why it matters

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.

What you'll be able to do

  • Explain how webhooks flip the usual direction: the provider calls your server
  • Sign webhook payloads and verify them, with protection against replayed messages
  • Handle at-least-once delivery: duplicates, retries and out-of-order events
  • Design the sending side: event objects, retries, secrets and safe destinations, and refuse an internal address as a URL
Quick check
Instead of asking a payment provider "done yet?" every minute, what does a webhook do?
  1. The provider emails you a daily summary of payments
  2. The provider calls your URL the moment the payment finishes
  3. Your code downloads every payment once a night
  4. Your code asks every second instead of every minute
Show the answer

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.

The idea: the provider calls you

This rests on API styles, where a webhook was one of four ways to hear about changes.

Push instead of poll

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".

Quick check
With a webhook, who sends the HTTP request?
  1. Your code, once every few seconds
  2. The provider, to a URL you registered
  3. The customer's browser, on checkout
  4. Nobody: it is a database trigger
Show the answer

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.

Anyone can POST to a URL

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:

  1. The provider takes the current time t and the raw body bytes.
  2. It computes HMAC-SHA256(secret, f"{t}.{body}") and sends t and the signature in a header.
  3. You recompute the same HMAC and compare with 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.

Quick check
From the lesson on authentication: a signature is an HMAC of the exact bytes, made with a shared secret. What does this print: the check against the raw body, and against the body after it was parsed and written out again?
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)),
)
  1. True True
  2. False False
  3. False True
  4. True False
Show the answer

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.

At-least-once delivery

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:

  • Verify first. No valid signature, no processing: answer 400 (or 401).
  • Deduplicate by event id. Record each id you've handled. A repeat gets 200 without doing the work again. Answering 200 matters, because it tells the sender to stop retrying.
  • Answer fast. Providers time out in seconds. Save the event and do the slow work (emails, model calls) in a background job, then reply.
  • Don't trust order. Check the current state (for example, fetch the payment from the API) rather than assuming events arrive in sequence.

Combined, these make your handler idempotent: processing the same event twice has the same effect as once.

Try it now

Delivery is at least once. Handling the same event twice must do no harm.

In your own words
How do webhooks flip the usual direction, and what must your handler do about repeats?

Write a sentence or two, then compare it with a good answer in the lesson.

In Python: verify it, queue it, run it once

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]
    )
)
It runs right here in your browser, with nothing to install.
Quick check
Your framework parses the JSON body for you. Why should you verify the signature against the raw bytes, not json.dumps(parsed)?
  1. The raw bytes are encrypted, and only the encrypted form can be checked
  2. Signatures only work on text, not dicts, and json.dumps doesn't give text
  3. json.dumps is too slow to run on every webhook that arrives at a busy endpoint
  4. Re-encoding can change spacing or key order, so the bytes and the signature no longer match
Show the answer

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.

Quick check
What does this print?
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)
  1. 2
  2. 3
  3. 0
  4. 1
Show the answer

2

The repeat of e1 still gets a 200, but the work is only done once.

Drill

Process each event 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
    )
)
In the lesson, your code is checked as you write it.

Answer fast, work later

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.

Worked example

Rotating a webhook secret

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")
In the lesson you can change this and run it.

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.

Quick check
A webhook handler sends an email and calls a model before it answers, and the provider times out waiting. What happens next?
  1. The provider waits as long as the handler needs to finish its work
  2. The provider drops the event, and it is lost for good
  3. The provider sends the event again while the first run is still working
  4. The provider reaches in and cancels the work the handler started
Show the answer

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.

In your own words
Why verify the raw bytes, and why answer fast and work later?

Write a sentence or two, then compare it with a good answer in the lesson.

In AI and ML systems: events from batch jobs and the URLs you accept

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.

An attack to try: an internal address as a webhook 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.

Quick check
A customer registers https://metadata.customer.test/latest as a webhook URL, and that name points at 169.254.169.254. What should your sender do?
  1. Send it: the scheme is HTTPS
  2. Send it once to see what happens
  3. Refuse it: the address is not public
  4. Send it, but with no payload
Show the answer

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.

The sending side

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.

Drill

When to stop sending

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))
In the lesson, your code is checked as you write it.

Where this shows up in an engineer's week

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.

Portfolio brief

A checkout with a payment provider

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.

It must

  • 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 1
  • handle_webhook(headers, body) verifies the signature with hmac.compare_digest and rejects events older than five minutes
  • A genuine payment.succeeded event marks the order paid only if the amount matches; payment.failed marks it failed
  • The same event delivered twice changes nothing the second time
  • Tests for a good payment, a failed one, a forged signature, a replayed event and a wrong amount

Go further

  • Refunds: a payment.refunded event moves a paid order to refunded, and nothing else
  • Wrap both handlers in a small Flask app (taught later, in Web pages with Flask and Jinja templates), and test them with its test client
  • Log every event you reject, with the reason, without logging the signature or secret
import 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}]))
In the lesson, you build it here and the tutor can review it.
In your own words
What must a webhook sender check about a customer's URL, and why check the address and not the name?

Write a sentence or two, then compare it with a good answer in the lesson.

Choose how to practice

Start with a short baseline or choose guided, independent, or AI-assisted practice.

Practice what you just read

  • 4 code examples you can edit and run
  • a practice exercise that checks your code
  • a 5-question quiz
  • 8 review cards for spaced repetition

Try a quiz question

Why do webhook signatures include a timestamp?

  1. So an attacker can't record a real webhook and replay it later
  2. So the receiver knows the time zone the event came from
  3. To make the signature longer, and harder to guess by chance
  4. Because HMAC needs a number to work with, as well as the text

Answer it at the end of the lesson to see if you're right, and why.

Before this lesson

Keep learning

Where this lesson leads.

575 lessons in thirteen phases. 176 are free without an account, and a free account opens the rest. See every lesson.

Phase 8 · about 23 hours of study

APIs

Design, build, secure and scale web APIs from first principles 27 lessons 1 free
  1. HTTP from the wire up FreeWhat really travels between client and server: bytes, headers and bodies.40 min
  2. API stylesREST, RPC, GraphQL, gRPC and streaming: what each is for.35 min
  3. Build an API server from scratchRouting, handlers and responses, with no framework.45 min
  4. A web framework, from the insideDecorators, middleware and error handling: how Flask and FastAPI work.40 min
  5. Designing a REST APIResources, methods, status codes, errors and pagination done well.45 min
  6. Validating requests with schemasCheck every request against a JSON Schema and say exactly what's wrong.45 min
  7. A database-backed APICRUD endpoints on SQLite, with safe concurrent updates.45 min
  8. Authentication and authorizationAPI keys, sessions, tokens and OAuth: who's calling, and what may they do?45 min
  9. Rate limits, retries and idempotencyKeep an API up under load and make retries safe.45 min
  10. Async HTTP clientsMany requests at once with asyncio and httpx: limits, timeouts and retries.45 min
  11. Webhooks and eventsPush events to other systems: signed, retried and deduplicated.45 min
  12. Documenting APIs with OpenAPIA machine-readable contract for docs, SDKs and AI tools.40 min
  13. Running APIs in productionVersioning, CORS, caching, request ids and health checks.45 min
  14. Project: a reviews APIAn authenticated, validated, paginated API with tests.45 min
  15. Web pages with FlaskRoutes, Jinja templates, a shared layout, links and error pages, tested with the test client.45 min
  16. Forms and redirectsGET and POST, validation messages, post/redirect/get, flash messages and CSRF tokens.45 min
  17. Accounts and loginsPassword hashing with bcrypt, sessions, pages that need a login, and safe logout.45 min
  18. Project: a trail log web appA multi-page app with a database, accounts, forms and tests.45 min
  19. JavaScript for Python programmersVariables, functions, arrays and objects mapped from Python, and the traps: truthy empty arrays, for...in and string sort.35 min
  20. Async JavaScript: promises, await and fetchThe event loop, async and await, fetch with res.ok checks, Promise.all, and timeouts with AbortController.35 min
  21. Modules, Node and reading TypeScriptimport and export, package.json, classes, and types as notes the compiler checks, read through a small tool server.30 min
  22. A chat front end in the browserThe DOM and events, model text kept out of innerHTML, a streamed reply parsed from server-sent events, and a Stop button.40 min
  23. APIs with FastAPITyped routes, pydantic models, automatic validation and docs, tested with httpx.45 min
  24. Streaming from the serverServer-sent events written by a server: an ASGI app that sends a body in pieces, FastAPI's StreamingResponse, heartbeats, and what a closed connection looks like.40 min
  25. Project: a FastAPI service with accountsA session per request, bcrypt sign-ups, signed tokens, ownership checks and tests on a fresh database.45 min
  26. Serving a model behind FastAPILoad once with lifespan, a typed predict route, a batch route, a cap on work in flight, 429 with Retry-After, a readiness route and a 202 job.45 min
  27. Capstone: a streaming chat serviceA FastAPI service with key auth, a per-user bucket, a token budget, request ids and an event-stream reply, tested on fresh state.45 min
Part of a free course 127 lessons

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.

Part of a free course 20 lessons

Build and Operate HTTP APIs

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