We are going to design a webhooks reliability framework that includes:
- Signature rotation: to enhance security, we'll rotate the secret keys used for signing the webhook payloads.
- Exponential backoff: for retrying failed webhook deliveries.
- Dead-letter storage: to store events that could not be delivered after maximum retries.
Assumptions:
- We are building a system that sends webhooks to multiple consumers (subscribers).
- Each subscriber has a list of active signing keys (for rotation) and a webhook URL.
- We have a database to store events, their status, and retry attempts.
Components:
-
Event Ingestion:
- When an event occurs, we create an event record in the database with status 'pending'.
- We sign the payload with the current primary key of the subscriber (or the current active key).
-
Delivery Worker:
- A worker that picks up pending events and attempts to deliver them to the subscriber's URL.
- It uses the current active signing key (from the subscriber's key list) to sign the request.
- On failure (non-2xx response or network error), it will retry with exponential backoff.
-
Key Management:
- Subscriber has a list of keys (each with a key id, secret, and whether it's active/primary).
- We rotate keys by deactivating the old primary and activating a new one. The old key is kept for verification for a while (until all events signed with it are delivered or dead-lettered).
-
Retry Mechanism:
- Each event has a retry count and a next retry time.
- When a delivery fails, we schedule the next attempt with exponential backoff (with jitter to avoid thundering herd).
- After max retries, the event is moved to dead-letter storage.
-
Dead-letter Storage:
- Events that fail after max retries are stored in a dead-letter queue/table for manual inspection and replay.
-
Verification on Receiver Side:
- The receiver (subscriber) can verify the signature using the public key (if using asymmetric) or the shared secret (symmetric). We assume symmetric for simplicity, but note that rotation requires the receiver to have multiple keys.
-
Monitoring and Alerts:
- We should monitor the dead-letter queue and alert on high failure rates.
Implementation Details:
Database Schema:
Subscribers:
id
url
current_key_id (foreign key to Keys)
... other fields
Keys:
id
subscriber_id
key_secret (hashed, or encrypted if asymmetric, but for symmetric we store the secret hashed? Actually, we need to sign so we need the secret. But we should store it encrypted at rest.)
is_active (boolean) -- the current primary key
created_at
rotated_at (nullable) -- when this key was rotated (deactivated)
Events:
id
subscriber_id
payload (JSON or text)
status: ['pending', 'delivered', 'failed', 'dead_letter']
retry_count (default 0)
next_retry_at (timestamp, for scheduling)
last_attempt_at (timestamp)
last_error (text)
signature (the signature we generated for this event, so that we can verify on the receiver side and also for our own reference)
key_id (the key that was used to sign this event) -- important because if we rotate keys, we still need to verify with the old key until it's expired.
DeadLetters:
event_id (foreign key to Events)
reason
created_at
Alternatively, we can keep dead-letter events in the Events table with status 'dead_letter' and have a separate table for dead-letter metadata? Or just use the Events table and mark them as dead_letter.
Let's do:
Events:
... as above, with status including 'dead_letter'
And a DeadLetter table for additional metadata? Not necessary, we can just have a reason in Events? But reason might be multiple. Let's keep it simple and have:
Events:
...
dead_letter_reason (nullable)
And when an event becomes dead-letter, we set status='dead_letter' and set dead_letter_reason.
But note: we might want to replay dead-letter events. So we need to be able to change status back to pending? Or have a separate replay mechanism.
Alternatively, we can have a separate table for dead-letter events that are archived, and the Events table is only for active (pending, delivered, failed) and dead-letter events are moved to DeadLetters table and removed from Events? But then we lose the original event id? We can keep the event id as a foreign key.
Let's do:
Events: for active events (pending, delivered, failed) and dead-letter events are moved to DeadLetters and removed from Events? But then we cannot retry by just updating the Event? We might want to retry dead-letter events.
Another idea: keep all events in Events, and have a boolean is_dead_letter? Or status='dead_letter'. Then we can change status back to pending if we want to retry.
We'll do:
Events:
id
...
status: enum('pending', 'delivered', 'failed', 'dead_letter')
dead_letter_reason (nullable, set when status becomes dead_letter)
And we can have a separate table for retry attempts? Not necessary, we have retry_count and next_retry_at.
But note: when we rotate keys, the event was signed with an old key. The receiver must still be able to verify with the old key until the event is either delivered or dead-lettered.
So in the Events table, we store the key_id that was used to sign the event. Then, when we attempt delivery, we use that same key to sign again? Actually, we are going to sign the same payload again? But the payload might change? We are going to send the same event again, so we should use the same key that was used originally? But if the key is rotated, the receiver might not have the old key. So we must ensure that the receiver keeps the old key for verification until all events signed with it are either delivered or dead-lettered.
Alternatively, we can change the signature on retry? That would break verification if the receiver only has the new key. So we must use the same key for retries.
Therefore, in the Events table, we store the key_id that was used for the initial signature, and on each retry we use that same key.
But what if the key is deleted from our system? We should not delete keys until all events signed with that key are either delivered or dead-lettered? Or we keep the key secret for verification until we are sure the receiver has rotated? Actually, the receiver must keep the old key until they have processed all events signed with it. So we can set an expiration on the key? Or we can have a policy: when we rotate a key, we mark the old key as inactive but keep it for verification for a certain period (e.g., 30 days). Then, after 30 days, we can delete it. But if there are events older than 30 days that are still pending? We should not have pending events for that long.
So:
When rotating keys:
1. Create a new key, set it as active.
2. Set the old key's is_active to false, and set rotated_at to now.
3. We will not use the old key for new events, but we keep it for verification of old events until we are sure the receiver has rotated? Actually, the receiver must keep the old key until they have processed all events. We don't control the receiver.
So we must store the key secret for as long as we might have events signed with that key. Since we have a max retry period (e.g., 7 days) and then dead-letter, we can delete the key after, say, 30 days? But note: the receiver might take longer to process? We cannot assume.
Alternatively, we can use asymmetric keys (public/private). Then we can sign with the private key and the receiver verifies with the public key. When we rotate, we generate a new key pair. The receiver must have multiple public keys? They can have a key id in the signature header and look up the corresponding public key. Then we can keep the old private keys for as long as we need to verify old events? But we are the sender, we only need the private key to sign. We don't need to verify. The receiver needs the public key.
So if we use asymmetric, then:
- We generate a key pair for each rotation.
- The receiver must be given the public key (and key id) for each rotation? Actually, the receiver must have a way to get the public key for the key id that we use in the signature.
But in our system, we are the sender and we have multiple subscribers. Each subscriber has their own set of keys? Or we have a global set of keys? Let's assume per-subscriber keys.
So:
Subscriber has a list of keys (each with a key id, private key, and public key). The receiver (the subscriber's server) must have the corresponding public key for each key id we might use.
How does the receiver get the public keys? They are provided out-of-band? Or we have an endpoint where they can fetch the public key by key id? But then we have to host that.
Alternatively, we can use symmetric keys and share the same secret. Then when we rotate, we give the new secret to the receiver and they must keep the old one for a while.
Given the complexity of key distribution, maybe we stick with symmetric and have a process to share the new secret with the receiver. Then the receiver must be configured with multiple secrets? Or we rotate the secret and the receiver must update at the same time? That is error-prone.
So asymmetric might be better because the receiver only needs the public key, which we can publish without secret. But then we have to manage a key registry for the receiver.
Considering the scope, let's stick with symmetric for simplicity in the design, but note that in practice asymmetric is more common for webhook signatures (like GitHub uses).
However, for the purpose of this design, we'll use symmetric and assume that the receiver has multiple secrets (one for each key) and they can look up by key id.
How do we include the key id in the request? We can have a header: X-Webhook-Key-Id: <key_id> and then the signature header: X-Webhook-Signature: <signature>.
The receiver then:
1. Looks up the secret for the given key id (from their configuration).
2. Computes the signature of the payload with that secret.
3. Compares with the provided signature.
If they don't have the key id, they reject.
So in our system, for each event, we store the key_id that was used.
Steps for delivery:
1. Fetch an event that is pending and next_retry_at <= now, and for which the subscriber's current_key_id is set (but note: the event was signed with an old key? Actually, we use the key stored in the event, not the subscriber's current key unless it's a new event).
2. For a new event (being sent for the first time), we use the subscriber's current_key_id.
3. For a retry, we use the same key_id that was used in the original event (stored in the event).
But what if the subscriber's current_key_id has changed? We still use the old key for that event? Yes, because the receiver still has that old key? We assume they keep all old keys for verification.
However, if the receiver has removed the old key, then verification will fail. That's a problem. So we must coordinate rotation: we rotate the key on our side and tell the receiver to rotate at the same time? And then we must ensure that all events signed with the old key are either delivered or dead-lettered before we deactivate the key on the receiver? That's a coordination problem.
Alternatively, we can have a grace period: after we rotate, we keep the old key active for verification for, say, 7 days (or until all events are delivered). Then we tell the receiver they can remove the old key after 7 days.
So in our system, we don't delete the key from the Keys table until we are sure no pending events are using it? Or we mark it as inactive but keep it in the database for verification? We must keep the secret to be able to sign retries? Actually, we don't need to sign with the old key for retries? Wait, we are signing the same payload with the same key for retries. So we need the old secret to sign the retry. Therefore, we must keep the old key secret in our database until all events signed with it are either delivered or dead-lettered.
How do we know when we can delete an old key?
- An event is signed with a key_id. If all events with that key_id are in a terminal state (delivered or dead_letter) then we can delete the key? But what if there are no events at all with that key? Then we can delete immediately.
So we can have a background job that:
- For each key that is not active (rotated) and has no pending events (events with status in ['pending', 'failed'] and that key_id), then we can delete the key.
But note: we might have a lot of keys and we don't want to scan all events for each key. We can have a counter per key? Or we can have a job that runs periodically and checks.
Alternatively, we can set an expiration on the key (e.g., keep for 30 days after rotation) and then delete regardless? But if there is an event that is stuck in pending for more than 30 days, we might lose the ability to sign it? That event would then fail because we don't have the key. So we must ensure that events don't stay pending for too long. Our max retry period should be less than the key retention period.
Let's set:
- Max retry period: 7 days (with exponential backoff, the last retry might be after 7 days? We can set the initial retry delay and max retries so that the total time is less than 7 days).
- Key retention: 30 days.
Then, after 30 days of rotation, we delete the key. But if there is an event that is still pending after 30 days? That event would have been retried for 7 days and then become dead-letter. So it should not be pending after 7 days. So we are safe.
Steps for key rotation:
1. Create a new key (with a new key_id, and a new secret). Set it as active for the subscriber.
2. Update the subscriber's current_key_id to the new key.
3. Mark the old key as inactive (set is_active=false, rotated_at=now).
4. The old key remains in the database for 30 days (or until all events with that key are in terminal state, whichever comes first? Actually, we can delete after 30 days regardless, but we must ensure no events are pending after 7 days, so by 30 days there should be none).
But what if we want to rotate keys more frequently? We can, but we must keep the old key for at least the max retry period (7 days) plus some buffer.
Implementation:
We'll assume we have a cron job that runs every day and deletes keys that are inactive and rotated_at <= now - 30 days.
Now, the delivery worker:
- It picks events where status in ['pending', 'failed'] and next_retry_at <= now.
- It orders by next_retry_at (or priority?).
Steps for each event:
1. Fetch the event and the subscriber.
2. Fetch the key that was used to sign the event (from event.key_id). If the key is not found (maybe deleted?), then fail the event and set dead_letter reason: "signing key not found".
3. If the event is being sent for the first time (retry_count==0) and we are using the current_key_id? Actually, for a new event, we set the key_id to the subscriber's current_key_id at the time of creation. So we always use the key stored in the event.
4. Sign the payload with the key's secret (using HMAC for symmetric). Create the signature header and the key id header.
5. Send the HTTP request to the subscriber's URL with the headers and the payload.
6. If the response is 2xx, mark the event as delivered.
7. If not, then:
- Increment retry_count.
- If retry_count < max_retries (say 5), then calculate next_retry_at using exponential backoff with jitter.
- Set status to 'failed' (or keep as 'pending'? We have a status 'failed' for when we are going to retry? Actually, we can have status 'pending' for events that are scheduled for retry, and 'failed' for events that have failed but will retry? Or we can have status='retrying'? Let's keep it simple:
status='pending' for events that are waiting for first delivery or next retry.
status='failed' for events that have failed but will retry? Actually, we don't need a separate status for that. We can just have:
status:
'pending' -> waiting for first delivery or next retry.
'delivered' -> success.
'dead_letter' -> failed after max retries.
So when we fail, we set next_retry_at and leave status as 'pending'. But then how do we know it's a retry? We have retry_count>0.
Alternatively, we can have:
status:
'pending' -> never attempted or scheduled for retry? Actually, we can have:
- When created: status='pending', retry_count=0, next_retry_at=now (or a small delay for batching?).
But we might want to batch the first delivery? Let's not for simplicity.
- If retry_count >= max_retries, then set status='dead_letter' and dead_letter_reason='max retries exceeded'.
8. If there's a network error (like timeout, connection error), we treat as failure and retry.
We must be careful about idempotency: the same event might be delivered multiple times. The receiver should be idempotent.
For the dead-letter storage, we already have the event in the Events table with status='dead_letter'. We can have a separate table for dead-letter metadata, but it's not necessary.
However, we might want to store the failure reason and the last response? We have last_error and last_attempt_at.
We can have a table for delivery attempts? But for simplicity, we just update the event with the last error.
We might want to keep a history of attempts? Not required, but useful for debugging. We can have a DeliveryAttempts table:
id
event_id
attempted_at
success (boolean)
response_code (nullable)
response_body (nullable, truncated)
error_message (nullable)
Then we can log each attempt. But that can be a lot of data. We can do it optionally.
For the design, we'll keep it simple and just store the last attempt in the event.
Now, the code structure:
We'll have:
- A service that creates events (ingestion).
- A delivery worker (can be a separate process) that processes events.
- A key management service (to rotate keys).
Let's write pseudo-code for the delivery worker:
while true:
event = db.query("""
SELECT * FROM events
WHERE status = 'pending'
AND next_retry_at <= NOW()
AND subscriber_id IN (SELECT id FROM subscribers WHERE active = true)
ORDER BY next_retry_at
LIMIT 1
FOR UPDATE SKIP LOCKED -- to avoid multiple workers picking the same event
""")
if not event:
sleep(10)
continue
subscriber = event.subscriber
# Fetch the key that was used for this event
key = db.query("SELECT * FROM keys WHERE id = ? AND subscriber_id = ?", event.key_id, subscriber.id)
if not key:
# This should not happen if we don't delete keys that are in use, but if it does, dead-letter.
event.status = 'dead_letter'
event.dead_letter_reason = 'signing key not found'
db.save(event)
continue
# Sign the payload
payload = event.payload # we might store the payload as JSON, but we need to send exactly what we signed.
signature = hmac_sha256(key.key_secret, payload) # we need to define the exact signing format.
# Usually, we sign the raw body? Or we can have a canonical representation? We'll assume we sign the raw JSON string as stored.
# But note: if we re-serialize the JSON, it might change (ordering, whitespace). So we must store the exact string that we signed.
# Alternatively, we can store the payload as text and sign that text. Then when retrying, we send the same text.
# So in the Events table, we store the payload as text (the raw JSON string) and we sign that string.
headers = {
'Content-Type': 'application/json',
'X-Webhook-Key-Id': key.id,
'X-Webhook-Signature': signature
}
try:
response = requests.post(subscriber.url, data=payload, headers=headers, timeout=10)
if 200 <= response.status_code < 300:
event.status = 'delivered'
event.retry_count = 0 # reset? not necessary.
db.save(event)
else:
raise Exception(f"Non-2xx response: {response.status_code}")
except Exception as e:
event.retry_count += 1
if event.retry_count >= MAX_RETRIES:
event.status = 'dead_letter'
event.dead_letter_reason = f'max retries exceeded: {str(e)}'
else:
# Calculate next retry time with exponential backoff and jitter
base_delay = 2 ** (event.retry_count - 1) # for first retry (retry_count=1) -> 2^0 = 1 second? But we might want longer.
# We can set a base delay in seconds and then multiply.
# Example: base = 60, then: 60, 120, 240, ... up to max.
delay = min(BASE_DELAY * (2 ** (event.retry_count - 1)), MAX_DELAY)
jitter = random.uniform(0, delay * 0.1) # 10% jitter
event.next_retry_at = now + timedelta(seconds=delay + jitter)
event.last_error = str(e)
event.last_attempt_at = now
db.save(event)
But note: we are using the same payload string for retries, so the signature will be the same.
However, what if the payload is huge and we don't want to store the raw string? We can compute the signature at creation time and store it, then on retry we use the stored signature? But then we must store the exact payload string to send? Or we can store the payload as a JSON object and then re-serialize with the same formatting? That's tricky.
So we store the raw payload string.
Now, for key rotation:
We have a cron job that runs periodically (daily) to rotate keys for subscribers? Or we rotate on demand?
Let's assume we have a list of subscribers that we want to rotate. We can rotate one by one.
Steps for rotating a subscriber's key:
1. Start a transaction.
2. Fetch the subscriber and current key.
3. Create a new key (generate a random secret, store it hashed? But we need the plain secret to sign. So we store it encrypted? Or we store it in plaintext? We must protect it. We'll assume we have a way to store secrets securely (like using a vault or at least encrypted in the database).
4. Update the subscriber's current_key_id to the new key.
5. Mark the old key as inactive (set is_active=false, rotated_at=now).
6. Commit.
Then, we must wait until all events that were signed with the old key are either delivered or dead-lettered. We can monitor:
- Count of events with key_id = old_key_id and status in ['pending', 'failed'].
We can have a background job that checks for keys that are inactive and have no pending events, and then deletes them (or archives them) after 30 days.
But note: we might have a lot of keys and events, so we need an index on events.key_id and events.status.
Indexes:
- events: index on (status, next_retry_at) for the delivery worker.
- events: index on (key_id, status) for key cleanup.
Now, dead-letter storage:
We already have the event in the database with status='dead_letter'. We might want to move it to a separate table for archiving? Or keep it in the same table.
We can have a separate table for dead-letter events that are older than, say, 90 days? But we can also just keep them in the Events table and have a status.
We'll keep it in the Events table.
However, if we have a huge volume, we might partition the Events table by time and move old dead-letter events to a cheaper storage? That's an optimization.
For now, we keep in the same table.
Monitoring:
- We should have alerts when the dead-letter queue grows beyond a threshold.
- We should monitor the delivery success rate.
This is a basic design. We can extend with:
- Batching: we might want to batch multiple events in one webhook? That's a different design.
- Rate limiting: we might want to limit the number of requests per subscriber per minute.
- Priority: some events might be high priority.
But for the requirements, we focus on reliability: signature rotation, exponential backoff, dead-letter.
Let's summarize the design:
Components:
- Event Store (database with Events, Subscribers, Keys tables)
- Delivery Worker(s)
- Key Rotation Service (cron job or on-demand)
- Key Cleanup Job (to delete old keys)
Workflow:
1. Event occurs -> create event record with status='pending', key_id = subscriber.current_key_id, and payload (raw string).
2.Delivery worker picks up the event, signs with the key (using the key's secret), sends, and on failure schedules a retry with exponential backoff.
3. After max retries, mark as dead_letter.
4. Key rotation: create new key, set as current, deactivate old. Old key remains until no pending events and 30 days passed.
This design should provide reliability and security through key rotation.
Note: We must handle the case where the subscriber's URL is no longer valid? We'll get a network error or a 4xx/5xx and retry. After max retries, dead-letter.
Also, we must handle timezones and clock skew? We use UTC timestamps.
We'll assume we have a way to store keys securely (encrypted at rest). The key secret must be accessible by the delivery worker to sign.
For asymmetric, we would store the private key and use it to sign. The receiver has the public key. But then we need to distribute the public key to the receiver. That's out of scope.
This is a high-level design. Implementation details will depend on the programming language and framework.
Let me know if you have any questions or need more details on a specific part.
I'll design a comprehensive webhooks reliability framework with signature rotation, exponential backoff, and dead-letter storage. This is a production-ready architecture that addresses common webhook delivery challenges.
Webhook Reliability Framework Architecture
1. Core Components
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Event Source │───▶│ Webhook Sender │───▶│ Target System │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│
▼
┌──────────────┐
│ Delivery │
│ Workers │
└──────────────┘
│
┌────────────┼────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌────────────┐
│ Success │ │ Retry │ │ Dead-Letter│
│ Store │ │ Queue │ │ Queue │
└──────────┘ └──────────┘ └────────────┘
2. Database Schema
-- Subscribers (target endpoints)
CREATE TABLE subscribers (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
url TEXT NOT NULL,
name VARCHAR(255),
active BOOLEAN DEFAULT true,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
-- Key Management (for signature rotation)
CREATE TABLE signing_keys (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
subscriber_id UUID REFERENCES subscribers(id) ON DELETE CASCADE,
key_id VARCHAR(100) UNIQUE NOT NULL, -- e.g., "whsk_2024_01"
secret_hash TEXT NOT NULL, -- store hash, not plaintext
is_active BOOLEAN DEFAULT false,
valid_from TIMESTAMP DEFAULT NOW(),
valid_until TIMESTAMP, -- null = indefinitely
created_at TIMESTAMP DEFAULT NOW(),
rotated_at TIMESTAMP,
INDEX idx_subscriber_active (subscriber_id, is_active)
);
-- Webhook Events
CREATE TABLE webhook_events (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
subscriber_id UUID REFERENCES subscribers(id),
event_type VARCHAR(100) NOT NULL,
payload JSONB NOT NULL,
signature TEXT NOT NULL, -- HMAC signature
key_id VARCHAR(100) NOT NULL, -- which key was used
-- Delivery tracking
status VARCHAR(50) DEFAULT 'pending', -- pending, delivered, failed, dead_lettered
attempts INT DEFAULT 0,
last_attempted_at TIMESTAMP,
next_retry_at TIMESTAMP,
last_error TEXT,
-- Metadata
delivery_response_code INT,
delivery_response_body TEXT,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
INDEX idx_status_retry (status, next_retry_at),
INDEX idx_subscriber_status (subscriber_id, status),
INDEX idx_created (created_at)
);
-- Dead Letter Queue (could be separate table or same with status)
CREATE TABLE dead_letters (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
webhook_event_id UUID REFERENCES webhook_events(id) ON DELETE SET NULL,
subscriber_id UUID REFERENCES subscribers(id),
failure_reason TEXT NOT NULL,
failure_count INT NOT NULL,
payload JSONB NOT NULL,
signature TEXT NOT NULL,
last_error TEXT,
occurred_at TIMESTAMP DEFAULT NOW(),
archived_at TIMESTAMP,
INDEX idx_subscriber (subscriber_id),
INDEX idx_occurred (occurred_at)
);
-- Retry Policy per subscriber
CREATE TABLE retry_policies (
subscriber_id UUID PRIMARY KEY REFERENCES subscribers(id) ON DELETE CASCADE,
max_attempts INT DEFAULT 5,
initial_delay_ms INT DEFAULT 1000, -- 1 second
max_delay_ms INT DEFAULT 3600000, -- 1 hour
multiplier DECIMAL(3,2) DEFAULT 2.0, -- exponential factor
jitter_factor DECIMAL(3,2) DEFAULT 0.2, -- 20% jitter
backoff_strategy VARCHAR(50) DEFAULT 'exponential' -- exponential, linear, fixed
);
3. Key Rotation Mechanism
class KeyRotationManager:
def __init__(self, db, key_vault):
self.db = db
self.key_vault = key_vault # HashiCorp Vault/AWS Secrets Manager
async def rotate_keys(self, subscriber_id: str):
"""Rotate signing keys for a subscriber"""
async with self.db.transaction():
# 1. Get current active key
old_key = await self.db.keys.find_one({
'subscriber_id': subscriber_id,
'is_active': True
})
# 2. Generate new key pair (symmetric for simplicity)
new_key_id = f"whsk_{datetime.utcnow().strftime('%Y%m')}"
new_secret = secrets.token_bytes(32)
# 3. Store new key (encrypted)
await self.db.keys.insert_one({
'subscriber_id': subscriber_id,
'key_id': new_key_id,
'secret_hash': self._hash_secret(new_secret),
'is_active': True,
'valid_from': datetime.utcnow()
})
# 4. Deactivate old key (but keep for verification)
if old_key:
await self.db.keys.update_one(
{'_id': old_key['_id']},
{'$set': {'is_active': False, 'rotated_at': datetime.utcnow()}}
)
# 5. Store secret in vault (for historical verification)
await self.key_vault.store_secret(
f"webhook/{subscriber_id}/{new_key_id}",
new_secret
)
# 6. Notify subscriber of new key (out-of-band)
await self._notify_subscriber_of_key_rotation(
subscriber_id,
old_key['key_id'] if old_key else None,
new_key_id
)
async def verify_signature(self, payload: bytes, signature: str, key_id: str) -> bool:
"""Verify webhook signature using appropriate key"""
# Get secret from vault (or decode from JWT if using asymmetric)
secret = await self.key_vault.get_secret(f"webhook/{key_id}")
if not secret:
return False
expected = hmac.new(
secret,
payload,
hashlib.sha256
).hexdigest()
return hmac.compare_digest(expected, signature)
4. Exponential Backoff with Jitter
class RetryScheduler:
def __init__(self, policy: RetryPolicy):
self.policy = policy
def calculate_next_retry(self, attempt: int) -> datetime:
"""Calculate next retry time with exponential backoff and jitter"""
if attempt >= self.policy.max_attempts:
return None
# Exponential backoff: delay = initial * (multiplier ^ (attempt - 1))
delay_ms = self.policy.initial_delay_ms * (
self.policy.multiplier ** (attempt - 1)
)
# Cap at max delay
delay_ms = min(delay_ms, self.policy.max_delay_ms)
# Add jitter (±20% random variation)
jitter = delay_ms * self.policy.jitter_factor
delay_ms += random.uniform(-jitter, jitter)
return datetime.utcnow() + timedelta(milliseconds=delay_ms)
def should_retry(self, status_code: int, attempt: int) -> bool:
"""Determine if we should retry based on HTTP status"""
if attempt >= self.policy.max_attempts:
return False
# Retry on server errors (5xx) and specific client errors
retryable_codes = {
408, # Request Timeout
409, # Conflict
429, # Too Many Requests
500, # Internal Server Error
502, # Bad Gateway
503, # Service Unavailable
504, # Gateway Timeout
}
return status_code in retryable_codes
5. Delivery Worker Implementation
class WebhookDeliveryWorker:
def __init__(self, db, queue, key_manager):
self.db = db
self.queue = queue # Redis/RabbitMQ/Kafka
self.key_manager = key_manager
self.http_client = httpx.AsyncClient(timeout=30.0)
async def process_event(self, event_id: str):
"""Process a single webhook delivery attempt"""
async with self.db.transaction():
event = await self.db.webhook_events.find_one({'_id': event_id})
if not event:
return
subscriber = await self.db.subscribers.find_one({'_id': event['subscriber_id']})
if not subscriber or not subscriber['active']:
await self._mark_failed(event, 'Subscriber inactive')
return
try:
# Verify signature matches payload (defensive check)
payload_bytes = json.dumps(event['payload']).encode('utf-8')
if not await self.key_manager.verify_signature(
payload_bytes,
event['signature'],
event['key_id']
):
await self._mark_failed(event, 'Signature verification failed')
return
# Send webhook
response = await self.http_client.post(
subscriber['url'],
content=payload_bytes,
headers={
'Content-Type': 'application/json',
'X-Webhook-Signature': event['signature'],
'X-Webhook-Key-Id': event['key_id'],
'User-Agent': 'WebhookReliability/1.0'
}
)
# Check response
if 200 <= response.status_code < 300:
await self._mark_delivered(event, response)
else:
# Determine if we should retry
policy = await self._get_retry_policy(subscriber['_id'])
if policy.should_retry(response.status_code, event['attempts']):
await self._schedule_retry(event, policy)
else:
await self._mark_dead_letter(event, f'HTTP {response.status_code}')
except (httpx.RequestError, asyncio.TimeoutError) as e:
# Network errors always retry
await self._schedule_retry(event, await self._get_retry_policy(subscriber['_id']))
except Exception as e:
await self._mark_failed(event, f'Unexpected error: {str(e)}')
async def _schedule_retry(self, event: dict, policy: RetryPolicy):
"""Schedule next retry attempt"""
next_retry = policy.calculate_next_retry(event['attempts'] + 1)
if next_retry:
await self.db.webhook_events.update_one(
{'_id': event['_id']},
{
'$set': {
'next_retry_at': next_retry,
'attempts': event['attempts'] + 1
},
'$push': {
'retry_history': {
'attempted_at': datetime.utcnow(),
'error': event.get('last_error')
}
}
}
)
# Re-queue for processing at next_retry time
await self.queue.schedule(
'webhook.delivery',
event['_id'],
execute_at=next_retry
)
else:
await self._mark_dead_letter(event, 'Max retries exceeded')
6. Dead Letter Queue Management
class DeadLetterManager:
def __init__(self, db, notification_service):
self.db = db
self.notification_service = notification_service
async def process_dead_letters(self):
"""Process dead-lettered events for analysis/replay"""
dead_letters = await self.db.dead_letters.find({
'archived_at': None,
'occurred_at': {'$gte': datetime.utcnow() - timedelta(days=7)}
}).to_list(100)
for dl in dead_letters:
# 1. Alert on critical failures
if self._is_critical_failure(dl):
await self.notification_service.alert(
f"Webhook DLQ: {dl['failure_reason']}",
f"Event {dl['webhook_event_id']} for subscriber {dl['subscriber_id']}"
)
# 2. Auto-replay logic (configurable)
if await self._should_auto_replay(dl):
await self._replay_event(dl['webhook_event_id'])
await self._archive_dead_letter(dl['_id'])
async def replay_event(self, event_id: str):
"""Manually replay a dead-lettered event"""
event = await self.db.webhook_events.find_one({'_id': event_id})
if event and event['status'] == 'dead_lettered':
# Reset status and clear retry history
await self.db.webhook_events.update_one(
{'_id': event_id},
{
'$set': {
'status': 'pending',
'attempts': 0,
'next_retry_at': datetime.utcnow(),
'last_error': None
},
'$unset': {'retry_history': 1}
}
)
# Re-queue for immediate processing
await self.queue.enqueue('webhook.delivery', event_id)
7. Monitoring & Alerting
# Prometheus Metrics Configuration
metrics:
webhook_delivery_total:
type: counter
labels: [subscriber_id, event_type, status]
webhook_delivery_duration_seconds:
type: histogram
buckets: [0.1, 0.5, 1, 2, 5, 10, 30]
labels: [subscriber_id, event_type]
webhook_retry_attempts:
type: histogram
buckets: [1, 2, 3, 5, 10]
dead_letter_queue_size:
type: gauge
labels: [subscriber_id]
signature_verification_failures:
type: counter
labels: [reason]
# Key Health Monitoring
key_monitoring:
- Alert: "WebhookKeyExpiringSoon"
Condition: key.valid_until < now() + 7d AND key.is_active == true
Severity: warning
- Alert: "InactiveKeyStillInUse"
Condition: EXISTS (
SELECT 1 FROM webhook_events
WHERE key_id = key.key_id
AND status IN ('pending', 'failed')
AND created_at > key.rotated_at
)
Severity: critical
8. API Endpoints
# Admin API for management
@app.route('/admin/webhooks/subscribers/<subscriber_id>/keys/rotate', methods=['POST'])
async def rotate_keys(subscriber_id):
"""Manually trigger key rotation"""
await key_manager.rotate_keys(subscriber_id)
return {'status': 'rotated', 'new_key_id': new_key_id}
@app.route('/admin/webhooks/dead-letters', methods=['GET'])
async def list_dead_letters(
subscriber_id: Optional[str] = None,
limit: int = 100,
offset: int = 0
):
"""List dead-lettered events"""
query = {'archived_at': None}
if subscriber_id:
query['subscriber_id'] = subscriber_id
dead_letters = await db.dead_letters.find(query)\
.sort('occurred_at', -1)\
.skip(offset)\
.limit(limit)\
.to_list(limit)
return {'dead_letters': dead_letters}
@app.route('/admin/webhooks/events/<event_id>/replay', methods=['POST'])
async def replay_event(event_id):
"""Manually replay a failed webhook"""
await dead_letter_manager.replay_event(event_id)
return {'status': 'replay_queued'}
9. Configuration Example
# config/webhook.yaml
webhook:
delivery:
worker_pool_size: 10
batch_size: 100
queue:
type: redis
url: ${REDIS_URL}
queue_name: webhook_delivery
retry:
default_max_attempts: 5
default_initial_delay_ms: 1000
default_max_delay_ms: 3600000
default_multiplier: 2.0
default_jitter_factor: 0.2
signature:
algorithm: hmac-sha256
key_rotation_days: 90 # Auto-rotate every 90 days
key_retention_days: 365 # Keep old keys for 1 year
dead_letter:
retention_days: 90
auto_replay_after_days: 1 # Auto-replay after 1 day if issue resolved
max_archive_size: 10000 # Archive when >10k DLQs
monitoring:
alert_webhook: ${ALERT_WEBHOOK_URL}
alert_channels:
- slack: ${SLACK_WEBHOOK}
- email: ops@example.com
10. Deployment Considerations
Infrastructure:
- Queue: Redis/RabbitMQ/Kafka for reliable message queuing
- Database: PostgreSQL with JSONB support, proper indexing
- Secret Management: HashiCorp Vault/AWS Secrets Manager for key storage
- Monitoring: Prometheus + Grafana dashboards
- Alerting: PagerDuty/Opsgenie integration
High Availability:
- Stateless delivery workers (can scale horizontally)
- Database connection pooling
- Queue consumers with consumer groups
- Dead-letter queue with multiple consumer groups for processing
Security:
- All secrets encrypted at rest
- Signature verification mandatory
- Rate limiting per subscriber
- IP whitelisting for delivery workers
- Audit logging for all key operations
Scalability:
- Shard events by subscriber_id for large scale
- Partition dead-letter queue by time/subscriber
- Use connection pooling for HTTP clients
- Implement circuit breakers for failing endpoints
11. Failure Scenario Handling
| Scenario | Handling |
|---|
| Network timeout | Immediate retry with backoff |
| 5xx error | Retry with exponential backoff |
| 4xx error (except 429) | Dead-letter (client error) |
| 429 Too Many Requests | Retry with backoff, respect Retry-After header |
| Signature mismatch | Immediate dead-letter (possible attack) |
| Subscriber deactivated | Immediate dead-letter |
| Key expired/removed | Dead-letter with "key not found" |
| Payload too large | Validate before enqueueing |
12. Key Rotation Best Practices
- Grace Period: Keep old keys active for verification for 30 days after rotation
- Notification: Inform subscribers of upcoming rotation via email/webhook
- Dual Signing: During transition, accept both old and new keys
- Monitoring: Track events using old keys to ensure no gaps
- Rollback Plan: Keep previous key available for rollback if needed
This framework provides:
- Reliability: Exponential backoff prevents overwhelming failing endpoints
- Security: Regular key rotation limits exposure if secrets compromised
- Observability: Complete audit trail and monitoring
- Recoverability: Dead-letter queue with replay capability
- Scalability: Horizontal scaling of delivery workers
- Fault Tolerance: Queue persistence ensures no event loss
Would you like me to elaborate on any specific component or provide implementation details for a particular tech stack?