FROMDEV

How to Implement Webhooks Securely: Signatures, Retries, and Idempotency

How to Implement Webhooks Securely: Signatures, Retries, and Idempotency

Build a Reliable Webhook Receiver: A Practical Security Guide

Webhooks let one application notify another when an event happens, without requiring the receiver to repeatedly poll an API. But a public endpoint also creates security and reliability challenges: requests may be forged, delivered more than once, or arrive out of order. A secure webhook implementation addresses all three.

This guide walks through the essentials: verify a cryptographic signature against the exact request body, acknowledge valid deliveries quickly, retry temporary failures with backoff, and make processing idempotent. The examples use Node.js-style pseudocode, but the principles apply across languages and frameworks.

How a secure webhook receiver should work

A robust receiver separates accepting a delivery from doing the work it describes. Its basic flow is:

  1. Read the raw request body, subject to a reasonable size limit.
  2. Verify the provider’s signature and timestamp, if supported.
  3. Validate the event’s structure and required fields.
  4. Record the event durably, using a unique event ID to prevent duplicate processing.
  5. Return a success response promptly, then process the event asynchronously.

This design limits exposure to forged requests and avoids making the sender wait for slow downstream work. It also makes retries safe: if the same delivery arrives again, your system can recognize it rather than repeat a payment, email, or account change.

Verify webhook signatures correctly

Webhook signatures prove that a request was created by a party holding a shared secret, and that the signed content has not changed in transit. Most providers use an HMAC, commonly HMAC-SHA-256. The provider’s documentation is authoritative: header names, signature format, timestamp rules, and signed data can differ.

Sign and verify the exact raw body

Compute the HMAC over the exact bytes specified by the provider—often the raw request body, sometimes a timestamp concatenated with the body. Do not parse and re-serialize JSON before verification. Whitespace, property order, escaping, or character encoding can change the bytes and invalidate the signature.

Frameworks often parse JSON automatically. Configure the webhook route to preserve the raw body, or capture it before parsing. Here is simplified Node.js pseudocode for a provider that sends a hexadecimal HMAC in an X-Webhook-Signature header:

import { createHmac, timingSafeEqual } from "node:crypto";

function verifySignature(rawBody, suppliedHex, secret) {
  if (!/^[0-9a-f]{64}$/i.test(suppliedHex)) return false;

  const expected = createHmac("sha256", secret)
    .update(rawBody)
    .digest();

  const supplied = Buffer.from(suppliedHex, "hex");

  return supplied.length === expected.length
    && timingSafeEqual(supplied, expected);
}

This is an illustrative format, not a universal webhook standard. Some providers prefix the digest, use base64, or sign a timestamp plus the body. Follow the provider’s algorithm precisely, reject malformed signatures, and use a constant-time comparison rather than ordinary string equality where your platform supports it.

Protect against replay attacks

A valid signature could be copied and sent again. If the provider includes a signed timestamp, reject requests outside a small, documented tolerance window, allowing for reasonable clock skew. Use synchronized system clocks and avoid excessively broad windows. A timestamp check limits replay opportunities, but does not replace event-level deduplication: a legitimate retry may also be a repeated delivery.

Signature verification is one part of API defense, not a substitute for input validation or authorization. For a broader security-testing perspective, see FromDev’s guide to why API security testing matters for scalable and secure applications.

Make event processing idempotent

Webhook providers commonly deliver at least once: if they do not receive a successful response, they may send the same event again. Network timeouts can also leave the sender unsure whether your receiver completed its work. Design for duplicates instead of assuming every event arrives exactly once.

Use a stable event ID and a durable record

If the provider supplies a unique event ID, store it with a uniqueness constraint in your database. A typical flow is to insert the event into an inbox table and enqueue it for processing. If the ID already exists, treat the delivery as a duplicate and return success once the existing event is safely recorded.

BEGIN;

INSERT INTO webhook_inbox (provider, event_id, payload, status)
VALUES ('example', :event_id, :payload, 'pending')
ON CONFLICT (provider, event_id) DO NOTHING;

COMMIT;

The exact SQL varies by database. The important detail is that deduplication is enforced durably and atomically, not only with an in-memory check that disappears on restart. If no stable event ID is available, ask the provider what identifier it recommends. A payload hash may help in limited cases, but distinct legitimate events can have identical payloads, so it is not a universal substitute.

Make side effects safe too

Recording an event once does not automatically make every downstream action exactly once. A worker might charge a card successfully and crash before marking the event complete. On retry, it could charge again. Where a downstream service supports idempotency keys, pass a stable key derived from the event or business operation. Otherwise, use transactional state changes, unique business constraints, or reconciliation procedures.

A useful rule is to make the “already processed” check and the corresponding database change part of one transaction whenever possible. For external services, exactly-once effects are generally not guaranteed by a webhook receiver alone. Idempotency reduces duplicates; it does not eliminate every failure boundary.

Handle retries without creating a retry storm

A webhook sender typically retries when it receives a timeout or a non-success status. Retry schedules vary by provider, so consult its documentation rather than assuming a specific number of attempts or response codes. Your receiver should distinguish temporary failures from permanent rejection and respond quickly when it has safely accepted an event.

Acknowledge first, process asynchronously

After signature and basic validation, persist the event to a durable queue or inbox and return the provider’s expected success status. A worker can then perform slower work, such as calling another API or updating several systems. Do not return success before the event is durably recorded: if the process crashes immediately afterward, the sender may stop retrying and the event can be lost.

If you cannot safely persist the event—for example, the database is unavailable—return a failure response so the sender can retry. Keep the request handler’s work bounded, and ensure queue insertion and inbox recording have clear recovery behavior.

Use backoff in your own processing queue

If your worker calls a dependency that is temporarily unavailable, retry internally with exponential backoff and jitter. For example, increase the delay after each failure while adding randomness so many workers do not retry at exactly the same time. Set a maximum delay and attempt count, then move exhausted events to a dead-letter queue or an alertable failure state.

Provider retries and your worker retries are separate mechanisms. A prompt acknowledgment after durable acceptance prevents the provider from retrying while your own queue handles downstream failures.

Validate, monitor, and test the endpoint

A valid signature does not mean every field is safe or relevant. Validate the payload against expected types and required fields, allow only supported event types, and avoid trusting user-controlled values in database queries or shell commands. Keep the endpoint’s permissions narrow: a delivery should trigger only the actions required for that event.

Monitor delivery volume, signature failures, duplicate events, queue depth, processing latency, and dead-letter counts. Avoid putting full payloads or sensitive data in ordinary logs. Include correlation IDs so a delivery can be traced from the HTTP request through the worker and any downstream calls.

Test the failure paths, not just a successful sample. A useful checklist includes:

Security reviews often uncover bugs at boundaries where data is copied, transformed, or retried. That is a useful mindset beyond webhooks: FromDev’s tutorials on implementing a custom memmove in C and understanding memmove’s internal implementation illustrate why careful handling of data and edge cases matters at a lower level, too.

Common webhook security pitfalls

Conclusion

A secure webhook receiver verifies the provider’s signature over the exact bytes the provider signed, applies replay protections when available, and validates every event before acting on it. It records deliveries durably, deduplicates them with stable IDs, acknowledges only after safe acceptance, and processes work asynchronously with bounded retries and clear failure handling.

There is no single header or library that makes a webhook secure. Security and reliability come from combining authentication, input validation, idempotency, durable queues, monitoring, and tests for failure cases. Build those safeguards into the endpoint from the start, and webhook integrations become far easier to operate safely as traffic and dependencies grow.

Exit mobile version