A webhook is often presented as “POST some JSON to this URL.” In production it is a message protocol crossing a trust boundary. Connections fail after the receiver commits, responses disappear, operators redeliver old events, and two workers can process the same delivery concurrently. Design for at-least-once delivery; make each business effect effectively once.

Authenticate the bytes before the object

Require HTTPS, cap request headers and body size, and read the body as raw bytes. Verify the provider’s documented signature over those exact bytes before JSON parsing, Unicode normalization, decompression, or framework reserialization. GitHub’s current scheme, for example, uses HMAC-SHA-256 over the payload and recommends a constant-time comparison. A normal string equality check can expose timing information.

The signature key belongs in a secret manager, never in the callback URL, logs, traces, or error bodies. Identify which key was used without revealing it. Rotation needs an overlap period: verify against the current and previous key, record the matched key ID, then retire the previous key after the provider has switched. An IP allow list can reduce noise, but it supplements cryptographic authentication because address ranges and network paths change.

Reject missing or malformed signatures before expensive work. Return the same small error shape for every authentication failure so the endpoint does not become a key oracle. Parsing and schema validation happen only after authenticity, with an explicit event type, schema version, and allowlist of supported actions.

A valid signature can still be a replay

Possession of a captured request and its valid signature does not prove freshness. RFC 9421 discusses signing sufficient message components and using created, expires, and a unique nonce to constrain replay. If a provider supplies a signed timestamp, enforce a documented clock-skew window using synchronized clocks. Do not invent a timestamp header that the signature does not cover.

Also store the provider’s stable delivery or event ID under a unique constraint scoped by provider and subscription:

deduplication key = provider + subscription + delivery_id

Retain that key for longer than the provider’s automatic retry window and any supported manual replay window. A duplicate should return the same successful acknowledgement once the original was durably accepted. A timestamp window alone is insufficient: an attacker can replay many times inside it, while a deduplication table alone cannot reject a previously unseen but years-old signed request.

Acknowledge durable acceptance, not completed business work

Keep the public request path short:

  1. Bound and authenticate the raw request.
  2. Validate required envelope fields.
  3. Insert an inbox row under the unique deduplication key.
  4. Commit the payload or encrypted reference and enqueue work atomically.
  5. Return a 2xx response.

Use a database-backed inbox, transactional outbox, or broker operation with equivalent durability. Never return success and then rely on an in-memory task: a process crash would lose an event the sender now considers delivered. Conversely, if durable storage is unavailable, return a retryable failure instead of acknowledging work that cannot be recovered.

202 Accepted means the request was accepted for processing, not that the business action succeeded. It is appropriate only after the handoff is durable. Do not hold the HTTP response open for downstream APIs, email, or a long transaction. GitHub, for example, currently expects a 2xx response within ten seconds and recommends asynchronous processing; every provider has its own deadline.

Make the effect idempotent

Deduplicating ingress stops the same delivery record from being created twice, but a worker can still crash after changing business state and before marking the row complete. The handler itself needs an idempotency boundary. Put the event transition and processed marker in one database transaction, or give the downstream operation a stable idempotency key.

Prefer state transitions that verify the expected previous state. “Set invoice 42 to paid for payment event P” is safer than “increment paid count.” Enforce unique business facts—such as one refund per refund ID—with database constraints. Record outcomes so a duplicate can become a no-op rather than repeating email, credit, or fulfillment.

Do not assume delivery order. Retries can let event 12 arrive after event 13. Include an object version or sequence when the producer offers one, reject stale transitions, and fetch authoritative state when an event is only a notification. Partition queues by object only when ordered processing is truly required; global ordering destroys useful concurrency.

Retry with a finite policy

For an outgoing webhook, retry network failures, timeouts, 408, 429, and selected 5xx responses with exponential backoff and jitter. Honor Retry-After when the receiver provides it, subject to a documented maximum. Do not retry permanent authentication, routing, or schema failures indefinitely. Set maximum attempts and event age, and limit concurrency per destination so one failing subscriber cannot consume the whole worker fleet.

Each attempt keeps the same delivery ID but gets its own attempt number, timestamps, response code, and bounded response excerpt. The receiver may have committed even when the sender did not receive 2xx, so a timeout is always an ambiguous outcome, never proof that nothing happened.

After the retry budget, move the delivery to a dead-letter state rather than deleting it. An operator can inspect the reason, repair configuration, and replay it. Replay creates a new attempt for the same logical delivery and must pass through the same signature, schema, deduplication, and idempotency rules. Audit who replayed what and why.

Treat destination URLs as untrusted input

If customers configure webhook URLs, the sender is also an SSRF surface. Require HTTPS, normalize and validate the URL, resolve DNS through controlled egress, block loopback, link-local, private, metadata, and internal service ranges, and re-check after redirects and DNS changes. Set connection, TLS, response-header, and total deadlines; cap redirects and response bytes. Give every subscription its own secret so one compromised receiver cannot forge another subscription’s traffic.

Operate the protocol, not just the endpoint

Measure accepted, rejected, duplicate, queued, processed, retried, exhausted, and manually replayed deliveries. Track signature failures by key ID, queue lag, oldest pending age, processing duration, attempt count, destination status, and final outcome without indexing raw sensitive payloads. Alert on lag and terminal failures, not merely HTTP request count.

Tests should send altered bytes with an old signature, stale timestamps, concurrent duplicates, out-of-order versions, both keys during rotation, and an oversized body. Crash a worker after the business commit but before acknowledgement; drop the sender’s copy of a successful response; make a receiver slow, return 429 with Retry-After, and recover after dead-lettering. The invariant is that no accepted event is lost and no retry creates a second irreversible effect.

A dependable webhook system therefore has two separate promises: the transport keeps trying within a finite, observable policy, and the consumer makes repeated delivery safe. Signatures establish origin and integrity; durable inboxes, idempotent state changes, bounded retries, and audited replay establish reliability.