Computing Foundations › APIs and the Web › Day 26

Day 26: Webhooks and Event-Driven APIs

Day 26 of 365 — Webhooks and Event-Driven APIs

After this lesson you will understand the shift from pull to push: what a webhook is, how to receive one safely by verifying a signature, how retries and idempotency keep delivery reliable, and how these ideas open onto event-driven architecture.

Course
Computing Foundations
Category
APIs and the Web
Reading time
≈ 40 min
Practical time
≈ 30 min
Lesson duration
1h 10m
Last verified
2026-07-12

Hands-on lab for this lesson

Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/computing-foundations/day-026-webhooks-and-event-driven-apis

  1. Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
    git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git
    cd ai-roadmap-365.github.io
  2. Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path — section / subsection / week / day:
    cd labs/sections/computing-foundations/day-026-webhooks-and-event-driven-apis
  3. Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work — read it before running anything.
  4. Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
    bash tests/run_tests.sh   # or the test command named in the lab README

You can also open the lab as a local page (works offline, shows the file tree and expected output).

Learning objectives

By the end of this lesson you will be able to:

Prerequisites

Why this matters


The idea in plain language

Diagram: polling versus webhooks, contrasting many repeated client requests with a single server callback


Historical background


What it is — and what it is not

It is:

It is not:


Why it was created and what problems it solves

Diagram: how many polling requests are wasted between real events


How it works

Anatomy of a delivery

Diagram: the parts of a webhook delivery and their purpose

Diagram: the life of one webhook delivery from event through signature check, acknowledgement, and retry

Securing the delivery

Diagram: relying on an unguessable URL compared with verifying a signature

Reliability

Diagram: slow inline processing compared with fast acknowledgement


An everyday analogy

Diagram: a typical webhook retry schedule

Waiting for a parcel.

The deliveryThe pattern
Phoning the depot every ten minutesPolling
Asking them to text you on arrivalA webhook
Your addressThe registered URL
Signing for the parcelReplying 200
No signature, so they come back tomorrowA retry
A courier ID you can checkThe HMAC signature
Two texts for one parcelAt-least-once delivery

Examples in practice

Diagram: the steps to verify a webhook signature

Diagram: polling compared with webhooks


Implications: security, privacy, performance, scalability, and cost

Diagram: how recording delivery identifiers makes repeated events safe


Alternatives: free, open source, and commercial

Diagram: how a tunnel exposes a local webhook receiver for testing

ApproachTypeWhere it fits
PollingBuilt inNo public address, low event rate, or simplicity matters most
WebhooksThe defaultPublic endpoint, events that matter promptly
WebSocketsBuilt inContinuous two-way streams, not discrete events
Server-sent eventsBuilt inOne-way streaming to a browser; how token streaming works
Message queuesFree, open sourceInternal systems, where ordering and replay matter
ngrok, smee.ioFree tiersReceiving webhooks on a laptop during development

TermWhat it actually is
WebhookAn HTTP callback triggered by an event
PollingAsking repeatedly whether anything has changed
PayloadThe JSON body describing what happened
HMACA keyed hash proving authenticity and integrity
At-least-onceDelivered one or more times, never zero
IdempotentSafe to process more than once
AcknowledgementYour 2xx, which stops the retries

When to use it — and when not to

Diagram: when to choose webhooks and when to choose polling


The AI connection


Knowledge check

quiz:
  question: "A webhook handler processes each event correctly, but occasionally applies the same event twice. Its logic is sound and the sender is reputable. What is the most likely cause?"
  options:
    - "The handler was slow to reply 2xx, so the sender timed out and retried an event that had already been processed"
    - "The sender is sending duplicate events because of a bug in its own queue"
    - "The signature check is passing for events that should have been rejected"
    - "Two instances of the handler are running and both received the same delivery"
  answer_index: 0
  explanation: "At-least-once delivery means the sender retries anything it did not hear a 2xx for. Work done before acknowledging — or simply a slow handler — leads to a timeout the sender reads as failure, so a successfully processed event is delivered again."

Hands-on exercise

Receive a real delivery, verify its signature, and prove a forged one is rejected. Worked through fully in the Day 26 lab directory.

What you are doingCommand
Run a local receiverpython3 -m http.server 8080 or the lab’s script
Expose it publiclyngrok http 8080
Send a delivery yourselfcurl -X POST -H 'Content-Type: application/json' -d @event.json URL
Compute an HMACopenssl dgst -sha256 -hmac "$SECRET" event.json
Send it with a signatureAdd -H "X-Signature: sha256=..."
Send a forged oneChange one byte of the body and resend the old signature
Compare in constant timehmac.compare_digest(a, b) in Python

Expected output

HMAC-SHA256(event.json)= 8f1c2a...e93b
[receiver] signature ok — event evt_28a7 accepted
[receiver] signature MISMATCH — rejected
[receiver] duplicate evt_28a7 — ignored

Validate your work

Troubleshooting

Common mistakes


Practice assignment


Extension challenge


Quiz

Q1. What is the essential difference between polling and a webhook?

  1. Polling uses HTTPS while webhooks use plain HTTP
  2. Polling asks repeatedly; a webhook is the server calling you
  3. Polling is only for browsers while webhooks are only for servers
  4. A webhook keeps a connection open permanently while polling closes it
Show answer

Answer: B. Polling asks repeatedly; a webhook is the server calling you

Polling is pull — your app keeps asking "anything new?" — while a webhook is push: the server makes an HTTP request to a URL you registered, at the moment the event occurs. That reversal is why a webhook is called a "reverse API."

Q2. Why is a webhook often described as a "reverse API"?

  1. Because it sends responses before requests
  2. Because the data travels backwards through the network stack
  3. Because your app receives the request instead of sending it
  4. Because it uses the DELETE method instead of GET
