We are going to design a framework for consuming webhooks that includes:
Retries: Exponential backoff with jitter, configurable max retries.
Signatures: Verify the signature of the incoming request (using a shared secret and a hash algorithm, e.g., HMAC-SHA256).
Idempotency: Ensure that processing the same event multiple times (due to retries or replay) does not cause side effects.
Replay UI: An admin interface to replay events (by event ID) for debugging or recovery.
Ordering Keys: Allow events to be ordered by a key (e.g., customer ID) so that events for the same key are processed in order.
We'll design a system that has:
A webhook endpoint that receives events.
A database to store events (for replay and idempotency).
A processing queue (like a message queue) to handle events asynchronously, with ordering support.
Steps:
Webhook Endpoint:
Accepts POST requests.
Verifies the signature (using a secret stored in config).
Extracts event ID (from a header, e.g., X-Event-ID), event data, and ordering key (from header or body).
Checks if the event ID has been processed (idempotency check). If yes, return 200 (or 202) without processing again.
If not, store the event in the database (with status: received, event ID, ordering key, payload, etc.) and enqueue for processing.
Retry Logic:
The processing worker will attempt to process the event.
If processing fails, it will retry with exponential backoff and jitter.
After max retries, the event will be marked as failed (and maybe alert).
Idempotency:
We use the event ID to check if we have already processed the event. We must store the event ID and the processing result (or at least a flag) in the database.
Replay UI:
An admin interface (could be a simple web page) that lists events (with filters by status, time, etc.) and allows replaying a failed event or any event.
Replaying an event means: if the event was already processed (and we have the result) we might want to re-run the processing logic? But note: idempotency should allow safe replay.
Alternatively, we can have a separate queue for replays and mark the original event as replayed? Or we can create a new event with the same payload and a new event ID? The requirement says "replay UI", so we want to be able to resend the same event (with same event ID) but we must be cautious because of idempotency. Actually, if the event was already processed and we want to replay, we might want to force processing even if the event ID is already in the processed table? But that breaks idempotency. Alternatively, we can have a "replay" that creates a new event with a new event ID? But then the original event ID is not replayed. So, we have two options:
a) Allow replay of the same event ID by resetting the status to 'received' and then re-enqueue. But then if the event was already processed, we are processing it again. This is acceptable if the processing is idempotent? But the requirement says idempotency, so the processing should be safe to run multiple times. So we can reset the status and re-enqueue.
b) Or, we can have a separate "replay" event that references the original event, but then the processing logic might need to know it's a replay? We don't want to change the processing logic.
Let's go with (a): We allow resetting the event and re-enqueueing. But note: if the event was successful and we replay, we are going to process it again. This might be acceptable because the processing is idempotent? But if the processing is not idempotent (e.g., charging a credit card) then replaying a successful event would be bad. So we must be cautious.
Alternatively, we can only allow replay of failed events? But the requirement says "replay UI", so we might want to replay any event for debugging. We can have a flag in the database that marks an event as "replayable" and then when replaying, we create a new event with a new event ID and the same payload? But then the original event ID is not used. This might break ordering if the ordering key is based on the event ID? Not necessarily, because ordering key is separate.
Let's think about ordering: if we have ordering keys, we want events with the same ordering key to be processed in order. If we replay an event, we want it to be processed in the same order as the original? But if we create a new event, then the new event might be processed after newer events for the same ordering key. So we might break ordering.
So, to preserve ordering, we might want to replay the event and have it processed in the same order as the original. This is complex.
Alternatively, we can design the system so that ordering is guaranteed by the queue (e.g., per ordering key, we have a separate queue and we process one by one). Then, if we want to replay an event, we must insert it at the correct position? That's very hard.
Given the complexity, let's assume:
We are going to store events with:
event_id (unique)
ordering_key
payload
status (received, processing, succeeded, failed)
created_at
processed_at
retry_count
last_error
For replay:
We will have an admin action that, for a given event_id, sets the status back to 'received' and clears the processed_at, retry_count, and last_error. Then we re-enqueue the event. But note: if the event was already succeeded and we replay, we are going to process it again. This might be acceptable if the processing is idempotent? But if it's not, then we have a problem.
Alternatively, we can only allow replay of failed events? But the requirement says "replay UI", so we might want to replay any event. We can add a configuration: only allow replay of failed events? Or we can have a warning when replaying a succeeded event.
Let's design the replay as:
code
- The admin UI shows events (with filters). For each event, there is a "Replay" button.
- When replaying, we check: if the event status is 'succeeded', we ask for confirmation (or we don't allow by default?).
- We then reset the event to 'received' and enqueue again.
But note: if the event was already processed and we reset, then when we process again, the idempotency check (by event_id) will see that the event_id is already in the processed table? Wait, we have an idempotency table that stores event_id and status? We must design the idempotency check:
code
Replay UI:
We need a way to list events and replay them.
We can build a simple admin page (using Flask/Django/Express, etc.) that:
code
- Lists events (with filters: by status, by time, by ordering_key, etc.)
- For each event, show the event_id, status, created_at, etc.
- Have a button to replay.
When replaying:
code
Ordering Keys:
code
We are using SQS with message group ID set to the ordering key. This ensures that messages with the same ordering key are processed in order by the same consumer.
But note: if we have multiple ordering keys, they can be processed in parallel by different consumers.
We must set the message group ID when sending the message.
If an event does not have an ordering key, we can set a default (e.g., 'global') so that all events without an ordering key are processed in order? But that would be a bottleneck. Alternatively, we can set the message group ID to the event_id? Then each event is its own group and can be processed in parallel? But then we don't have ordering across events for the same customer? The requirement is to have ordering by a key (e.g., customer ID). So we set the message group ID to the ordering key (which might be the customer ID). Then events for the same customer are in the same group and processed in order.
So, we must extract the ordering key from the webhook. It could be in a header (e.g., `X-Ordering-Key`) or in the body. We need to define how.
Let's assume we have a header `X-Ordering-Key`. If not present, we use a default (e.g., 'global').
Then, when sending to the queue, we set the message group ID to the ordering key.
But note: SQS has a limit of 20,000 message group IDs per queue? And if we have many distinct ordering keys, we might hit that? Then we need to use a consistent hashing to map ordering keys to a fixed number of groups? But that breaks ordering? Because two different ordering keys might map to the same group and then they will be ordered? That's not what we want.
Alternatively, we can use the ordering key as the message group ID and accept that we might have many groups. But if we have too many, we can use a hashing to a fixed number of groups and then within each group, we don't have ordering? That's a trade-off.
Given the requirement, we want ordering by the given key. So we must use the key as the group ID.
But then we must ensure that the number of distinct ordering keys is not too high? If it is, we might need to use a different queue that supports ordering by key without a limit on groups? Or we can use a different approach (like a database queue with row-level locks per ordering key).
Given the time, let's assume we are using SQS and we have a manageable number of ordering keys.
Summary of Database Schema:
code
Table: events
event_id (varchar, primary key)
ordering_key (varchar, not null)
payload (json, not null)
status (varchar, not null, default 'received') -- 'received', 'processing', 'succeeded', 'failed'
created_at (timestamp, not null)
processed_at (timestamp, nullable)
retry_count (integer, default 0)
last_error (text, nullable)
We might also have an index on (ordering_key, status) for the worker to pick events? But we are using a queue, so the worker gets events from the queue, not from the database. So we don't need to query by ordering_key? We only query by event_id.
So we just need the event_id primary key.
Worker Implementation:
code
We have a worker that:
while true:
message = sqs.receive_message(...)
if not message:
sleep(1)
continue
event_id = message.body
event = db.get_event(event_id)
if event is None:
# Event not found? Then delete the message and log error.
delete_message(message)
log_error(f"Event {event_id} not found")
continue
if event.status in ['succeeded', 'failed']:
# Already processed, delete the message.
delete_message(message)
continue
if event.status == 'processing':
# This might be a duplicate delivery? Or we have two messages for the same event? Then delete this message and let the original processing continue?
delete_message(message)
continue
# Try to set to processing
rows_updated = db.update_event_status_to_processing(event_id)
if rows_updated == 0:
# Another worker set it to processing? Then delete this message and continue.
delete_message(message)
continue
try:
process_event(event)
db.mark_event_succeeded(event_id)
delete_message(message)
except Exception as e:
event.retry_count += 1
event.last_error = str(e)
db.save_event(event)
if event.retry_count >= config.MAX_RETRIES:
db.mark_event_failed_permanently(event_id)
delete_message(message)
else:
# Change the message visibility timeout to the next retry time.
backoff = calculate_backoff(event.retry_count)
change_message_visibility(message, backoff)
Note: We are using the same message for retries. We change the visibility timeout to delay the next attempt.
Webhook Receiver:
code
@app.route('/webhook', methods=['POST'])
def webhook():
# Verify signature
signature = request.headers.get('X-Webhook-Signature')
if not verify_signature(request.data, signature, config.WEBHOOK_SECRET):
return 'Invalid signature', 401
event_id = request.headers.get('X-Event-ID')
if not event_id:
return 'Missing event ID', 400
ordering_key = request.headers.get('X-Ordering-Key', 'global')
payload = request.get_json()
# Check if event already exists and is in terminal state
event = db.get_event(event_id)
if event and event.status in ['succeeded', 'failed']:
return 'Event already processed', 200
# If event exists and is not terminal, we might be already processing? Then we return 200? Or we wait?
# Let's return 200 and let the existing processing continue.
if event and event.status in ['received', 'processing']:
return 'Event already received', 200
# Insert new event
db.create_event(event_id, ordering_key, payload)
# Send to queue
sqs.send_message(
MessageBody=event_id,
MessageGroupId=ordering_key
)
return 'Accepted', 202
Replay UI (admin):
code
We'll create a simple admin page (protected by basic auth or similar) that:
- Lists events (with filters: status, ordering_key, date range, etc.)
- For each event, show details and a "Replay" button (only for failed events? or for all with warning).
When replaying a failed event:
- Reset the event: set status='received', retry_count=0, last_error=None, processed_at=None.
- Send a new message to the queue (with the same event_id and ordering_key).
But note: we are only allowing replay for failed events, so we don't have the issue of duplicate processing with the old message (because the old message would have been deleted after max retries).
However, what if the event failed but we haven't reached max retries? Then there might be a message in the queue? Actually, in our worker, when we fail and haven't reached max retries, we don't delete the message and change the visibility. So there is a message in the queue. Then if we replay (reset and send a new message), we will have two messages for the same event? Then the first one that gets the lock will process, the second will see the event is 'processing' and delete? So we will process only once? But we want the replay to be processed? Actually, we are resetting the event to 'received', so the old message (if it becomes visible) will see the event as 'received' and try to process? Then we have two messages that will try to process? But the first one to update the event to 'processing' will succeed, the second will fail to update (because the event is now 'processing') and then delete the message? So we will process only once? That's acceptable.
But if we want the replay to be processed even if the old message is still in the queue, we must remove the old message? We can't.
Given the complexity, we accept that replay might result in the event being processed only once (if the old message is still in the queue) and that's okay because we are replaying to retry a failed event? Actually, if the event failed, then the old message would have been processed and failed? And then we changed the visibility? So the old message is still in the queue? Yes, until we reach max retries. So if we replay a failed event (that hasn't reached max retries) then we have two messages. The first one (old) will be processed and might fail again? Then we will have two failing attempts? That's not what we want.
So, we must only allow replay for events that have reached max retries? Then we are sure there is no message in the queue.
Alternatively, we can change the worker to not use the queue for retries? We can have a separate retry queue? Or we can have a delay queue? But that's complex.
Given the time, let's change the replay policy:
We only allow replay for events that are in 'failed' state (permanently failed, i.e., max retries reached). Then we are sure there is no message in the queue.
So, in the admin UI, we only show events with status='failed'.
And when we replay, we reset and send a new message.
Then, we are safe.
Signature Verification:
We assume the sender signs the request body with a secret and sends the signature in the header.
We'll use HMAC-SHA256.
Example:
code
signature = request.headers.get('X-Webhook-Signature')
expected = hmac.new(config.WEBHOOK_SECRET, request.data, 'sha256').hexdigest()
if not hmac.compare_digest(signature, expected):
return 'Invalid signature', 401
Config:
WEBHOOK_SECRET: string
MAX_RETRIES: integer
ALLOW_REPLAY_SUCCEEDED: boolean (if we want to allow replay of succeeded events? We set to false for now)
Conclusion:
This design is complex and has some edge cases. But it covers the requirements.
We have:
code
- Retries: with exponential backoff and jitter (using SQS visibility timeout).
- Signatures: verified on webhook receipt.
- Idempotency: by event_id and status.
- Replay UI: for failed events only (safe).
- Ordering: by ordering_key (using SQS message group ID).
We assume:
code
- The number of distinct ordering keys is manageable for SQS (less than 20,000 per queue?).
- The webhook events are not too high volume? Because we are storing every event in the database.
We also assume that the processing is idempotent? Because we might process the same event multiple times (if the worker crashes after processing but before deleting the message, or if we replay).
We must design the processing function to be idempotent.
Code Structure:
We'll have:
code
- webhook_receiver.py: Flask app that receives webhooks.
- worker.py: Long-running process that processes events from the queue.
- admin.py: Flask app for admin UI (or we can integrate with the webhook_receiver app with a separate route and protect it).
- models.py: Database models.
- queue.py: Wrapper for SQS (or other queue) operations.
We'll use environment variables for configuration.
Additional Considerations:
We need to handle database connections and queue connections properly (with retries and timeouts).
We need to log appropriately.
We need to monitor the queue and the worker.
Given the time, we are providing a high-level design.
Let's write some pseudocode for the main components.
However, note: the requirement is to draft a framework, so we are providing the design and some code snippets.
Due to the complexity, we cannot write the entire codebase, but we can outline the key parts.
Let's write:
The webhook endpoint.
The worker loop.
The replay admin endpoint.
We'll use Python and Flask for the webhook and admin, and boto3 for SQS.
But note: the queue could be any, so we abstract the queue operations.
Let's define:
class Queue:
def send_message(self, event_id, ordering_key):
pass
Then we have a concrete implementation (e.g., PostgreSQLDatabase).
We'll also have a config module.
Let's write the webhook endpoint:
code
from flask import Flask, request, jsonify
from database import Database
from queue import Queue
from config import Config
import hmac
import hashlib
app = Flask(__name__)
db = Database(Config.DATABASE_URL)
queue = Queue(Config.QUEUE_URL)
def verify_signature(payload, signature, secret):
expected = hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest()
return hmac.compare_digest(signature, expected)
@app.route('/webhook', methods=['POST'])
def webhook():
signature = request.headers.get('X-Webhook-Signature')
if not signature:
return 'Missing signature', 401
if not verify_signature(request.data, signature, Config.WEBHOOK_SECRET):
return 'Invalid signature', 401
event_id = request.headers.get('X-Event-ID')
if not event_id:
return 'Missing event ID', 400
ordering_key = request.headers.get('X-Ordering-Key', 'global')
payload = request.get_json()
# Check if event exists and is in terminal state
event = db.get_event(event_id)
if event and event.status in ['succeeded', 'failed']:
return 'Event already processed', 200
# If event exists and is not terminal, we assume it's already being processed and return 200.
if event and event.status in ['received', 'processing']:
return 'Event already received', 200
# Create new event
db.create_event(event_id, ordering_key, payload)
# Send to queue
queue.send_message(event_id, ordering_key)
return 'Accepted', 202
Worker:
code
import time
from database import Database
from queue import Queue
from config import Config
db = Database(Config.DATABASE_URL)
queue = Queue(Config.QUEUE_URL)
def calculate_backoff(retry_count):
# Exponential backoff with jitter
base = 2 # base seconds
max_backoff = 300 # 5 minutes
backoff = min(base * (2 ** retry_count), max_backoff)
jitter = random.uniform(0, 0.1 * backoff)
return backoff + jitter
while True:
message = queue.receive_message(wait_time_seconds=20) # long polling
if not message:
continue
event_id = message.body
event = db.get_event(event_id)
if event is None:
queue.delete_message(message)
print(f"Event {event_id} not found, deleting message")
continue
if event.status in ['succeeded', 'failed']:
queue.delete_message(message)
print(f"Event {event_id} already processed, deleting message")
continue
if event.status == 'processing':
# Duplicate delivery? Delete the message.
queue.delete_message(message)
print(f"Event {event_id} is already processing, deleting duplicate message")
continue
# Try to set to processing
rows_updated = db.update_event_status_to_processing(event_id)
if rows_updated == 0:
# Another worker set it to processing? Delete this message.
queue.delete_message(message)
print(f"Event {event_id} was set to processing by another worker, deleting message")
continue
try:
# Process the event (call the user-defined function)
process_event(event.payload)
db.mark_event_succeeded(event_id)
queue.delete_message(message)
print(f"Event {event_id} processed successfully")
except Exception as e:
print(f"Event {event_id} failed: {e}")
event.retry_count += 1
event.last_error = str(e)
db.save_event(event)
if event.retry_count >= Config.MAX_RETRIES:
db.mark_event_failed_permanently(event_id)
queue.delete_message(message)
print(f"Event {event_id} failed permanently")
else:
backoff = calculate_backoff(event.retry_count)
queue.change_message_visibility(message, backoff)
print(f"Event {event_id} will be retried in {backoff} seconds")
Admin endpoint (for replay):
code
from flask import Flask, request, jsonify, abort
from database import Database
from queue import Queue
from config import Config
app = Flask(__name__)
db = Database(Config.DATABASE_URL)
queue = Queue(Config.QUEUE_URL)
# We'll protect the admin endpoints with basic auth (simplified)
def check_auth(username, password):
return username == Config.ADMIN_USER and password == Config.ADMIN_PASSWORD
@app.route('/admin/events')
def list_events():
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
abort(401)
# Get query parameters for filtering
status = request.args.get('status', 'failed')
events = db.get_events_by_status(status) # We need to implement this in Database
return jsonify([event.to_dict() for event in events])
@app.route('/admin/events/<event_id>/replay', methods=['POST'])
def replay_event(event_id):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
abort(401)
event = db.get_event(event_id)
if not event:
abort(404)
if event.status != 'failed':
return jsonify({'error': 'Only failed events can be replayed'}), 400
# Reset the event
db.reset_event_for_replay(event_id)
# Send to queue
queue.send_message(event_id, event.ordering_key)
return jsonify({'status': 'replay scheduled'}), 202
In the Database class, we need:
code
def reset_event_for_replay(self, event_id):
# Set status to 'received', reset retry_count, clear last_error and processed_at.
sql = """
UPDATE events
SET status = 'received',
retry_count = 0,
last_error = NULL,
processed_at = NULL
WHERE event_id = %s AND status = 'failed'
"""
# Execute and check that we updated one row.
This is a basic framework.
Limitations and Improvements:
We are using a single queue. If we have high volume, we might need multiple queues? But then ordering keys must be in the same queue? So we must route by ordering key to the same queue? That's complex.
We are storing the entire payload in the database. If the payload is large, we might want to store it in object storage and keep a reference in the database.
We are not handling dead letter queues? We are marking as failed after max retries. We might want to move to a dead letter queue for further inspection.
The admin UI is very basic.
We are not providing a way to see the event payload in the admin UI? We should.
We are not providing a way to manually mark an event as succeeded or failed? Maybe not.
We are not handling the case where the worker crashes after processing but before deleting the message? Then the message will be redelivered and we will process again? But we have idempotency, so it should be safe.
We are not handling the case where the worker crashes after updating the event to 'processing' but before processing? Then the event will be stuck in 'processing'. We need a cleanup job that resets events that have been in 'processing' for too long.
We are using a fixed max retries? We can make it configurable per event type? Not in this design.
We are not providing a way to delay the processing of an event? (e.g., schedule for future) Not required.
We are not providing a way to prioritize events? Not required.
Given the requirements, this is a good starting point.
Conclusion:
We have drafted a webhook consumer framework with retries, signatures, idempotency, replay UI, and ordering keys.
The design uses a database for event storage and idempotency, and a queue (SQS) for asynchronous processing with ordering by key.
We have provided pseudocode for the main components.
Note: This is a simplified design and may need adjustments for production use.
Let me know if you have any questions or need more details on a specific part.
I'll outline a comprehensive webhook consumer framework that addresses all your requirements. This is a production-ready design pattern.
-- Main events table
CREATE TABLE webhook_events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
event_id VARCHAR(255) UNIQUE NOT NULL, -- From sender
source VARCHAR(100) NOT NULL, -- webhook source/type
ordering_key VARCHAR(255), -- For ordering
payload JSONB NOT NULL,
signature TEXT NOT NULL,
received_at TIMESTAMPTZ DEFAULT NOW(),
status VARCHAR(20) DEFAULT 'received',
processing_attempts INT DEFAULT 0,
last_error TEXT,
completed_at TIMESTAMPTZ,
metadata JSONB DEFAULT '{}' -- retry_count, etc.
);
-- Idempotency tracking (optimized for lookups)
CREATE INDEX idx_webhook_events_event_id ON webhook_events(event_id);
CREATE INDEX idx_webhook_events_ordering ON webhook_events(ordering_key, received_at)
WHERE status != 'completed';
-- Replay audit log
CREATE TABLE replay_audit (
id SERIAL PRIMARY KEY,
event_id VARCHAR(255) NOT NULL,
replayed_by VARCHAR(100),
replayed_at TIMESTAMPTZ DEFAULT NOW(),
reason TEXT,
FOREIGN KEY (event_id) REFERENCES webhook_events(event_id)
);
3. Worker with Retry Logic
python
import asyncio
from tenacity import (
retry,
stop_after_attempt,
wait_exponential_jitter,
retry_if_exception_type
)
class WebhookWorker:
def __init__(self, db, queue, max_retries=3):
self.db = db
self.queue = queue
self.max_retries = max_retries
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential_jitter(initial=1, max=60),
reraise=True
)
async def process_event(self, event: dict):
"""Process webhook with automatic retry on transient failures"""
try:
# Your business logic here
await self.handle_webhook(event['payload'])
# Mark as completed
await self.db.mark_completed(
event_id=event['event_id'],
success=True
)
except TransientError as e:
# Will be retried by tenacity
raise
except PermanentError as e:
# Won't be retried
await self.db.mark_completed(
event_id=event['event_id'],
success=False,
error=str(e)
)
# Send to dead letter queue
await self.queue.send_to_dlq(event)
4. Ordering Key Implementation
python
class OrderedQueue:
"""Queue that preserves ordering per key"""
def __init__(self, redis_client):
self.redis = redis_client
async def enqueue(self, event: dict):
"""Enqueue with ordering key partitioning"""
ordering_key = event.get('ordering_key', 'default')
# Use sorted set per ordering key
# Score = timestamp + sequence for deterministic ordering
score = self._calculate_score(event)
await self.redis.zadd(
f"queue:{ordering_key}",
{event['event_id']: score}
)
# Notify workers
await self.redis.publish(f"channel:{ordering_key}", event['event_id'])
Worker consumption pattern:
python
async def consume_ordering_key(ordering_key: str):
"""Single worker per ordering key for strict ordering"""
while True:
# Get next event for this key (atomic pop)
event_id = await redis.zpopmin(f"queue:{ordering_key}")
if event_id:
event = await db.get_event(event_id)
await process_event(event)
5. Replay UI Endpoints
python
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
router = APIRouter(prefix="/admin/webhooks")
class ReplayRequest(BaseModel):
event_ids: list[str]
reason: str
force: bool = False # Bypass idempotency check
@router.post("/replay")
async def replay_events(
request: ReplayRequest,
current_user: User = Depends(get_admin_user)
):
"""Replay specific events"""
results = []
for event_id in request.event_ids:
event = await db.get_event(event_id)
if not event:
results.append({"event_id": event_id, "status": "not_found"})
continue
# Idempotency check
if event['status'] == 'completed' and not request.force:
results.append({
"event_id": event_id,
"status": "already_processed",
"completed_at": event['completed_at']
})
continue
# Reset for replay
await db.reset_for_replay(event_id)
# Re-enqueue with same ordering key
await queue.enqueue(event)
# Audit log
await db.log_replay(event_id, current_user.id, request.reason)
results.append({"event_id": event_id, "status": "replayed"})
return {"results": results}
@router.get("/events")
async def list_events(
source: str = None,
status: str = None,
ordering_key: str = None,
start_date: datetime = None,
end_date: datetime = None,
page: int = 1,
limit: int = 50
):
"""Paginated event list with filters"""
filters = {}
if source: filters['source'] = source
if status: filters['status'] = status
if ordering_key: filters['ordering_key'] = ordering_key
events = await db.query_events(
filters=filters,
start_date=start_date,
end_date=end_date,
page=page,
limit=limit
)
total = await db.count_events(filters)
return {
"events": events,
"pagination": {
"page": page,
"limit": limit,
"total": total,
"pages": (total + limit - 1) // limit
}
}
Ordered processing per business key (customer_id, account_id, etc.)
Secure verification with timestamp replay protection
Operational visibility through replay UI and metrics
Resilient processing with configurable retries and DLQ
Scalable architecture that handles high throughput
Would you like me to elaborate on any specific component or provide implementation details for a particular queueing system (Redis, RabbitMQ, Kafka, AWS SQS)?
We have a table `processed_events` with:
event_id (primary key)
status (succeeded, failed)
processed_at
When we receive a webhook, we check if event_id exists in `processed_events` and if the status is 'succeeded', we don't process again. But if we reset the event in the main events table, we also need to reset the `processed_events` table? Or we can remove the entry from `processed_events`? But then we lose the history.
Alternatively, we can have the idempotency check on the main events table? We can check the status of the event in the main events table. But note: we might have multiple events with the same event_id? No, event_id is unique.
So, we can do:
When receiving a webhook:
BEGIN TRANSACTION
INSERT INTO events (event_id, ...) ON CONFLICT (event_id) DO NOTHING? But we want to update if it exists? Actually, we don't want to update the existing event because we want to keep the original. So we do:
If the event_id exists in events table and the status is not 'received' (i.e., it's been processed) then we return 200.
But if we are replaying, we set the status back to 'received', so then the next time we try to process, we will process again.
However, note: the webhook receiver might get the same event multiple times (due to retries from the sender). We want to ignore duplicates. So we must check the events table for the event_id and if it's already in a terminal state (succeeded or failed) then we ignore.
So the idempotency check is: if the event exists and status in ('succeeded', 'failed') then ignore.
But when we replay, we set the status to 'received', so then it will be processed again.
So we need two tables:
1. events: stores all events (even duplicates? but we don't store duplicates because event_id is unique). Actually, we only store unique event_id. So if we receive the same event again, we don't insert a new row, we check the existing row.
So the flow:
- Receive webhook with event_id.
- Check if event_id exists in events table.
- If exists and status is 'succeeded' or 'failed', then return 200 (already processed).
- If exists and status is 'received' or 'processing', then we might be already processing? We can return 200? Or we can let it be processed again? But we don't want two workers processing the same event. So we should have a lock? Or we can use the status to avoid duplicate processing.
We can do:
UPDATE events SET status = 'processing' WHERE event_id = ? AND status = 'received'
If the update returns 0 rows, then it means the event is not in 'received' state (maybe already processing or succeeded/failed). Then we return 200.
But then we have a race condition? We can use a database lock or atomic update.
Alternatively, we can have a separate table for in-progress events? Or use a queue that guarantees at-least-once? But we want at-most-once? Actually, we want to process each event at least once, but we don't want to process the same event concurrently.
Given the complexity, let's simplify:
We are going to use a message queue (like RabbitMQ, Kafka, or AWS SQS) that supports ordering by key? Not all do. Alternatively, we can have a single queue and have the worker process one event at a time? But that doesn't scale.
Alternatively, we can have multiple queues per ordering key? But then we need to manage many queues.
Given the requirement for ordering keys, we can:
- Partition the events by ordering key. Each ordering key goes to a specific partition (queue). Then we can have multiple consumers for different partitions, but within a partition, order is preserved.
But if we have many ordering keys, we might have many partitions. We can use a consistent hashing to map ordering key to a fixed number of partitions (say 10). Then we have 10 queues, and each queue is processed by one worker at a time? Or we can have multiple workers per queue but only one active? That's complex.
Alternatively, we can use a database as a queue with row-level locking? But that might be slow.
Let's assume we are using a message queue that does not support ordering by key. Then we have to enforce ordering in the application:
- We have a table `event_locks` with `ordering_key` and a flag. When we want to process an event with a given ordering_key, we try to acquire the lock for that ordering_key. If we get the lock, we process and then release. If we don't, we put the event back in the queue (or wait and retry later). This is complex and can lead to deadlocks.
Given the complexity, let's assume we are using a queue that supports ordering by a key (like Amazon SQS with message group ID). Then we can set the message group ID to the ordering key. Then SQS will guarantee that messages with the same group ID are processed in order by the same consumer (but note: SQS only guarantees order within a group, and if you have multiple consumers, a group is processed by one consumer at a time). So we can set the message group ID to the ordering key.
But note: if we have too many distinct ordering keys, we might have too many groups and SQS might not scale? But it should be okay.
So, steps:
- When we receive a webhook and pass the idempotency check, we send a message to SQS with:
- Message body: event_id (and maybe the payload? but we have the payload in the database, so we can just send the event_id)
- Message group ID: ordering_key (if provided, else use a default, e.g., 'global').
- The worker receives the message, gets the event_id, fetches the event from the database, and processes it.
- If processing fails, we retry (with exponential backoff). We update the event record with retry count and last error. We also update the status to 'processing' when we start, and then to 'succeeded' or 'failed' when done.
But note: SQS will redeliver the message if we don't delete it. So we must be cautious: if we fail to process and we want to retry, we don't delete the message and let SQS redeliver? But then we might get the same event again and again. We want to control the retry with backoff. So we can:
- On failure, we don't delete the message and set a visibility timeout to the next retry time? But SQS doesn't let us set arbitrary visibility timeout per message? Actually, it does. We can change the visibility timeout of the message to the next retry time (with exponential backoff). Then we don't delete the message until we succeed.
But then we are using SQS as a retry mechanism. However, we also have our own retry count in the event record. We can do:
- When we receive a message, we check the event's retry_count. If it's over the max, we delete the message and mark the event as failed.
- Otherwise, we try to process. If it fails, we update the event's retry_count and set the message's visibility timeout to (backoff time). Then we don't delete the message.
But note: if the worker crashes after processing but before deleting the message, the message will become visible again and we will process again. So we must make the processing idempotent.
Alternatively, we can delete the message only on success? And on failure, we update the event and let the message become visible again (with the default visibility timeout). But then we don't control the backoff? We can set the visibility timeout on failure to the next retry time.
Let's do:
Worker:
while true:
message = receive_message()
event_id = message.body
event = get_event(event_id)
if event.retry_count >= max_retries:
delete_message(message)
mark_event_failed(event)
continue
try:
process_event(event)
delete_message(message)
mark_event_succeeded(event)
except Exception as e:
event.retry_count += 1
event.last_error = str(e)
save_event(event)
# Set the message's visibility timeout to the next retry time (based on retry_count)
change_message_visibility(message, backoff_seconds(event.retry_count))
But note: if the worker fails after updating the event but before changing the visibility, then the message will become visible again immediately and we will process again (and the retry_count will be incremented again). That's acceptable? It might cause more retries than intended? But it's safe because we are using the event's retry_count to limit.
Alternatively, we can not change the visibility and just let the message become visible after the default (e.g., 30 seconds). Then we don't need to change the visibility. But then we don't have exponential backoff? We can have the worker sleep? Not ideal.
Given the complexity, let's assume we are using a queue that doesn't support per-message visibility timeout. Then we can:
- On failure, we don't delete the message and let it become visible again after the queue's default visibility timeout (say 30 seconds). Then we will retry after 30 seconds, then 60, then 120? But we can't change the visibility per retry.
So we might need to implement our own retry queue? Or use a queue that supports delayed retries (like SQS with delay seconds per message).
Given the time, let's assume we are using SQS and we can change the visibility timeout.
But note: the ordering key (message group ID) will cause messages with the same group to be processed by the same consumer. If we change the visibility timeout, the message will be delayed for that consumer, but other consumers might pick up other groups. So ordering is preserved.
- We check the current status of the event.
- If the event is in a terminal state (succeeded or failed), we reset it to 'received' and also reset the retry_count and clear the last_error.
- Then we send a new message to the queue (with the same event_id and ordering_key). But note: the event_id is already in the events table, so we don't insert a new row, we update the existing row.
However, we must be cautious: if the event was succeeded and we reset, then we are going to process it again. This might be acceptable if the processing is idempotent? But if it's not, then we have a problem.
Alternatively, we can only allow replay of failed events? We can add a configuration: REPLAY_ALLOWED_STATUSES = ['failed'].
But the requirement says "replay UI", so we might want to replay any event. We can have a warning for succeeded events.
Implementation:
In the admin UI, when the user clicks replay, we send a POST request to an admin endpoint (with event_id).
The endpoint:
event = get_event(event_id)
if event.status not in ['succeeded', 'failed']:
return error ("Event is not in a terminal state")
if event.status == 'succeeded' and not config.ALLOW_REPLAY_SUCCEEDED:
return error ("Replaying succeeded events is not allowed")
# Reset the event
event.status = 'received'
event.retry_count = 0
event.last_error = None
event.processed_at = None
save_event(event)
# Send to queue
send_to_queue(event_id, event.ordering_key)
But note: if the event was already in the queue (because we are still processing it) then we might have duplicate? But we reset the status to 'received', so when the original message is processed, it will try to process again? Actually, we are sending a new message. So we might have two messages for the same event? That's bad because we are using the event_id for idempotency. The worker will see the same event_id and if the first one is still processing (status='processing') then the second one will see status='processing' and skip? But we reset the status to 'received'. So the first one might still be processing and the second one will also try to process? We might have two workers processing the same event at the same time.
So we need to be careful: when we reset, we must ensure that there is no in-progress processing for that event. We can check the status: if it's 'processing', we cannot reset? Or we can wait until it's done? But we are in an admin UI, we might want to force replay.
Alternatively, we can design the worker to be safe for concurrent processing of the same event? But that's hard.
Let's change the idempotency check:
We have a table `event_locks` (or we use the events table with a status and a lock). When a worker starts processing an event, it sets the status to 'processing' and also sets a lock (maybe a timestamp or a worker id). Then when another worker comes, it sees the event is 'processing' and skips? But then if the worker crashes, the event will be stuck in 'processing'.
We can have:
events table:
event_id (PK)
status: 'received', 'processing', 'succeeded', 'failed'
processing_started_at (nullable)
retry_count
...
When a worker picks an event (from the queue), it does:
UPDATE events
SET status = 'processing', processing_started_at = NOW()
WHERE event_id = ? AND status = 'received'
If the update returns 0, then the event is not in 'received' state (maybe already processing or succeeded/failed). Then the worker will not process and will delete the message? But then the message is gone and the event is stuck in 'processing'? So we need a way to reset events that are stuck.
Given the complexity, let's keep it simple:
We are using a queue that delivers each message only once? But we might have duplicates? We are using event_id for idempotency, so we can have duplicate messages but we will ignore if already processed.
So, when we replay, we send a new message. The worker will pick up the new message and then check the event status. If the event is already 'succeeded', it will skip? But we reset the event to 'received', so it will process again.
But what if the original message (for the same event) is still in the queue? Then we might have two messages for the same event in the queue? That's possible because we are sending a new message without deleting the old one? Actually, the old message might have been processed already and deleted? Or it might be in the queue.
If the old message is still in the queue, then we will have two messages for the same event. The first one that is processed will set the status to 'processing' and then to 'succeeded' (if successful). Then the second one will see the event is already 'succeeded' and skip? But wait: we reset the event to 'received' when we replay. So if the old message is processed first, it will set to 'succeeded'. Then the new message (replay) will see the event is 'succeeded' and skip? But we want the replay to be processed. So we must reset the event before sending the new message? But then the old message (if still in the queue) will see the event as 'received' and process again? So we might have two processing for the same event.
This is a problem.
To avoid this, we must ensure that when we replay, we remove the old message from the queue? But we don't have the old message's handle? We don't store the queue message ID.
Alternatively, we can design the queue to be exactly-once? That's hard.
Given the constraints, let's change the design:
We store the event in the database and then send a message to the queue with the event_id. The queue message does not contain the event data, just the event_id.
The worker, when it receives a message, does:
event = get_event(event_id)
if event.status in ['succeeded', 'failed']:
# Already processed, so delete the message and skip.
delete_message(message)
continue
if event.status == 'processing':
# This should not happen? But if it does, we can wait? Or we can assume that the worker that set it to processing crashed and we need to reset? We can have a timeout for processing?
# Let's assume we don't get the same event in two messages at the same time because we are using a queue that doesn't deliver the same message twice? But we are using idempotency to avoid duplicates.
# Actually, we are using the event status to avoid duplicate processing. So if we see 'processing', we can wait and then check again? Or we can delete the message and let the original processing continue? But then the message is lost and the event will never be marked as succeeded? We need to delete the message only after we have processed the event? So we cannot delete the message until we are done.
# So, if we see 'processing', we should not delete the message and wait? But then we are stuck.
# Alternatively, we can set a processing timeout. If the event is in 'processing' for more than X minutes, we reset it to 'received'? That's a cleanup job.
Then, we set the event to 'processing' and process.
So, when we replay, we reset the event to 'received'. Then, if the old message is still in the queue, it will see the event is 'received' and try to process. But we are also sending a new message. So we might have two messages for the same event. The first one that gets the lock (by updating the event to 'processing') will process, the second one will see the event is 'processing' and then what? We can:
- The second one, when it sees 'processing', can wait and then check again? But that might be complex.
- Or, we can delete the message and then re-enqueue? But then we lose the message? We don't want to lose the message.
Let's change the worker:
while true:
message = receive_message()
event_id = message.body
event = get_event(event_id)
if event.status in ['succeeded', 'failed']:
delete_message(message)
continue
if event.status == 'processing':
# We are already processing this event? Then we delete this message and let the original processing continue? But then we lose the message? Actually, we have two messages for the same event? That's a duplicate delivery by the queue? We don't want to process twice.
# So we delete this duplicate message and continue.
delete_message(message)
continue
# Now event.status is 'received'
# Try to set to 'processing'
rows_updated = update_event_status_to_processing(event_id)
if rows_updated == 0:
# Someone else set it to processing? Then delete this message and continue.
delete_message(message)
continue
try:
process_event(event)
mark_event_succeeded(event)
delete_message(message)
except Exception as e:
mark_event_failed(event) # and maybe set status back to 'received'? No, we leave it as failed? But then we want to retry? So we set status to 'failed' but we also have retry_count. We are using the message visibility for retry? Or we are retrying by re-enqueueing?
# We are using the queue for retry? We are not deleting the message on failure? Then we must change the visibility timeout? But we are using the event's retry_count to limit.
# Let's decide: we are going to use the queue for at-least-once delivery and we control retry with the event's retry_count and the message's visibility.
# So on failure, we update the event's retry_count and then change the message's visibility timeout to the next retry time? And then we don't delete the message.
# But then we are not deleting the message until success? So we must change the visibility timeout on failure and then not delete? Then when the message becomes visible again, we will process again.
# But note: we are updating the event's retry_count and the message's visibility. If the worker crashes after updating the event but before changing the visibility, then the message will become visible again immediately and we will process again (and the retry_count will be incremented again). That's acceptable.
# So:
event.retry_count += 1
save_event(event)
if event.retry_count >= max_retries:
delete_message(message)
mark_event_failed_permanently(event) # status = 'failed'
else:
change_message_visibility(message, backoff_seconds(event.retry_count))
This way, we avoid two workers processing the same event because we update the event status to 'processing' and only one worker can do that.
Now, when we replay:
We reset the event to 'received' and set retry_count to 0, and then send a new message to the queue.
The old message (if still in the queue) will be delivered and the worker will see the event is now 'received' (because we reset) and try to process. But then we have two messages for the same event? And the first one that updates the event to 'processing' will process, the second one will see the event is now 'processing' and delete the message? That's acceptable.
But note: when we reset, we might reset while the old message is being processed? Then the old message might have set the event to 'processing' and then we reset to 'received'? Then the new message will also try to process? We have a race condition.
To avoid this, we must not reset the event if there is a message in the queue for the same event? But we don't know that.
Alternatively, we can have a flag in the event that indicates it's being replayed? And then the worker, when it sees the event is 'received' but there is a replay flag? Not helpful.
Given the complexity, let's accept that replay might cause duplicate processing if there is an old message in the queue. But we are using the event status and the atomic update to avoid two concurrent processing. So at most one of the two messages (old or new) will be processed at a time. And after one is processed and succeeds, the other will be deleted (because the event will be 'succeeded')? But if we reset the event to 'received' and then the old message is processed and succeeds, then the event is 'succeeded'. Then the new message (replay) will see the event is 'succeeded' and delete the message? So the replay won't be processed? That's not what we want.
So we must reset the event and then also remove the old message? But we don't have the old message's handle.
Alternatively, we can design the replay to create a new event with a new event_id? But then we break ordering? Because the ordering key might be the same? But if we create a new event, then the ordering key is the same? Then we want to process the new event in order? But if the original event (old) is still in the queue, then we might have:
Original event (event_id=1, ordering_key=A) -> in queue
Replay event (event_id=2, ordering_key=A) -> in queue
Then the worker will process event 1 and then event 2? But what if event 1 is stuck in 'processing'? Then event 2 might be processed first? That breaks ordering.
So, to preserve ordering, we must process the replay event in the same order as the original? That is very hard.
Given the complexity, let's assume:
We are going to allow replay only for failed events? And we are going to reset the event and then send a new message. And we accept that if the original message (for the same event) is still in the queue, then we might have two messages for the same event, but the worker will only process one because of the status update.
But if the original event was failed and we reset, then the original message (if still in the queue) will be processed and then the replay message will be processed? But the original event was failed, so we reset to 'received'. Then the original message (which is for the same event) and the replay message (same event) will both be for the same event_id. The first one to get the lock will process, the second will see the event is 'processing' and delete the message? So we will process only once? That's acceptable.
However, if the original message was already processed (and succeeded) and we reset, then the original message (if still in the queue) will be processed and set the event to 'processing' and then succeed? Then the replay message will see the event is 'succeeded' and delete? So the replay won't be processed? That's not what we want.
So, we must only allow replay for failed events? Then the original event is in 'failed' state, so the original message (if any) would have been processed and failed? Actually, if the event failed, then the original message would have been processed and failed, and then the message would have been deleted? Or not? In our worker, on failure we don't delete the message until we reach max retries? So if the event failed (and we reached max retries) then we delete the message? So there should be no message in the queue for a failed event? But what if we are still retrying? Then the event is in 'failed'? Actually, we have:
- If the event is in 'failed', it means we have exhausted retries and we have deleted the message? So there is no message in the queue.
So, for failed events, there is no message in the queue. Then when we reset and send a new message, there is only one message.
So, let's change: we only allow replay for events that are in 'failed' state. Then we are safe.
But the requirement says "replay UI", which might imply replaying any event. But we can limit to failed events for safety.
Alternatively, we can have a way to remove the old message from the queue? But we don't have the handle.
Given the time, let's design for replaying only failed events.
Steps for replay:
- Admin UI: list events with status='failed' and allow replay.
- When replaying, reset the event to 'received', reset retry_count, and send a new message to the queue.
Then, the worker will process the event again.