Your payment gateway fires a webhook for a successful charge. Due to a momentary network partition or an aggressive retry policy on their end, their infrastructure doesn't receive your TCP acknowledgment in time. Ten milliseconds later, they fire the exact same webhook again.
Both requests hit your API gateway simultaneously. Your routing layer distributes them across two different worker processes. Both workers query the database for an existing transaction ID, find nothing, and spin up an identical, expensive backend workflow.
Suddenly, your user receives two onboarding emails, your billing system triggers a double credit allocation, and your database records a race condition that takes down your checkout service.
If you have built integrations with Stripe, GitHub, Shopify, or any modern SaaS platform, you've experienced this scenario. Webhooks are inherently at-least-once delivery mechanisms. When multiple webhooks arrive together—whether due to automatic retries, concurrent event streams, or distributed client architectures—handling them idempotently is non-negotiable.
This guide explores the engineering patterns, architectural trade-offs, and production-tested strategies required to prevent duplicate webhook runs and race conditions when concurrent events hit your system.
📋 Table of Contents
- The Distributed Webhook Problem: Why Simple Checks Fail
- 1. Atomic Database Constraints and Unique Indexes
- 2. Distributed Locking with Redis and Redlock Mechanics
- 3. Idempotency Keys and Cryptographic Payload Hashing
- 4. Optimistic Concurrency Control (OCC) for State Transitions
- 5. Event Sourcing and Deduplication via Append-Only Logs
- 6. Deduplication at the Edge with Cloudflare Workers or API Gateways
- 7. Queue-Based Buffering and Debouncing Strategies
- Comparing Webhook Deduplication Strategies
- Production Architecture Decision Guide
The Distributed Webhook Problem: Why Simple Checks Fail
The most common mistake engineers make when implementing webhook handlers is relying on a "check-then-act" pattern inside application code.
# 🚨 DANGEROUS: The check-then-act race condition
async def handle_webhook(event):
exists = await db.events.find_one({"event_id": event.id})
if exists:
return {"status": "skipped"}
# --- RACE CONDITION WINDOW HAPPENS HERE ---
await db.events.insert_one({"event_id": event.id, "status": "processing"})
await run_heavy_workflow(event)
return {"status": "processed"}
Why this fails in production: Between the moment find_one() returns None and the moment insert_one() executes, a concurrent webhook request for the exact same event_id can slip through the gap. Both workers evaluate exists as false, and both proceed to trigger the workflow.
To prevent duplicate workflow runs, you must push deduplication down into the storage engine or use coordination primitives that are atomic by design. Let's look at how to solve this across seven architectural patterns.
1. Atomic Database Constraints and Unique Indexes
Scenario: Your Node.js application receives concurrent invoice.payment_succeeded webhooks from Stripe for the same subscription renewal. Your workers try to insert the event record into PostgreSQL.
Why it matters: Application-level locks are useless across separate worker nodes and serverless functions. You need a guarantee enforced by the storage layer itself.
Solution: Rely on database-level unique constraints. When two workers attempt to insert the same event_id simultaneously, the database's internal concurrency control will allow only one transaction to succeed while throwing a unique violation error on the other.
Code:
CREATE TABLE processed_webhooks (
event_id VARCHAR(255) PRIMARY KEY,
provider VARCHAR(50) NOT NULL,
received_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
status VARCHAR(50) NOT NULL
);
import { Pool } from 'pg';
const pool = new Pool();
async function processWebhook(eventId: string, payload: any) {
const client = await pool.connect();
try {
// Attempt to claim the event atomically
await client.query(
'INSERT INTO processed_webhooks (event_id, provider, status) VALUES ($1, $2, $3)',
[eventId, 'stripe', 'processing']
);
} catch (error: any) {
if (error.code === '23505') { // PostgreSQL unique_violation code
console.warn(`Duplicate webhook detected: ${eventId}`);
return { status: 'ignored', reason: 'duplicate' };
}
throw error;
}
try {
// Run your business logic safely here
await executeWorkflow(payload);
await client.query(
'UPDATE processed_webhooks SET status = $1 WHERE event_id = $2',
['completed', eventId]
);
return { status: 'success' };
} catch (error) {
await client.query(
'UPDATE processed_webhooks SET status = $1 WHERE event_id = $2',
['failed', eventId]
);
throw error;
} finally {
client.release();
}
}
Why this works: Database engines use page-level or row-level locks during unique index insertions. Even if 50 webhooks arrive at the exact same millisecond, the database serializes the insertions on the index, ensuring exactly one winner and 49 constraint exceptions.
💡 Practical note: Make sure your unique index covers not just the
event_id, but also the webhook provider if you ingest webhooks from multiple sources whose IDs could theoretically collide (e.g., GitHub and Stripe both using UUIDs or incremental integers).
2. Distributed Locking with Redis and Redlock Mechanics
Scenario: Your workflows interact with third-party legacy APIs that do not support database transactions or unique constraints. You need to ensure that for a given resource ID (like a user account or order ID), only one webhook workflow runs at a time across your entire Kubernetes cluster.
Why it matters: Unique event IDs prevent processing the same webhook twice, but what if a provider sends two different webhook event types (e.g., customer.updated and subscription.created) simultaneously for the same user? Both could trigger conflicting workflow modifications.
Solution: Implement a distributed lock using Redis with atomic SET NX PX operations or the Redlock algorithm for multi-node Redis clusters.
Code:
import redis.asyncio as redis
import uuid
import asyncio
redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)
async def acquire_lock(resource_key: str, ttl_ms: int = 5000):
identifier = str(uuid.uuid4())
acquired = await redis_client.set(
f"lock:{resource_key}",
identifier,
nx=True,
px=ttl_ms
)
if acquired:
return identifier
return None
async def release_lock(resource_key: str, identifier: str):
# Use a Lua script to ensure we only release the lock if we still own it
lua_script = """
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
"""
await redis_client.eval(lua_script, 1, f"lock:{resource_key}", identifier)
async def handle_user_webhook(user_id: str, event_data: dict):
lock_key = f"user_workflow:{user_id}"
lock_id = await acquire_lock(lock_key, ttl_ms=10000)
if not lock_id:
# Another webhook is currently modifying this user's state
print(f"Concurrency conflict for user {user_id}. Queuing or dropping.")
return {"status": "retry_later"}
try:
await run_complex_workflow(event_data)
finally:
await release_lock(lock_key, lock_id)
Why this works: The Redis NX (Not eXists) modifier ensures that setting the key is strictly atomic. By attaching a unique UUID identifier to the lock value and clearing it via a Lua script, you prevent a slow worker from accidentally releasing a lock that has already expired and been acquired by another process.
⚠️ Gotcha: Never set your lock TTL shorter than the maximum possible execution time of your workflow. If your workflow takes 12 seconds and your lock expires in 10, a second worker will acquire the lock while the first worker is still running, completely defeating the purpose of the lock.
3. Idempotency Keys and Cryptographic Payload Hashing
Scenario: Webhook providers occasionally fail to supply a reliable, unique event ID in their headers. Alternatively, they might send structurally identical events under different internal identifiers due to internal service failovers.
Why it matters: Relying blindly on headers supplied by third parties exposes you to header spoofing or missing identifiers. You need a deterministic way to identify duplicate payloads.
Solution: Generate a cryptographic hash (SHA-256) of the normalized webhook payload body combined with the event type. Store this hash in your database with a time-to-live (TTL) or cleanup policy.
Code:
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"net/http"
)
func generatePayloadHash(payload []byte, eventType string) string {
hasher := sha256.New()
hasher.Write(payload)
hasher.Write([]byte(eventType))
return hex.EncodeToString(hasher.Sum(nil))
}
func handleWebhook(w http.ResponseWriter, r *http.Request) {
// 1. Read body
body := readBody(r)
eventType := r.Header.Get("X-Provider-Event-Type")
// 2. Generate deterministic fingerprint
fingerprint := generatePayloadHash(body, eventType)
// 3. Try inserting into Redis or DB with unique constraint
isNew, err := cache.SetNX(r.Context(), "webhook_hash:"+fingerprint, "1", time.Hour*24).Result()
if err != nil {
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
if !isNew {
// Duplicate detected via content hash
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status": "duplicate_ignored"}`))
return
}
// 4. Proceed with workflow execution
executeWorkflow(body)
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status": "processed"}`))
}
Why this works: Even if the webhook provider changes their event ID format or sends a retry with a new delivery header, identical request bodies produce identical SHA-256 hashes. This creates an immutable content-addressable deduplication barrier.
4. Optimistic Concurrency Control (OCC) for State Transitions
Scenario: Your e-commerce platform receives inventory update webhooks from multiple fulfillment warehouses simultaneously. Each webhook reads the current inventory count, calculates adjustments, and attempts to write the new state back.
Why it matters: Pessimistic locking (SELECT ... FOR UPDATE) can severely degrade throughput and cause connection pool exhaustion when high volumes of webhooks hit your database simultaneously.
Solution: Use Optimistic Concurrency Control with a version number or state discriminator column. Instead of locking the row, you verify that the row's version hasn't changed during the update.
Code:
async def update_order_status_occ(order_id: str, expected_version: int, new_status: str):
query = """
UPDATE orders
SET status = $1, version = version + 1, updated_at = NOW()
WHERE id = $2 AND version = $3
RETURNING version;
"""
result = await db.execute(query, new_status, order_id, expected_version)
if not result:
raise ConcurrencyConflictError(
f"Order {order_id} was modified concurrently. Expected version {expected_version}."
)
return True
Why this works: OCC assumes conflicts are rare. It allows multiple workers to read the same state and process their webhooks concurrently in application memory. When they write back, the database's atomic WHERE version = X check ensures that only the first write succeeds. Subsequent writes find 0 affected rows, signaling your application to refetch the latest state and reconcile or safely discard the duplicate run.
5. Event Sourcing and Deduplication via Append-Only Logs
Scenario: You are building a complex financial ledger where discarding duplicate webhooks silently is unacceptable. You need an audit trail of every single webhook payload received, alongside its processing lifecycle.
Why it matters: Traditional CRUD tables make it difficult to trace why a workflow ran twice or when duplicate events arrived relative to one another.
Solution: Treat incoming webhooks as immutable events written to an append-only log (such as Apache Kafka, AWS Kinesis, or a PostgreSQL event table). Use consumer groups or partition keys to guarantee that events for the same entity are processed strictly in order.
Code:
-- An append-only event store for incoming webhooks
CREATE TABLE webhook_event_log (
sequence_id BIGSERIAL PRIMARY KEY,
event_id VARCHAR(255) UNIQUE NOT NULL,
aggregate_id VARCHAR(255) NOT NULL,
payload JSONB NOT NULL,
received_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
processed BOOLEAN DEFAULT FALSE
);
async function ingestWebhookEvent(eventId: string, aggregateId: string, payload: any) {
try {
// Step 1: Append to immutable log. Unique constraint on event_id protects against duplicates.
await db.query(
`INSERT INTO webhook_event_log (event_id, aggregate_id, payload)
VALUES ($1, $2, $3)`,
[eventId, aggregateId, payload]
);
// Step 2: Publish to internal message broker partitioned by aggregate_id
await messageBroker.publish(`entity-${aggregateId}`, { eventId, payload });
} catch (error: any) {
if (error.code === '23505') {
// Already logged. Safe to acknowledge webhook upstream.
return;
}
throw error;
}
}
Why this works: Decoupling webhook ingestion from webhook processing gives your system breathing room. The ingestion endpoint becomes a lightweight, high-throughput receiver whose sole job is to append to the log and return 200 OK to the provider. Downstream workers process the log sequentially, eliminating race conditions entirely.
6. Deduplication at the Edge with Cloudflare Workers or API Gateways
Scenario: A malicious or misconfigured webhook client floods your origin servers with 10,000 identical webhook requests per second over a span of 5 seconds. Your database connection pool collapses under the connection spike before your application code even runs.
Why it matters: Protecting your database at the application layer is too late if your infrastructure is already overwhelmed by network traffic volume.
Solution: Implement distributed request deduplication at the edge using Cloudflare Workers, API Gateway caching, or Redis Bloom filters combined with sliding-window rate limiting.
Code:
// Cloudflare Worker Edge Script
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
if (request.method !== 'POST') {
return new Response('Method not allowed', { status: 405 });
}
const signature = request.headers.get('Stripe-Signature');
const clone = request.clone();
const bodyText = await clone.text();
// Create a quick cryptographic hash at the edge
const encoder = new TextEncoder();
const data = encoder.encode(bodyText + (signature || ''));
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
const cacheKey = new Request(`https://dedup-cache.internal/webhook/${hashHex}`, request);
const cache = caches.default;
// Check if we have already seen this exact payload recently (e.g., 60-second window)
let response = await cache.match(cacheKey);
if (response) {
// Return cached 200 OK immediately without hitting origin servers
return new Response(JSON.stringify({ status: 'deduplicated_at_edge' }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
});
}
// Forward to origin server
response = await fetch(request);
// If origin processed successfully, cache the response at the edge for 60 seconds
if (response.status === 200) {
const responseToCache = new Response(JSON.stringify({ status: 'processed' }), {
status: 200,
headers: { 'Cache-Control': 'public, max-age=60' }
});
event.waitUntil(cache.put(cacheKey, responseToCache));
}
return response;
}
Why this works: Edge computing layers sit physically closer to the webhook sender. By caching responses to identical request signatures at the edge, you absorb DDoS-like webhook retry storms before they ever touch your core application cluster or database.
7. Queue-Based Buffering and Debouncing Strategies
Scenario: A user updates their billing profile 5 times in 2 seconds. Your payment provider fires 5 separate customer.updated webhooks in rapid succession. Running your heavy billing reconciliation workflow 5 times in parallel is a massive waste of compute resources.
Why it matters: Standard deduplication treats identical events as duplicates. But what about burst events where state changes rapidly and you only care about the final state?
Solution: Use a delayed message queue (such as RabbitMQ delayed exchanges, AWS SQS with visibility timeouts, or Redis sorted sets) to debounce incoming webhooks.
Code:
import time
import redis.asyncio as redis
redis_client = redis.Redis(host='localhost', port=6379, decode_responses=True)
async def handle_burst_webhook(customer_id: str, event_payload: dict):
# Use a Redis Sorted Set as a debouncing buffer
# Score is current timestamp + buffer window (e.g., 5 seconds from now)
execution_time = time.time() + 5
# Store the latest payload for this customer, overwriting older ones in the burst
await redis_client.hset(f"customer:payloads:{customer_id}", "latest", str(event_payload))
# Add to sorted set for delayed execution, or update score to push back execution time
await redis_client.zadd("webhook_debounce_queue", {customer_id: execution_time})
return {"status": "buffered_for_debounce"}
# Background worker running every second
async def process_debounce_queue():
while True:
now = time.time()
# Find customer IDs whose debounce window has elapsed
customer_ids = await redis_client.zrangebyscore("webhook_debounce_queue", 0, now)
for customer_id in customer_ids:
# Remove from queue atomically
removed = await redis_client.zrem("webhook_debounce_queue", customer_id)
if removed:
payload = await redis_client.hget(f"customer:payloads:{customer_id}", "latest")
await run_reconciliation_workflow(customer_id, payload)
await redis_client.delete(f"customer:payloads:{customer_id}")
await asyncio.sleep(1)
Why this works: Debouncing collapses multiple rapid-fire webhooks into a single workflow execution representing the latest state of the resource. This eliminates redundant compute cycles and prevents race conditions caused by out-of-order execution.
Comparing Webhook Deduplication Strategies
| Strategy | Complexity | Scalability | Best Use Case | Primary Failure Mode |
|---|---|---|---|---|
| 1. Database Unique Indexes | Low | High | Standard event ID tracking | Database index bloat over time if not purged |
| 2. Distributed Locks (Redis) | Medium | Medium-High | Resource-level serialization | Lock expiration during long-running workflows |
| 3. Payload Hashing | Low | High | Providers missing reliable event IDs | Schema drift altering JSON serialization order |
| 4. Optimistic Concurrency | Medium | High | High-throughput inventory/state updates | High contention causing excessive retry loops |
| 5. Append-Only Event Logs | High | Very High | Financial ledgers & strict audit trails | Storage consumption and operational overhead |
| 6. Edge Deduplication | Medium | Very High | Absorbing webhook retry storms & DDoS | Edge cache invalidation complexity |
| 7. Queue Debouncing | High | High | Burst events & rapid state changes | Risk of data loss if worker crashes before flush |
Production Architecture Decision Guide
When architecting a robust webhook ingestion pipeline, don't rely on a single silver bullet. Combine layers based on your throughput and consistency requirements:
- For standard SaaS webhooks (Stripe, GitHub, Shopify): Implement Strategy 1 (Database Unique Indexes) combined with Strategy 3 (Payload Hashing). This provides absolute safety against duplicate deliveries with minimal operational overhead.
- For high-frequency state updates and mutations: Use Strategy 4 (Optimistic Concurrency Control) on your aggregate tables to allow concurrent processing while preventing silent data corruption.
- For bursty notification streams: Introduce Strategy 7 (Queue-Based Debouncing) to conserve compute resources and ensure your workflows operate on the most up-to-date state.
- For mission-critical financial transactions: Adopt Strategy 5 (Append-Only Event Logging) so that every single incoming webhook is permanently recorded before any business logic executes, turning potential duplicate failures into replayable audit events.