Show answer

Answer: C. Because your app receives the request instead of sending it

In a normal API call your code sends the request; in a webhook the roles are swapped — the other server sends the HTTP POST to your endpoint, and your application is the one that must listen and respond.

Q3. A webhook receiver replies with 200 OK. What does that status mean to the sending server?

  1. Nothing — webhook senders ignore the response status
  2. A request for the sender to send the event again
  3. That the receiver wants the payload in a different format
  4. The acknowledgement that the delivery was received, so the sender stops retrying
Show answer

Answer: D. The acknowledgement that the delivery was received, so the sender stops retrying

The sender treats a 2xx response as an acknowledgement ("received, thank you") and stops retrying. Anything else — a 4xx, 5xx, or timeout — is read as a failed delivery and triggers a retry.

Q4. Why must a webhook receiver verify the signature on an incoming delivery?

  1. The endpoint is public, so the signature proves it is authentic
  2. To measure how long the request took to arrive
  3. To decompress the payload before reading it
  4. Because the sender refuses to retry unsigned deliveries
Show answer

Answer: A. The endpoint is public, so the signature proves it is authentic

The URL alone proves nothing about who is calling — anyone who learns it can POST a forged event. A matching HMAC signature proves both authenticity (the caller knows the shared secret) and integrity (the body was not changed in transit).

Q5. How does an HMAC signature let a receiver detect a tampered payload?

  1. The signature includes a plain-text copy of the original payload
  2. Changing one byte produces a different signature, so it fails
  3. The receiver asks the sender to confirm the payload by email
  4. Tampered payloads are automatically rejected by the network
Show answer

Answer: B. Changing one byte produces a different signature, so it fails

The receiver recomputes the HMAC over the body it received using the shared secret and compares. Because a hash changes drastically when any input byte changes, an altered body yields a signature that shares nothing with the original — the mismatch reveals the tampering.

Q6. What does "at-least-once delivery" imply for how you must design a webhook handler?

  1. That every event is guaranteed to arrive exactly once and in order
  2. That you should poll as a backup in case the webhook never fires
  3. That the same event may arrive more than once, so the handler must be idempotent
  4. That the receiver must reply within one millisecond
Show answer

Answer: C. That the same event may arrive more than once, so the handler must be idempotent

Because senders retry until they get a 2xx, a delivery can arrive more than once (for example if your handler did the work but crashed before acknowledging). Idempotency — making repeated processing of the same event have the same effect as processing it once — is what prevents double charges and duplicate actions.

Q7. In event-driven architecture, what role does a message queue (broker) play?

  1. It replaces HTTPS with a faster custom protocol
  2. It converts JSON payloads into HTML for browsers
  3. It signs every webhook so receivers do not have to
  4. It stores events durably so producer and consumer need not overlap
Show answer

Answer: D. It stores events durably so producer and consumer need not overlap

A message queue is an intermediary that buffers events between producers (which emit events) and consumers (which handle them), adding durability, ordering, and replay that a bare webhook lacks — so a consumer that is briefly offline loses nothing.

Q8. Which push mechanism is the best fit for a continuous, two-way, real-time connection such as a chat app?

  1. A WebSocket
  2. Polling every few seconds
  3. Server-sent events (SSE)
  4. A single webhook callback
Show answer

Answer: A. A WebSocket

A WebSocket keeps one persistent connection open and lets both client and server send messages at any time, which suits interactive real-time apps. A webhook is a one-shot server-to-server callback, and SSE streams one-way from server to client only.

Glossary

webhook
An HTTP request that a server sends to a URL you registered in advance, to notify you that an event happened; because the server calls you, it is often described as a "reverse API."
polling
Repeatedly asking a server "has anything changed?" — the pull alternative to push, simple but wasteful because most requests return nothing and updates lag by the polling interval.
event
A discrete thing that happened on a server (a payment succeeded, a job finished, code was pushed) that a webhook or event-driven system reports so others can react.
payload
The body of a webhook delivery — a small JSON document describing the event, including its type, an identifier, a timestamp, and the relevant data.
producer
In event-driven architecture, a service that emits events (for example, the system where a payment settles) for others to consume.
consumer
In event-driven architecture, a service that receives and handles events emitted by producers (for example, your webhook receiver).
signature
A value (typically an HMAC computed over the raw body with a shared secret) attached to a webhook delivery so the receiver can prove the payload is authentic and unaltered.
HMAC
Hash-based message authentication code — a signature made by hashing a message together with a shared secret, used to verify a webhook came from someone who knows the secret and was not tampered with.
secret
A random string known only to the sender and receiver, used to compute and verify webhook signatures; a credential that must be kept out of source code and logs.
retry
The sender re-attempting a delivery (usually with growing gaps, called backoff) when it does not receive a 2xx acknowledgement, which is why the same event can arrive more than once.
idempotency
The property that processing the same event more than once has the same effect as processing it once; required because at-least-once delivery can deliver duplicates.
at-least-once delivery
A delivery guarantee that a sender will keep retrying until acknowledged, so an event arrives one or more times (possibly duplicated) rather than being silently lost.
acknowledgement
The 2xx response (typically 200 OK) a receiver sends back to confirm it accepted a delivery, telling the sender it can stop retrying.
message queue
Infrastructure that sits between producers and consumers, durably storing events so services can exchange them reliably with buffering, ordering, and replay.
server-sent events
A web standard (SSE) in which a server streams a sequence of events to a client over one long-lived, one-way HTTP connection.
WebSocket
A persistent, two-way connection over which client and server can both send messages at any time, used for interactive real-time applications.
event-driven architecture
A style of building systems in which services communicate by emitting and reacting to events (via webhooks, queues, or streams) rather than constantly asking one another for updates.

Sources and further reading


Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.