Webhooks are appealing because they promise “real time” integration: an outside system calls your endpoint when something changes, and your app reacts. For small teams, webhooks can replace scheduled polling jobs and reduce API usage.
The catch is that webhooks turn reliability into your problem. Networks drop requests, providers retry, payloads evolve, and your downstream systems fail in unpredictable ways. If your webhook handler does too much in one request, you can get timeouts, duplicate actions, and lost events that are hard to reconcile.
This post lays out a simple, robust pattern: accept and store first, then process asynchronously with clear safety checks. It is designed for teams that want reliability without building a full event platform.
Why webhooks break (even when everyone is competent)
Most webhook incidents are not caused by a single bug. They come from a mismatch between how webhooks behave and how application code is typically written.
- Delivery is “at least once.” Providers retry when they do not receive a timely success response, which means duplicates are normal.
- Timing is not guaranteed. Events can arrive late, out of order, or bunched together after downtime.
- Payloads change. New fields appear, optional fields become absent, and sometimes nested structures shift.
- Your dependencies fail. Even if your app is healthy, a database lock, email provider issue, or rate limit can make the handler slow.
- Security is subtle. Public endpoints attract probes, and signature validation is easy to implement incorrectly.
The goal is not to make webhook processing perfect. The goal is to make it recoverable.
A minimal resilient design
A resilient webhook consumer separates “receipt” from “processing.” Receipt is fast and dependable. Processing can be slower, retried, and observed.
The four steps
- Receive the request and perform lightweight checks.
- Store the raw event (and metadata) durably.
- Acknowledge quickly with a success response when the event is safely stored.
- Process asynchronously, with retries and dedupe.
Conceptually, you want something like this:
Webhook Endpoint
- verify signature + basic schema
- write event to "inbox" table (raw body, headers, received_at)
- return 200
Worker / Job Runner
- claim unprocessed inbox rows
- run business mapping + side effects
- mark processed (or failed with reason, next_retry_at)
This pattern gives you a durable audit trail and a replay mechanism without extra infrastructure. Your “inbox” can be a database table, a durable queue, or a log store, but the principle is the same: store first, process second.
Validate and authenticate before you trust
Webhook endpoints are public by default. Even if the provider is trustworthy, the internet is not. Put guardrails at the boundary.
Boundary checks that pay off
- Signature verification: Verify the provider’s signature using the raw request body and the shared secret. Do this before parsing into a different representation that might change whitespace or ordering.
- Clock tolerance: If timestamps are involved, allow small skew but reject stale requests to reduce replay attacks.
- Content type and size limits: Reject unexpected content types and cap payload size to avoid memory pressure.
- Schema sanity checks: Validate the event type and presence of the minimal identifiers you need (for example,
event_idandresource_id).
Keep validation lightweight. You are not doing full business logic here. You are deciding whether the event is plausible and safe to store.
Process safely: dedupe, ordering, and side effects
Once events are in your inbox, the worker’s job is to translate them into your internal model and trigger side effects. This is where reliability practices matter most.
Dedupe as a first-class feature
Because “at least once” delivery is the norm, your worker should assume duplicates. There are two common approaches:
- Provider event ID: Store a unique constraint on the provider’s event ID in your inbox table. If the same event arrives again, it is a no-op at insert time.
- Business key dedupe: If you do not get a stable event ID, derive a dedupe key from stable fields (for example,
invoice_id + status). Be careful: derived keys can accidentally collapse distinct events.
Dedupe protects you from sending duplicate emails, creating duplicate tickets, or applying state transitions twice.
Ordering and state transitions
Many webhook event streams are not strictly ordered. If you treat them as ordered, you will build fragile logic. Instead:
- Prefer state reconciliation over “apply delta.” Example: when receiving “subscription updated,” fetch the current subscription state from the provider API during processing, then reconcile.
- If you must apply deltas, guard with monotonic checks (for example, ignore events older than the last processed timestamp for that resource).
- Make side effects conditional on internal state, not on the assumption that this is the first time you have seen the event.
A concrete example
Imagine a small ecommerce brand using a payment provider that sends webhooks for payment_succeeded and refund_issued. The business wants:
- When payment succeeds: create an order in the warehouse system and email a receipt.
- When refund is issued: notify support and update the order record.
With the “store then process” pattern, a temporary outage in the warehouse system does not cause lost payments. Events still land in your inbox, your endpoint still returns success quickly, and your worker retries processing until the warehouse API is available. Meanwhile, dedupe prevents receipt emails from being sent twice if the payment provider retries the webhook.
- Separate webhook receipt from processing so timeouts do not become data loss.
- Assume duplicates and reordering; build dedupe and state-based logic.
- Store raw events with enough metadata to replay and to troubleshoot.
- Operational basics (metrics, alerts, dashboards) matter more than fancy architecture.
Replay and backfill without panic
Replays turn scary incidents into manageable work. If you can replay safely, you can fix a bug and rerun processing without begging the provider to resend historical events.
To make replay feasible, store:
- Raw payload as received (string or blob).
- Headers relevant to verification and debugging (signature header, event type, request ID).
- Received timestamp and a processing status (new, processing, processed, failed).
- Error reason and next retry time when processing fails.
A good replay tool can be simple: a UI button for “reprocess this event,” plus a bulk action for “reprocess all failed events in a time range.” The key is that reprocessing should go through the same worker logic as normal processing.
Monitoring and operations that catch issues early
Reliability is not just code. If you cannot see failures quickly, small issues become large ones.
- Track inbox growth: Alert when unprocessed event count rises steadily.
- Measure processing latency: Time from receipt to processed. Watch p95 and max, not just average.
- Classify failures: Separate “retryable” (timeouts, rate limits) from “non-retryable” (bad signature, missing required IDs).
- Keep a thin dashboard: new events per hour, failed events per hour, oldest unprocessed age.
Also decide what “good enough” means. For many small teams, “processed within 5 minutes with less than 0.1% manual intervention” is a realistic operational target.
Common mistakes
These are patterns that frequently cause webhook headaches, even in otherwise well-built systems.
- Doing heavy work in the request thread: calling downstream APIs, rendering PDFs, or sending emails before returning success invites timeouts and retries.
- Logging without persistence: logs are not a replay system. If the only copy of the payload is in application logs, recovery will be painful.
- Assuming event order: treating “updated” as always arriving after “created” is fragile.
- No uniqueness constraints: if your database allows duplicate inserts for the same event, you will eventually process duplicates.
- Over-broad retries: retrying bad signatures or malformed payloads wastes capacity and hides real issues.
When not to use webhooks (or when to add polling)
Webhooks are not always the right tool. Consider alternatives when:
- You need guaranteed completeness and the provider does not offer strong delivery guarantees or replay support. In that case, combine webhooks with periodic reconciliation polling.
- Events are extremely high volume and your team cannot invest in robust queuing and scaling. Polling with checkpoints might be simpler to control.
- The provider’s webhook payloads are inconsistent and you regularly need additional API calls anyway. A scheduled sync can be more predictable.
- Your downstream side effects are irreversible and duplicates would be unacceptable. You can still do webhooks, but only if you can design safe idempotent operations and strong auditing.
In practice, many mature integrations use webhooks for speed and polling for correctness. That hybrid approach is common because it works.
Implementation checklist
Copy this list into your issue tracker and check items off as you implement.
- Boundary
- Verify signature using the raw body
- Enforce payload size limits and content type
- Reject unknown event types (or safely ignore them)
- Inbox storage
- Store raw payload + key headers + received timestamp
- Add uniqueness constraint on provider event ID (or dedupe key)
- Track status: new, processing, processed, failed
- Worker
- Claim events safely (avoid two workers processing the same row)
- Retries with backoff for retryable errors
- Stop retrying on non-retryable errors, capture reason
- Side effects
- Make operations conditional on internal state
- Record what you did (for example, “receipt email sent at”)
- Operations
- Metrics: unprocessed count, oldest age, failure rate
- Alerting: backlog growth and sustained failures
- Replay tools: single event reprocess and bulk reprocess
Conclusion
Reliable webhook processing is mostly about boundaries and recovery. If you store events durably, acknowledge quickly, process asynchronously with dedupe, and invest in basic monitoring, you can make webhooks boring in the best way.
The simple “inbox plus worker” pattern scales surprisingly far and gives small teams the operational leverage they need without turning integration work into a full-time job.
FAQ
Should the webhook endpoint return 200 even if downstream work fails?
Return success after the event is safely stored, not after downstream work completes. Downstream failures belong in the worker, where you can retry and observe. If you return failure for downstream issues, you invite retries that may create duplicates and load spikes.
What database fields are most important for the inbox table?
At minimum: provider event ID (or dedupe key), received timestamp, event type, raw payload, processing status, and an error field. Add attempt count and next retry time if you plan to manage retries in the database.
Do I need a message queue, or is a database table enough?
A database inbox is often enough for small to medium volume and is easy to operate. A dedicated queue can be helpful for very high throughput or when you need advanced routing, but it adds operational overhead. Start simple and upgrade when you have clear pressure points.
How do I handle payload version changes from the provider?
Store the raw payload and parse defensively. Avoid strict parsing that fails on new fields, and treat missing optional fields as normal. When you need a breaking change, write the worker to support both versions during a transition period.