Building a webhook receiver for event-driven automation¶
The REST-at-scale article frames webhooks as the efficient alternative to polling — you register a URL and the platform calls you the moment something happens — and the logging article shows your automation firing outbound webhooks into Slack or an incident tool. Both cover the sending side. This article builds the other half: the inbound endpoint that receives an event and turns it into action. Getting that endpoint right is mostly about three things the push model forces on you — run a reachable HTTPS endpoint, prove the request is genuine, and get off the request path fast.
The shape of a receiver¶
A webhook receiver is a small HTTP server exposing one route the platform POSTs to. The moment you accept inbound requests from the internet, three requirements follow: the endpoint must be a reachable HTTPS URL with a valid certificate; every request must be authenticated, because anyone who learns the URL can POST to it; and the handler must return a 2xx quickly, doing any real work asynchronously. Providers treat a slow or non-2xx response as a failed delivery and retry it, so blocking the response on a device push or a database write turns one event into a storm of duplicates.
A minimal Flask receiver captures that shape:
from flask import Flask, request, abort
app = Flask(__name__)
@app.post("/webhook")
def receive():
raw = request.get_data() # exact bytes, needed for the HMAC
if not verify(raw, request.headers):
abort(401) # reject before trusting anything
enqueue(request.get_json()) # hand off; don't work here
return "", 200 # acknowledge fast
Note the order: verify first, parse and enqueue second, return immediately. The handler never touches a device.
Prove the request is genuine¶
The URL is not a secret you can rely on — it ends up in logs, proxies, and configuration. Every serious provider gives you a way to verify the payload really came from them, and they fall into two families.
Signed-header HMAC is the common pattern. The provider computes an HMAC of the raw request body using a secret you both share and puts the digest in a header; you recompute it and compare.
- GitHub sends
X-Hub-Signature-256, asha256=-prefixed hex HMAC-SHA256 of the raw body (docs). - Cisco Webex sends
X-Spark-Signature, a hex HMAC-SHA1 of the raw body, but only when the webhook was created with a secret (Webex blog).
import hmac, hashlib, os
def verify(raw: bytes, headers) -> bool:
secret = os.environ["WEBHOOK_SECRET"].encode() # from env, never in code
expected = "sha256=" + hmac.new(secret, raw, hashlib.sha256).hexdigest()
got = headers.get("X-Hub-Signature-256", "")
return hmac.compare_digest(expected, got) # constant-time compare
Two details make or break this. Compute the HMAC over the raw bytes exactly as received — if you
parse the JSON and re-serialize it, the whitespace changes and the digest won't match, which is why
the Flask handler grabs request.get_data() before anything else. And compare with
hmac.compare_digest, not ==: a plain string
compare returns early on the first mismatched character, and the timing difference leaks the
signature one byte at a time.
Shared-secret-in-body is the simpler family. Cisco Meraki webhooks carry no signature header
at all; instead the JSON payload includes a sharedSecret field you compare against the value you
configured in the Dashboard (Meraki docs).
Here you do have to parse first, but the comparison is still constant-time:
def verify_meraki(payload: dict) -> bool:
expected = os.environ["MERAKI_SHARED_SECRET"]
return hmac.compare_digest(expected, payload.get("sharedSecret", ""))
Whichever family you're in, fail closed: if the secret isn't configured or the signature is missing, reject the request rather than waving it through.
Return fast, work asynchronously¶
The handler's only synchronous job is to verify and acknowledge. Everything expensive — pushing config, calling a controller API, running a playbook — belongs in a background worker. The receiver drops the validated event onto a queue and returns; a separate process picks it up:
# in the web handler — enqueue and return in milliseconds
def enqueue(event):
queue.put(event) # Redis/RQ, Celery, SQS, or an internal task queue
# in a worker process — the slow work runs here, off the request path
def worker():
for event in queue:
handle(event) # talk to devices, write to the database, etc.
This decoupling is what lets you absorb bursts and keeps a slow device from tripping the provider's delivery timeout.
Make the handler idempotent¶
Webhook delivery is at-least-once: when a provider doesn't get a prompt 2xx it retries, so the same event can arrive two or three times, and events can arrive out of order. The queue between your receiver and worker is usually at-least-once too, so the worker must also tolerate re-runs. The fix is the same property the idempotency article builds everything else on: processing an event twice must have the same effect as processing it once.
Most providers include a unique delivery or event ID. Record the ones you've handled and skip repeats:
def already_processed(event_id: str) -> bool:
# SET NX returns None if the key already exists → we've seen this event
return redis.set(f"webhook:{event_id}", "1", nx=True, ex=7 * 24 * 3600) is None
Give that record a time-to-live longer than the provider's retry window, or a late retry slips
past the dedup check. When the underlying work is naturally convergent — an idempotent Ansible run, a
PUT that replaces a resource, an upsert on a business key — you get much of this for free, and
webhooks become a trigger rather than a source of truth. For state that must be exactly right,
reconcile periodically against the provider's API instead of trusting the event stream alone.
Securing an inbound endpoint¶
An endpoint open to the internet is attack surface, so the secure-coding practices apply directly. Keep the signing secret and shared secret in environment variables or a vault, never in code. Serve only over HTTPS with a valid, CA-signed certificate (see CA-signed TLS certificates) so the payload and its secret aren't exposed in transit. Validate the payload against a schema before acting on it — a signature proves who sent the event, not that its contents are well-formed. And scope whatever the worker can do: an event that triggers a config push should run through the same dry-run and validation gates as any other change, because "the webhook told me to" is not authorization.
Key takeaways¶
- A webhook receiver is a small HTTPS server that must verify, acknowledge fast, and work asynchronously — never push config or hit a database on the request path.
- Authenticate every request. Signed-header HMAC (GitHub
X-Hub-Signature-256, WebexX-Spark-Signature) is computed over the raw body; shared-secret-in-body (MerakisharedSecret) is a field compare. Always usehmac.compare_digest, and fail closed. - Return a 2xx in milliseconds and hand the event to a queue; do the slow work in a worker so a slow device doesn't trip the provider's retry-and-duplicate behavior.
- Delivery is at-least-once and unordered — dedupe on the event ID with a TTL longer than the retry window, keep the work idempotent, and reconcile against the API for state that must be exact.
- Treat the endpoint as attack surface: secrets from the environment, HTTPS with a real certificate, schema-validate the payload, and gate any change the worker makes.
Sources: GitHub — Validating webhook deliveries,
Cisco Webex — Using a webhook secret,
Cisco Meraki — Webhooks introduction,
Python hmac module,
Flask — request data.