The user wants a "secure webhook receiver".
Key requirements:
Signatures: Verification that the payload comes from the trusted sender.
Idempotency: Handling duplicate events gracefully (processing an event only once, even if received multiple times).
Order: Processing events in the correct sequence (or handling out-of-order delivery).
I need to choose a technology stack. Python with Flask or FastAPI is a common and readable choice for examples. I'll go with Python and Flask for simplicity in the core logic, but I'll mention that the concepts apply generally.
Header: The sender puts a signature in a header (e.g., X-Signature or X-Hub-Signature-256).
Implementation:
Receiver reads the raw request body.
Receiver hashes the body using a shared secret key.
Compare the generated hash with the header's hash (using a constant-time comparison function to prevent timing attacks).
2. Idempotency:
Problem: Network failures or timeouts cause the sender to retry. The receiver shouldn't charge a customer twice or create duplicate records.
Mechanism: A unique identifier for the event (Idempotency Key).
Header: Usually X-Idempotency-Key or X-Event-ID.
Implementation:
Extract the key from the header.
Check a database (Redis, SQL, etc.) to see if this key has already been processed.
If yes, return 200 OK (acknowledge receipt) but don't re-process logic.
If no, process logic, mark key as "processing" (locking), then "completed", then return 200.
3. Order (Event Sequencing):
Problem: Webhooks often arrive out of order in distributed systems.
Mechanism: A timestamp or a sequence number (monotonically increasing).
Header: X-Timestamp or X-Sequence-Number.
Implementation:
Strict Order (Blocking): If event N+1 arrives before N, reject it (400/409) and force a retry later. This relies on the sender having a retry policy.
Reconciliation (Buffering): Store N+1, wait for N.
Application Level: Just process it and let the application logic handle the update (e.g., UPDATE account SET balance = new_balance WHERE version > old_version).
Decision: For a "webhook receiver" example, strict checking (rejecting old/out-of-order) or simple logic is best. I'll implement a check: if the new timestamp is older than the last processed timestamp, ignore it (or error). Let's use a timestamp approach.
Architecture / Stack for the Example:
Language: Python.
Framework: Flask (minimal boilerplate).
Database: Redis (perfect for fast key lookups for idempotency and storing "last processed timestamp").
Dependencies: flask, redis, hmac.
Code Structure:
Config: Shared secret, Redis connection.
Signature Verification: Decorator or middleware.
Idempotency Check: Logic using Redis.
Ordering Check: Logic using Redis.
The Endpoint: Ties it all together.
Refining the Code Details:
Signature:
python
# Standard HMAC generation
sig = hmac.new(secret, msg=request.data, digestmod='sha256').hexdigest()
# Compare safely
hmac.compare_digest(sig, provided_sig)
Idempotency:
python
key = request.headers.get('X-Event-ID')
if redis.exists(key):
return "Already processed", 200
redis.set(key, "processing", ex=3600) # Expire after an hour
Ordering:
python
# Let's assume a timestamp in ISO format or Epoch
ts = request.headers.get('X-Timestamp')
last_ts = redis.get(f"last_ts:{user_id}")
if ts < last_ts:
return "Stale event", 400
redis.set(f"last_ts:{user_id}", ts)
Drafting the solution steps:
Introduction: Explain the three pillars (Signature, Idempotency, Ordering).
Prerequisites: Python, Redis (or a mock).
The Code: A complete, runnable Python script.
Explanation: Walk through the code sections.
Testing: How to simulate a request (curl or script).
Self-Correction/Refinement during thought process:
Concurrency: What if two requests for the same event ID arrive simultaneously?
Redis SETNX (Set if Not Exists) is atomic. This handles the race condition for idempotency. I should use setnx or a lock.
Ordering Logic: Storing "Last Timestamp" has a race condition too. If two requests arrive, one might overwrite the other.
Better approach for ordering in Redis: WATCH or Lua scripting.
Simplification for example: I will use a basic logic but mention that in high-throughput production, atomic operations (Lua scripts) are needed.
Signature Header format: Different providers use different headers (Standard: Signature, Stripe: Stripe-Signature, Github: X-Hub-Signature-256). I'll define my own standard header names for clarity: X-Signature-SHA256, X-Event-ID, X-Event-Timestamp.
Final Plan:
Provide a Python (Flask) implementation using Redis.
Verify Signature: Middleware to reject unauthenticated requests.
Idempotency: Use Redis SETNX to lock the event ID.
Ordering: Compare timestamp against the last known state in Redis.
Processing: Mock business logic.
I will write the code to be modular so the user can copy-paste parts or use the whole thing. I will include a "Client" script to test it as well, as verifying signatures by hand is hard.
Let's write the content.
A robust webhook receiver requires handling three distinct layers of complexity:
Security (Authentication): Ensuring the payload is from a trusted sender (HMAC Signatures).
Reliability (Idempotency): Ensuring processing the same event multiple times doesn't cause duplicate side effects (e.g., double charging a customer).
Consistency (Ordering): Ensuring event B doesn't get processed before event A.
Below is a production-ready implementation in Python (using Flask). I have chosen Redis to handle the state for idempotency and ordering because it is fast and supports atomic operations.
Architecture Overview
Signature: We verify an HMAC SHA-256 hash sent in the header.
Idempotency: We store processed Event IDs in Redis with a TTL (Time To Live).
Ordering: We track the "Last Seen Sequence Number" per entity. If an event arrives out of order, we temporarily reject it (HTTP 409 Conflict) so the sender retries it later.
1. The Implementation (Python/Flask)
You will need flask, redis, and hmac (standard lib).
python
2. How to Send (The Client Side)
To test this, you need to generate the signature headers correctly.
We use HMAC-SHA256. The sender hashes the payload body with a secret key; the receiver does the same.
Why request.data? We use the raw bytes. If you use request.json first, Flask might alter whitespace or character encoding, causing the signature verification to fail.
Timing Attacks: We use hmac.compare_digest instead of ==. Standard string comparison stops at the first wrong character, allowing hackers to guess the signature character-by-character based on response time.
2. Idempotency (The event_id)
We check if event:{id} exists in Redis.
The result: If the client sends the same evt_001 twice due to a network timeout, the receiver processes it once and returns 200 OK both times. The client is happy, and your database is clean.
TTL: We set an expiry (e.g., 24 hours or 7 days). We assume that if a week has passed, we don't need to remember this specific ID to prevent duplicates anymore.
3. Ordering (The sequence_number)
This is the hardest part.
Strict Sequentiality: The code enforces that for user_123, you must process sequence 1, then 2, then 3.
Handling Gaps (HTTP 409): If we receive Seq 5 but only have Seq 1 recorded, we return 409 Conflict. This tells the sender: "I can't handle this now, put it back in the queue and try later." This buffers the system against network race conditions where packets arrive out of order.
4. Concurrency & Atomicity
If two webhooks for the same user arrive at the exact same millisecond:
Standard Python variables are not thread-safe.
Redis Pipelines (used in step 4 of the logic) ensure that setting the "processed" flag and updating the "sequence number" happen instantly together. This prevents a race condition where two threads think they are both the next valid sequence.
import os
import hmac
import hashlib
import json
import time
from flask import Flask, request, jsonify, abort
from redis import Redis
from functools import wraps
app = Flask(__name__)
# Configuration
# In production, load these from environment variables
SHARED_SECRET = os.getenv('WEBHOOK_SECRET', 'super_secret_key').encode('utf-8')
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
# Initialize Redis
r = Redis(host=REDIS_HOST, port=REDIS_PORT, decode_responses=True)
# --- Helper Classes ---
class EventProcessingError(Exception):
"""Custom exception for processing failures."""
pass
class OutOfOrderError(EventProcessingError):
"""Raised when event sequence is violated."""
pass
class DuplicateEventError(EventProcessingError):
"""Raised when an event is replayed."""
pass
# --- Decorators ---
def verify_signature(f):
@wraps(f)
def wrapper(*args, **kwargs):
signature_header = request.headers.get('X-Signature-256')
if not signature_header:
abort(401, "Missing signature header")
# Calculate expected signature
# request.data is the raw bytes of the body
expected_sig = hmac.new(SHARED_SECRET, request.data, hashlib.sha256).hexdigest()
# Format usually "sha256=<hash>"
received_sig = signature_header.replace('sha256=', '')
# Constant time comparison to prevent timing attacks
if not hmac.compare_digest(expected_sig, received_sig):
abort(401, "Invalid signature")
return f(*args, **kwargs)
return wrapper
# --- Core Logic ---
def process_event_logic(event_data):
"""
YOUR BUSINESS LOGIC GOES HERE.
e.g., Update database, charge card, send email.
"""
print(f"Processing Event {event_data['event_id']}: {event_data['type']}")
# Simulate work
time.sleep(0.1)
return True
def handle_webhook_event(payload):
"""
Handles the complexity of Idempotency and Ordering.
"""
event_id = payload.get('event_id')
entity_id = payload.get('entity_id') # e.g., user_id or order_id
sequence_num = payload.get('sequence_number') # Monotonically increasing integer
if not all([event_id, entity_id, sequence_num is not None]):
abort(400, "Missing required fields")
# 1. IDEMPOTENCY CHECK
# Check if we already successfully processed this event ID
if r.exists(f"event:{event_id}"):
print(f"Duplicate event detected: {event_id}. Acknowledging.")
return {"status": "duplicate_ignored"}, 200
# 2. ORDERING CHECK
# We need to ensure we haven't processed a NEWER event for this entity yet.
# Key: last_seq:<entity_id> -> Value: <sequence_number>
last_seq_key = f"last_seq:{entity_id}"
# Atomically check sequence order using Redis WATCH or Lua scripting.
# Here we use a simplified approach for readability, but WATCH is safer for high concurrency.
last_seq_str = r.get(last_seq_key)
last_seq = int(last_seq_str) if last_seq_str else -1
if sequence_num <= last_seq:
# This is an old event (or duplicate that slipped past check 1)
return {"status": "stale_event"}, 200
if sequence_num > last_seq + 1:
# We are expecting last_seq + 1, but got something higher.
# This means an intermediate event is missing.
# We return 409 Conflict to tell the sender to retry later.
abort(409, f"Event out of order. Expected {last_seq + 1}, got {sequence_num}")
# 3. PROCESS
try:
process_event_logic(payload)
except Exception as e:
print(f"Business logic failed: {e}")
# Don't save state, allow retry
abort(500, "Internal processing error")
# 4. COMMIT STATE
# If logic succeeded, mark event as done and update sequence counter.
# We use a pipeline to ensure atomicity.
pipe = r.pipeline()
pipe.set(f"event:{event_id}", "processed", ex=86400) # Keep record for 24h
pipe.set(last_seq_key, sequence_num)
pipe.execute()
return {"status": "success"}, 200
# --- Routes ---
@app.route('/webhook', methods=['POST'])
@verify_signature
def webhook_receiver():
try:
# Ensure JSON
if not request.is_json:
return jsonify({"error": "Content-Type must be application/json"}), 415
payload = request.json
return handle_webhook_event(payload)
except OutOfOrderError:
return jsonify({"error": "Out of order"}), 409
except Exception as e:
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(port=5000, debug=True)