Security: The Signature Layer: HMAC-SHA256, constant time compare.
Reliability: The Replay Defense: Timestamps + Nonce/Idempotency Key + Redis.
Consistency: The Ordering Challenge: Entity IDs, Partitioning, Sequence Numbers.
The Processing Flow (The "Golden Path").
Code Snippets (Python/Go style pseudocode).
Self-Correction during drafting:
Ordering: Simply saying "check sequence number" isn't enough. You can't process event 2 if event 1 hasn't arrived. You have to wait or buffer.
Wait logic: If using a queue (like Kafka) with partitioning, the queue handles the order for that partition. But if Event 2 arrives before Event 1 at the ingress, the ingress needs to handle that?
Actually, webhooks are usually "fire and forget" from the sender. If the receiver returns 200, the sender is happy.
If Event 2 arrives at the receiver before Event 1, the receiver shouldn't process Event 2 yet.
Strategy: Store in DB. Check if previous event exists. If not, park it. (Too complex for a general receiver).
Better Strategy: Most receivers process asynchronously. Use the Queue for ordering. Partition by entity_id. If the network delivers them out of order to the ingress, the ingress enqueues them. If the queue preserves order per partition, the worker sees them in order relative to the ingress arrival.
Crucial distinction: Network out-of-order arrival. You can't fix this easily without buffering/delaying. I should recommend "Sequence Numbering" and "Wait/Retry logic" or "State Versioning" (only update if new_version > current_version). State versioning is the most resilient.
Let's write this out clearly.
Designing a resilient webhook receiver requires shifting from a mentality of "handling a request" to "managing a distributed transaction."
Here is a comprehensive design for a system that ensures Authenticity (Signatures), Exactly-Once Processing (Replay Protection), and Causality (Ordering).
1. High-Level Architecture
Do not process business logic synchronously in the webhook endpoint. The receiver should act as a buffer that validates, persists, and acknowledges.
text
[Sender] -> [Load Balancer] -> [Webhook Ingestion Service]
|
v
[Validation Layer]
|
v
[Persistent Queue / DB]
|
v
[Async Worker Pool]
|
v
[Business Logic]
We assume the use of standard HMAC signatures (like Stripe/AWS style) or Asymmetric keys (like JWT/JWS).
The Strategy
Never trust the payload body. Always verify the signature against the raw bytes.
Configuration: Store the signing secret (HMAC) or public key (RSA/ECDSA) in a secure vault (e.g., HashiCorp Vault, AWS Secrets Manager).
Constant-Time Comparison: To prevent timing attacks, the comparison of the calculated signature vs. the provided signature must be constant-time.
Scheme Support: Support versioned signatures (e.g., v1, v2) to allow for key rotation without downtime.
Implementation Logic
Read the Signature header.
Read the raw request body (do not parse JSON yet, as parsing might alter whitespace/formatting and break the hash).
Recompute the HMAC using the stored secret and the raw body.
Compare the two hashes.
Failure Mode: If validation fails, return 401 Unauthorized immediately. Do not retry.
3. Pillar 2: Replay Protection (Idempotency)
A "Replay Attack" occurs when a valid request is intercepted and resent by an attacker. However, "Replay Handling" also covers network retries where the sender sends the same valid message twice because they didn't receive your ACK.
The Strategy
We need a unique identifier for every event. This is usually provided by the sender (e.g., Event-ID or X-Request-ID) or generated by the receiver if absent.
The "Seen" Set (Deduplication Store):
Use a high-speed datastore like Redis to store processed IDs.
The Workflow
Extract ID: Get Message-ID from headers.
Check Redis:GET webhook:processed:{Message-ID}.
If Exists: The event was processed. Return 200 OK (crucial: do not error, or the sender will retry indefinitely).
If Missing: Proceed to processing.
Locking (Race Conditions): If you have high concurrency, use SETNX (Set if Not Exists) with a short TTL to acquire a "processing lock" so two parallel requests don't slip through.
Commit: Once business logic succeeds, set the key in Redis with a TTL (e.g., 24 hours) to prevent replays.
4. Pillar 3: Ordering (Causality)
HTTP does not guarantee order. Message A might be sent before Message B, but B arrives first.
The Strategy
You cannot rely on arrival time. You must rely on Causality Keys (e.g., Timestamps or Sequence Numbers) embedded in the payload.
There are two approaches to handling order:
Approach A: Optimistic Locking (State Versioning)
Best for systems updating a specific entity (e.g., "User Updated").
Payload contains entity_id and event_timestamp (or version).
When applying the change to your DB:
sql
UPDATE users
SET email = 'new@email.com', last_event_ts = :ts
WHERE id = :id AND last_event_ts < :ts;
If the DB update affects 0 rows, it means this event is old (out of order). Discard it and return 200 OK.
Approach B: Sequence Buffering (The "Gap" Method)
Best for systems where every event must be processed (e.g., financial ledgers).
Partitioning: Group events by a key (e.g., user_id). Events for User A have no ordering dependency on User B.
Sequencing: The sender includes a monotonically increasing sequence_id.
The Buffer:
Worker checks Redis for the last_processed_seq for this user_id.
If incoming_seq == last_processed_seq + 1: Process it. Update Redis.
If incoming_seq > last_processed_seq + 1: We have a gap. Store the event in a "Pending Queue" (e.g., Redis Sorted Set) and wait for the missing one.
If incoming_seq <= last_processed_seq: It's a duplicate/old. Discard.
5. Implementation Blueprint (Golang Pseudo-code)
This example combines all three pillars using Redis for Deduplication/Ordering and a theoretical Validator for signatures.
go
func WebhookHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
// 1. Read Raw Body for Signature Verification
rawBody, _ := io.ReadAll(r.Body)
signature := r.Header.Get("X-Signature")
eventID := r.Header.Get("X-Event-ID")
// PILLAR 1: SIGNATURES
if !ValidateSignature(rawBody, signature) {
http.Error(w, "Invalid Signature", 401)
return
}
// Parse JSON only after security check
var event WebhookEvent
json.Unmarshal(rawBody, &event)
// PILLAR 2: REPLAY PROTECTION (Idempotency)
// We use a Redis SETNX pattern
redisKey := fmt.Sprintf("webhook:lock:%s", eventID)
// Try to set the key.
isProcessing, _ := redis.SetNX(ctx, redisKey, "1", 10*time.Second).Result()
if !isProcessing {
// Key already exists. We are already processing this, or finished recently.
// Return 200 to stop sender retries.
w.WriteHeader(200)
return
}
// PILLAR 3: ORDERING
// Check sequence logic (Simplified)
if !IsInOrder(ctx, event) {
// If out of order, we might buffer it or reject it depending on strategy.
// Here we implement a "Reject Old" strategy.
if event.Timestamp < GetLastProcessedTimestamp(event.EntityID) {
w.WriteHeader(200) // Ack but ignore
return
}
}
// 4. ASYNC PROCESSING
// Push to internal queue (Kafka/RabbitMQ) or spawn goroutine
// This ensures the HTTP connection is freed quickly.
ProcessAsync(event)
// Acknowledge the sender immediately
w.WriteHeader(202) // Accepted
}
func ValidateSignature(body []byte, sig string) bool {
// Use crypto/hmac
// IMPORTANT: Use hmac.Equal for constant time comparison
expected := computeHMAC(body)
return hmac.Equal([]byte(expected), []byte(sig))
}
6. Summary of Headers for the Design
To implement this design, you must agree on a contract with the Sender. You require these headers:
Header Name
Purpose
Pillar
X-Signature
HMAC-SHA256 of the body.
Security
X-Timestamp
Unix timestamp of when sent.
Security (Prevent very old replays)
X-Event-ID
UUID of the event.
Idempotency (Replay Protection)
X-Entity-ID
ID of the object being modified (e.g., User ID).
Ordering (Partitioning Key)
X-Sequence-ID
Monotonically increasing integer per Entity.
Ordering
Failure Scenarios & Responses
Bad Signature:401 Unauthorized.
Duplicate Event (Replay):200 OK (Do not return 409/500, or sender will loop).
Server Busy/Internal Error:503 Service Unavailable (Prompt sender to retry with exponential backoff).