We are going to design a system that implements the Outbox/Inbox pattern for durable messaging with a UI for replaying messages.
The Outbox/Inbox pattern is used to ensure reliable message delivery in distributed systems. The basic idea is:
When a service wants to send a message, it writes the message to an outbox table (or collection) in the same database transaction that updates the business data.
A separate process (the outbox poller) reads the outbox and sends the messages to the message broker (e.g., RabbitMQ, Kafka, etc.) and then marks them as sent (or deletes them).
The receiving service has an inbox (or a similar mechanism) to process incoming messages and ensures idempotency.
We are also going to have a UI that allows an operator to inspect the outbox and manually trigger resending of messages that might have failed.
We'll design the following:
Database tables for Outbox and Inbox.
A service that writes to the Outbox (as part of the business transaction).
An Outbox Poller service that sends messages from the Outbox to the message broker.
An Inbox service that receives messages and processes them (with idempotency).
A UI for viewing the Outbox and triggering resends.
We'll assume a relational database for simplicity.
Let's define the Outbox table:
id: primary key
aggregate_id: the ID of the aggregate (or business entity) that this message is about (for replay purposes)
event_type: the type of event (e.g., "OrderCreated")
payload: the event data (JSON)
status: enum ('pending', 'sent', 'failed')
created_at: timestamp
sent_at: timestamp (when it was successfully sent)
retry_count: number of attempts
last_error: error message from the last failure
We'll also have an Inbox table for the receiving side to track processed messages (to ensure idempotency):
id: primary key
message_id: a unique identifier for the message (could be the outbox id or a separately generated UUID)
event_type: the type of event
payload: the event data (JSON)
processed_at: timestamp
However, note that the Inbox pattern can be implemented in various ways. We'll assume that the receiving service uses the message's unique ID (which we can set as a property in the message) to check if it has already been processed.
Alternatively, we can have the sending service generate a unique message_id (UUID) and include it in the message. Then the receiving service stores that message_id in its inbox to avoid duplicate processing.
We'll adjust the Outbox table to include a message_id (UUID) that is generated by the sender.
So Outbox table:
id: primary key (for our table, but we don't expose this to the receiver)
message_id: UUID (this will be sent in the message and used by the receiver for idempotency)
aggregate_id: the aggregate ID (for replay by aggregate)
event_type: string
payload: JSON
status: string (pending, sent, failed)
created_at: timestamp
sent_at: timestamp
retry_count: integer
last_error: text
The Inbox table on the receiver:
id: primary key
message_id: UUID (unique, from the outbox)
event_type: string
payload: JSON
processed_at: timestamp
Now, let's design the components:
Sender Service:
When an event occurs (e.g., order created), it writes an outbox record in the same transaction that creates the order.
The outbox record has a generated message_id (UUID), the event type, the payload, and status 'pending'.
Outbox Poller:
Runs periodically (or uses a trigger-based mechanism) to fetch pending outbox records (status='pending').
For each record, it attempts to send the message to the message broker (with the message_id as a header or property).
If successful, it updates the outbox record to status='sent' and sets sent_at.
If failed, it increments retry_count, sets last_error, and if retry_count exceeds a threshold, it might set status to 'failed' (or keep as pending and retry later with backoff).
Receiver Service:
Consumes messages from the message broker.
For each message, it extracts the message_id and checks the inbox table for that message_id.
If found, it's a duplicate, so it acknowledges the message and does nothing.
If not found, it processes the event (business logic) and then inserts a record into the inbox table with the message_id and processed_at.
Then it acknowledges the message.
UI for Replay:
We need a UI that shows the outbox records, especially those that are in a failed state or that we want to replay for a given aggregate.
The UI should allow filtering by aggregate_id, status, event_type, etc.
For each record, we can have an action to resend (which would set the status back to 'pending' and reset retry_count? or just try to send again?).
Also, we might want to resend all pending messages for a given aggregate.
How to handle replay?
We have two scenarios:
Replay a single message: set its status to 'pending' (and maybe reset retry_count and last_error) so that the outbox poller will pick it up again.
Replay all messages for an aggregate: we can set all pending (or failed) messages for that aggregate to 'pending' (and reset retry_count) or we can create new outbox records?
But note: the original outbox records are already there. If we set status back to pending, the poller will try again. However, if the message was already sent (status='sent') and we want to replay it (for example, because the receiver didn't process it correctly and we fixed the receiver), then we might want to resend the same message again. But the receiver's inbox will have the message_id already, so it will be a duplicate. So we cannot resend the same message_id because the receiver will ignore it.
Therefore, for replaying a message that was already sent (and maybe the receiver failed to process it, but the message is in the receiver's inbox), we have two options:
Option 1: The receiver's inbox is per aggregate? But that would not be idempotent across different aggregates? Actually, the inbox is for the entire service. So if we want to replay a message that was already sent and the receiver has it in its inbox, we cannot use the same message_id because the receiver will think it's a duplicate.
So we need to generate a new message_id for the replayed message? But then the original aggregate event might have been already processed (and we are replaying because we suspect it wasn't). We have to be careful.
Alternatively, we can have the receiver's inbox be per aggregate? But that doesn't solve the problem because the same event for the same aggregate might be sent multiple times (for example, due to network issues) and we want to process it only once. So the message_id must be unique per event attempt.
Therefore, when we replay, we must generate a new message_id. But then the outbox will have a new record? Or we can update the existing outbox record with a new message_id? But then we lose the old message_id and the old record.
Better approach for replay:
For a given aggregate, we can have a way to re-emit the events that are stored in the event store (if we are using event sourcing) or we can have a way to re-create the outbox records for the events that we want to replay.
But in our current design, the outbox is write-once. We don't update the payload or message_id after creation. So if we want to replay, we should create new outbox records (with new message_id) for the same event data? But then we are duplicating events? And the receiver will process the same event again (with a new message_id) which might be acceptable if the event is idempotent? But the business event might not be idempotent (e.g., "charge credit card" should not be done twice).
So replay is dangerous and should be done with caution.
Given the complexity, let's assume:
The outbox is for communicating events that have already happened in the sender's database.
The receiver processes the event and marks it as processed by the message_id.
If the receiver fails to process (e.g., due to a bug) and we fix the bug, we might want to replay the event. But the event might have been already marked as processed (so the receiver won't process again). So we need a way to force the receiver to process again.
Thus, we might need a separate mechanism for replay that bypasses the inbox idempotency? Or we can have a concept of "replay" that deletes the inbox record for that message_id and then resends the same message (with the same message_id). But then we are deleting the inbox record, which might be acceptable if we are sure the event was not processed correctly.
Alternatively, we can have a flag in the inbox that says "processing_failed" and then have a way to retry from the inbox? That's a different pattern.
Given the requirement for a UI for replay, let's assume:
The outbox UI shows all outbox records (pending, sent, failed).
For a record that is in 'sent' status, we assume the receiver has processed it (because we don't know otherwise). But if we suspect the receiver didn't process it, we can force a resend by creating a new outbox record (with a new message_id) and then the receiver will process it as a new event? That would be a duplicate event.
So maybe we need to have the receiver's processing be idempotent by business key? Not by message_id? But then we lose the exactly-once guarantee.
This is a complex problem. Let's stick to the classic outbox/inbox pattern and for replay, we will only allow replaying messages that are in the outbox with status 'failed' (or maybe 'pending' that we want to retry). For messages that are already 'sent', we assume they are processed and we don't replay them. If we need to replay a 'sent' message, we have to do it at the business level (e.g., by issuing a compensating event or by manually correcting the state).
Alternatively, we can have a separate "replay" table that stores the events to be replayed, and then the outbox poller can also send from that table? But that complicates.
Given the time, let's design the UI for the outbox that allows:
Viewing outbox records (with filters)
For records that are in 'failed' status, we can set them back to 'pending' (and reset retry_count) so that the poller will try again.
For records that are in 'pending' status, we can also manually trigger an immediate send (by passing the record id to an endpoint that does the send and updates the record).
We won't handle replay of already sent messages in this design.
So the UI will have:
A list of outbox records with columns: message_id, aggregate_id, event_type, status, created_at, sent_at, retry_count, last_error.
Buttons or actions for each record:
If status is 'failed', a button to "Retry" which sets status to 'pending', resets retry_count and last_error.
If status is 'pending', a button to "Send Now" which will attempt to send that message immediately (by calling the same function the poller uses) and update the record accordingly.
Maybe a button to "View Details" to see the payload.
Additionally, we might want to retry all failed messages at once.
Now, let's design the API endpoints for the UI (assuming a web application):
GET /api/outbox?status=pending&aggregate_id=...&event_type=... -> list of outbox records (with pagination)
POST /api/outbox/{id}/retry -> set the record to pending (reset retry_count and last_error) so that the poller will pick it up again.
POST /api/outbox/{id}/send-now -> immediately try to send this message (and update the record accordingly). This endpoint would call the same send function that the poller uses.
We also need an endpoint to get the payload of a specific outbox record.
GET /api/outbox/{id}/payload -> returns the payload (maybe as JSON).
Now, let's write some code for the outbox poller and the sender.
We'll use a simple example with a message broker (like RabbitMQ) but abstract the sending.
We'll assume we have a function send_to_message_broker(message_id, event_type, payload) that sends the message and returns True if successful, False otherwise.
But note: the message must include the message_id so that the receiver can use it for idempotency.
So the outbox poller:
python
def process_outbox():
# Fetch a batch of pending outbox records (with a limit and maybe order by created_at)
pending_records = Outbox.objects.filter(status='pending').order_by('created_at')[:100]
for record in pending_records:
try:
success = send_to_message_broker(
message_id=record.message_id,
event_type=record.event_type,
payload=record.payload
)
if success:
record.status = 'sent'
record.sent_at = datetime.now()
record.save()
else:
record.retry_count += 1
record.last_error = "Send failed (temporary)"
if record.retry_count >= MAX_RETRIES:
record.status = 'failed'
record.save()
except Exception as e:
record.retry_count += 1
record.last_error = str(e)
if record.retry_count >= MAX_RETRIES:
record.status = 'failed'
record.save()
The send_to_message_broker function would be specific to the broker. For example, with RabbitMQ:
python
def send_to_message_broker(message_id, event_type, payload):
# Assume we have a channel
properties = pika.BasicProperties(
message_id=message_id,
type=event_type,
delivery_mode=2, # persistent
)
channel.basic_publish(
exchange='events',
routing_key=event_type,
body=json.dumps(payload),
properties=properties
)
return True
But we have to handle connection errors, etc.
Now, the receiver:
python
def on_message(channel, method, properties, body):
message_id = properties.message_id
event_type = properties.type
payload = json.loads(body)
# Check inbox
if Inbox.objects.filter(message_id=message_id).exists():
# Duplicate, acknowledge and return
channel.basic_ack(delivery_tag=method.delivery_tag)
return
try:
# Process the event (business logic)
process_event(event_type, payload)
# Record in inbox
Inbox.objects.create(
message_id=message_id,
event_type=event_type,
payload=payload
)
channel.basic_ack(delivery_tag=method.delivery_tag)
except Exception as e:
# Nack the message and don't requeue (or requeue based on error)
channel.basic_nack(delivery_tag=method.delivery_tag, requeue=False)
# Optionally, log the error and maybe send to a dead letter queue
Now, the sender service (business service) that writes to the outbox:
python
def create_order(order_data):
# Start a database transaction
with transaction.atomic():
order = Order.objects.create(**order_data)
# Generate a message_id
message_id = str(uuid.uuid4())
Outbox.objects.create(
message_id=message_id,
aggregate_id=order.id,
event_type='OrderCreated',
payload={'order_id': order.id, ...}
)
Now, for the UI, we need to build a simple web application that connects to the database and provides the endpoints.
We can use any framework (Django, Flask, etc.) but we'll keep it simple and just outline the endpoints.
We'll assume we have a Django-like ORM.
We also need to secure the UI so that only authorized operators can access.
Given the complexity, we'll just outline the code structure.
But note: the outbox table might grow large, so we need to consider archiving or deleting sent messages after some time. That's an operational concern.
Now, let's write the code for the outbox poller as a standalone script that runs periodically (e.g., every minute).
We'll also consider that the poller might run in multiple instances, so we need to avoid duplicate sending. We can use row-level locking (select for update) or use a status field and update it in a way that only one poller picks a record.
We can do:
python
Given the time, let's write a simplified version without the locking and reset, but note that it's not safe for multiple pollers.
We'll assume we run only one poller.
But for production, we need to handle multiple pollers. So we'll implement the conditional update.
We'll change the Outbox model to have a processing status? Actually, we have 'pending', 'sent', 'failed'. We can add 'processing' as a status.
So:
When we pick a pending record, we try to update it to 'processing' (only if it's still pending). If the update fails (0 rows updated), then another poller got it, so we skip.
Then we process and then update to 'sent' or 'failed' (or back to 'pending' if we want to retry immediately?).
But if we fail to send, we might want to set back to 'pending' for retry? But then we have to be careful because if we set back to 'pending', another poller might pick it immediately. We can set it to 'pending' and then the next run will pick it. But we might want to backoff.
We'll keep it simple: if send fails, we set status to 'failed' after max retries, otherwise we set back to 'pending'? But then we might get into a tight loop.
We'll do:
If send fails and retry_count < MAX_RETRIES, set status to 'pending' (and update retry_count and last_error). Then the next run will pick it again (but we don't control the timing).
Alternatively, we can set a next_retry_at timestamp and then only pick records that are pending and next_retry_at <= now. But that's more complex.
Given the time, we'll just set back to 'pending' and rely on the poller running periodically.
So the plan:
Poller fetches a batch of pending records (with a limit).
For each record, try to update to 'processing' (conditional). If fails, skip.
Then send the message.
If send succeeds, set status to 'sent', sent_at, and clear processing fields.
If send fails, increment retry_count, set last_error, and if retry_count >= MAX_RETRIES, set status to 'failed', else set status to 'pending' (so it can be retried in the next poll).
But note: when we set back to 'pending', we might want to set a delay? We'll ignore for now.
We also need to handle the case where the poller crashes after setting to 'processing' and before step 4. Then the record is stuck in 'processing'. So we need a way to reset 'processing' records that are too old.
We'll add a processing_started_at field. When we set to 'processing', we set processing_started_at to now. Then, when we start the poller, we first reset any 'processing' records that have processing_started_at older than, say, 10 minutes, to 'pending'.
Given the complexity and time, we'll implement a simpler version without the batch claiming and without the reset for stuck processing. We'll assume one poller and just update the record to 'processing' and then to 'sent' or 'failed' in the same transaction? But then if the send takes a long time, we hold the transaction.
Alternatively, we can do:
Start transaction.
Select a pending record with select_for_update (so we lock it).
Update to 'processing' and set processing_started_at.
Commit the transaction (release the lock).
Send the message.
Start a new transaction, update the record to 'sent' or 'failed'.
But if the process crashes after step 4 and before step 6, the record is stuck in 'processing'. So we need the reset.
Given the time, I think we have to choose one approach and code it.
Let's do:
One poller (so no concurrency issues) and no reset. We'll just update the record in the same transaction after sending? But if the send fails, we update the record to 'failed' (or 'pending') and commit. If the send succeeds, we update to 'sent' and commit.
But then if the send takes a long time, we are holding the transaction? Actually, we are not holding the transaction during the send because we commit after the send? We can do:
python
def process_outbox():
records = Outbox.objects.filter(status='pending').order_by('created_at')[:100]
for record in records:
try:
# We are going to send and then update in a transaction.
with transaction.atomic():
# But we want to make sure the record hasn't been updated by someone else? Since we assume one poller, it's okay.
# Refresh the record from the database to get the latest status? But we just fetched it.
success = send_to_message_broker(...)
if success:
record.status = 'sent'
record.sent_at = datetime.now()
else:
record.retry_count += 1
record.last_error = ...
if record.retry_count >= MAX_RETRIES:
record.status = 'failed'
# else, leave as pending? But we are in the same transaction and we are going to commit, so if we leave as pending, then in the next run we will pick it again.
record.save()
except Exception as e:
# Log and continue
pass
But this doesn't handle multiple pollers. And if the send fails and we set back to pending, we might get into a loop.
Given the time, we'll go with this simple version and note that for production we need to handle multiple pollers and stuck records.
Now, the UI part:
We'll create a Django app with two models: Outbox and Inbox (but the Inbox is on the receiver side, so the UI for the outbox is only on the sender side).
We'll create a Django app called 'outbox' with a model Outbox (as defined). Then we'll create a view to list the outbox records and a view to retry and send-now.
But note: the outbox poller is a separate process that runs periodically. The UI's "send-now" will call the same send function that the poller uses.
We'll create a service function for sending a single outbox record, and both the poller and the UI's send-now endpoint will use that.
def process_outbox():
records = Outbox.objects.filter(status='pending').order_by('created_at')[:100]
for record in records:
send_outbox_message(record)
But note: the retry endpoint doesn't actually send, it just resets so that the poller will send it again.
We also need to consider that the record might be in 'failed' status and we want to retry, so we set to 'pending'.
Now, the UI template: we can use a simple table with the records and buttons for each row.
We'll use Django templates.
But note: the outbox table might have many records, so we need pagination.
We'll use Django's pagination.
Given the complexity of the entire system, we'll just outline the code.
Now, the receiver side: we have an inbox table and a consumer that uses the inbox to avoid duplicates. We don't need a UI for the inbox? Maybe we do for debugging? But the requirement is for the outbox replay UI.
Now, the receiver side is separate and we don't need to include it in this UI.
This is a basic implementation. We have not handled:
Multiple pollers and concurrency.
Stuck processing records.
Archiving or deleting old records.
Security for the UI.
Error handling in the UI (the fetch calls might fail).
But it gives a starting point.
We also need to set up the message broker and the consumer on the receiver side, but that's out of scope for the UI.
So, in summary, we have:
Outbox model and Inbox model (on receiver).
Sender service that writes to Outbox.
Outbox poller that sends messages and updates Outbox.
Receiver service that consumes messages and uses Inbox for idempotency.
UI for viewing and manually triggering resends of Outbox records.
We have to run the poller periodically (e.g., with a cron job or a background worker).
This design is a simplified version of the Outbox pattern with a UI for replay.
I'll help you design a comprehensive Outbox/Inbox durable messaging pattern with replay capabilities and a management UI. This pattern ensures reliable message delivery in distributed systems.
CREATE TABLE outbox_messages (
id BIGSERIAL PRIMARY KEY,
message_id UUID NOT NULL DEFAULT gen_random_uuid(),
aggregate_type VARCHAR(100) NOT NULL, -- e.g., 'order', 'user'
aggregate_id VARCHAR(255) NOT NULL, -- Business entity ID
event_type VARCHAR(100) NOT NULL, -- e.g., 'order_created'
payload JSONB NOT NULL, -- Event data
metadata JSONB, -- Headers, correlation ID, etc.
-- Status tracking
status VARCHAR(20) NOT NULL DEFAULT 'pending',
retry_count INTEGER NOT NULL DEFAULT 0,
last_error TEXT,
-- Timing
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
processed_at TIMESTAMPTZ,
next_retry_at TIMESTAMPTZ, -- For exponential backoff
-- Constraints
UNIQUE(message_id),
INDEX idx_status_retry (status, next_retry_at),
INDEX idx_aggregate (aggregate_type, aggregate_id)
);
2. Inbox Table (Receiver Side)
sql
CREATE TABLE inbox_messages (
id BIGSERIAL PRIMARY KEY,
message_id UUID NOT NULL,
aggregate_type VARCHAR(100) NOT NULL,
aggregate_id VARCHAR(255) NOT NULL,
event_type VARCHAR(100) NOT NULL,
payload JSONB NOT NULL,
metadata JSONB,
-- Processing status
status VARCHAR(20) NOT NULL DEFAULT 'received',
processor_name VARCHAR(100), -- Which service processed it
processed_at TIMESTAMPTZ,
-- Error handling
error_count INTEGER NOT NULL DEFAULT 0,
last_error TEXT,
-- Timing
received_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-- Constraints
UNIQUE(message_id), -- Idempotency key
INDEX idx_status (status, received_at),
INDEX idx_aggregate (aggregate_type, aggregate_id)
);
Core Components
1. Outbox Producer Pattern
python
# transactionally write to outbox within business transaction
class OutboxProducer:
def __init__(self, db_session):
self.db_session = db_session
def emit_event(self, aggregate_type, aggregate_id, event_type, payload, metadata=None):
"""Emit event within same transaction as business operation"""
outbox = OutboxMessage(
aggregate_type=aggregate_type,
aggregate_id=str(aggregate_id),
event_type=event_type,
payload=payload,
metadata=metadata or {},
status='pending',
next_retry_at=datetime.utcnow()
)
self.db_session.add(outbox)
# Transaction commits with business operation
return outbox.message_id
2. Outbox Poller Worker
python
class OutboxPoller:
def __init__(self, broker_client, db_session, batch_size=100):
self.broker_client = broker_client
self.db_session = db_session
self.batch_size = batch_size
def poll_and_send(self):
"""Fetch pending messages and send to broker"""
now = datetime.utcnow()
# Get batch of messages ready for delivery
messages = self.db_session.query(OutboxMessage).filter(
OutboxMessage.status == 'pending',
OutboxMessage.next_retry_at <= now
).order_by(OutboxMessage.created_at).limit(self.batch_size).all()
for msg in messages:
try:
# Send to message broker with message_id as deduplication key
self.broker_client.publish(
topic=msg.event_type,
key=str(msg.aggregate_id),
value=msg.payload,
headers={
'message_id': str(msg.message_id),
'aggregate_type': msg.aggregate_type,
'aggregate_id': msg.aggregate_id,
'event_type': msg.event_type
}
)
# Mark as sent
msg.status = 'sent'
msg.processed_at = datetime.utcnow()
msg.retry_count = 0
except Exception as e:
self._handle_failure(msg, str(e))
self.db_session.commit()
def _handle_failure(self, msg, error):
"""Handle send failure with exponential backoff"""
msg.retry_count += 1
msg.last_error = error
if msg.retry_count >= 5: # Max retries
msg.status = 'failed'
else:
# Exponential backoff: 2^retry_count seconds (min 1, max 300)
delay = min(2 ** msg.retry_count, 300)
msg.next_retry_at = datetime.utcnow() + timedelta(seconds=delay)
3. Inbox Processor (Idempotent Consumer)
python
class InboxProcessor:
def __init__(self, broker_client, db_session):
self.broker_client = broker_client
self.db_session = db_session
def process_message(self, raw_message):
"""Process incoming message with idempotency"""
message_id = raw_message.headers.get('message_id')
# Check if already processed
existing = self.db_session.query(InboxMessage).filter(
InboxMessage.message_id == message_id
).first()
if existing:
if existing.status == 'processed':
return # Already processed, skip
# Could be 'received' but failed processing, retry
try:
# Begin transaction for idempotent processing
with self.db_session.begin():
# Create inbox record (idempotency check)
inbox = InboxMessage(
message_id=message_id,
aggregate_type=raw_message.headers['aggregate_type'],
aggregate_id=raw_message.headers['aggregate_id'],
event_type=raw_message.headers['event_type'],
payload=raw_message.value,
metadata=dict(raw_message.headers),
status='processing'
)
self.db_session.add(inbox)
# Process business event
self._handle_event(
raw_message.headers['aggregate_type'],
raw_message.headers['aggregate_id'],
raw_message.headers['event_type'],
raw_message.value
)
# Mark as processed
inbox.status = 'processed'
inbox.processed_at = datetime.utcnow()
inbox.processor_name = self.__class__.__name__
# Acknowledge message only after successful processing
raw_message.ack()
except Exception as e:
# Update inbox with error, don't ack
inbox.status = 'failed'
inbox.error_count += 1
inbox.last_error = str(e)
# Message will be retried by broker (requeue) or sent to DLQ
def _handle_event(self, aggregate_type, aggregate_id, event_type, payload):
"""Business logic handler - implement in subclass"""
raise NotImplementedError()
-- SQL for monitoring dashboard
SELECT
status,
COUNT(*) as count,
MAX(retry_count) as max_retries,
AVG(EXTRACT(EPOCH FROM (NOW() - created_at))) as avg_age_seconds
FROM outbox_messages
WHERE created_at > NOW() - INTERVAL '24 hours'
GROUP BY status;
-- Find stuck messages
SELECT COUNT(*) FROM outbox_messages
WHERE status = 'processing'
AND updated_at < NOW() - INTERVAL '1 hour';
4. Dead Letter Queue (DLQ) Handling
python
class DeadLetterQueue:
def __init__(self, db_session, dlq_topic):
self.db_session = db_session
self.dlq_topic = dlq_topic
def move_to_dlq(self, message, reason):
"""Move failed message to dead letter queue"""
dlq_record = DeadLetterMessage(
original_message_id=message.message_id,
aggregate_type=message.aggregate_type,
aggregate_id=message.aggregate_id,
event_type=message.event_type,
payload=message.payload,
failure_reason=reason,
failed_at=datetime.utcnow(),
retry_count=message.retry_count
)
self.db_session.add(dlq_record)
# Publish to DLQ topic for manual inspection
self.broker_client.publish(
topic=self.dlq_topic,
key=str(message.message_id),
value={
'original_message': message.payload,
'failure_reason': reason,
'retry_count': message.retry_count
}
)
Best Practices
Idempotency: Always use message_id as deduplication key
Transactionality: Write to outbox in same transaction as business operation
Backpressure: Implement rate limiting if producer is faster than consumer
Schema Evolution: Version your event payloads for backward compatibility
UI Features to Consider
Bulk Operations: Select multiple messages for replay
Filtering: By aggregate, event type, status, date range
Search: Full-text search in payloads (be cautious with PII)
Payload Viewer: Pretty-print JSON/XML payloads
Diff View: Compare original vs replayed payloads
Retry History: Show retry attempts and errors
Export: Export filtered messages to CSV/JSON
Dry Run: Preview which messages would be replayed
This pattern provides:
✅ Durable messaging: Messages survive crashes
✅ Exactly-once semantics: Through idempotent processing
✅ Replay capability: Fix processing errors
✅ Visibility: Full audit trail of all messages
✅ Operational control: Manual intervention when needed
The UI gives operators the ability to diagnose and fix messaging issues without touching the database directly.
def process_outbox():
# We'll use a transaction and select for update to lock the rows we are about to process.
with transaction.atomic():
# We select pending records and lock them (so that other pollers skip them)
pending_records = Outbox.objects.select_for_update(skip_locked=True).filter(status='pending').order_by('created_at')[:100]
for record in pending_records:
# ... same as above, but we are in a transaction so we can update the record and commit after each?
# But we don't want to hold the lock for too long. Alternatively, we can update the record to a 'processing' status and then commit, then process and then update again.
# Let's change the status to 'processing' when we pick it up, so that other pollers don't pick it.
record.status = 'processing'
record.save()
# Then commit the transaction to release the lock? But then we are not in the same transaction for the send and the final update.
# We can do:
# 1. Update to 'processing' and commit (so we release the lock and other pollers skip this record).
# 2. Then try to send.
# 3. Then update to 'sent' or 'failed' (or back to 'pending' if we want to retry immediately?).
# But if the process crashes after step 1 and before step 3, the record will be stuck in 'processing'. So we need a way to reset 'processing' records that are too old.
# Alternatively, we can keep the lock until we finish sending and then update. But that might hold the lock for a long time if the send is slow.
# We'll do:
# Step 1: In a transaction, set status to 'processing' and update a 'processing_started_at' timestamp. Then commit.
# Step 2: Send the message.
# Step 3: Update the record to 'sent' or 'failed' (and clear the 'processing_started_at').
# We'll adjust the Outbox model to have a `processing_started_at` field.
# But to keep it simple, we'll just use the status and rely on the fact that if we crash, we have a separate process to reset stuck records? Or we can have a timeout.
# Given the complexity, let's stick to the simple version without locking and use a queue (like a task queue) for sending? But then we are not using the outbox pattern.
# Since we are building a durable pattern, we want to avoid losing messages. So we'll do:
# In the poller, we'll use `select_for_update(skip_locked=True)` and then immediately update the record to 'processing' and save, then commit the transaction (so we release the lock). Then we process and then update again.
# But note: the `select_for_update` will lock the rows until the transaction is committed. So we do:
# transaction 1: select for update, update to 'processing', commit.
# Then we send.
# Then transaction 2: update to 'sent' or 'failed'.
# We'll do:
# with transaction.atomic():
# record = Outbox.objects.select_for_update().get(id=record.id)
# if record.status != 'pending':
# continue
# record.status = 'processing'
# record.save()
# Then outside the transaction, we send.
# But what if after we set to 'processing' and before we send, the process crashes? Then the record is stuck in 'processing'. We can have a cron job that resets 'processing' records that have been in that state for more than, say, 5 minutes, to 'pending'.
# We'll add a field `processing_started_at` and set it when we set to 'processing'. Then the reset job sets back to 'pending' if `processing_started_at` is older than 5 minutes.
# Given the time, we'll skip the locking and reset mechanism and assume we run only one poller. But that's not durable.
# Let's change the plan: we'll use a task queue (like Celery) to process the outbox. The poller just enqueues tasks for each pending record? But then we are back to the same problem: how to ensure exactly-once sending?
# Alternatively, we can have the poller run in a single instance and use database locks to avoid multiple pollers. We'll do:
# In the poller:
# with transaction.atomic():
# records = Outbox.objects.filter(status='pending').order_by('created_at')[:100]
# for record in records:
# # We try to update the record to 'processing' and check that it was 'pending' (using a conditional update)
# updated = Outbox.objects.filter(id=record.id, status='pending').update(status='processing')
# if updated == 0:
# # Someone else updated it, skip
# continue
# # Now we have the record in processing, we can process it outside the transaction.
# Then we send and then update the record to 'sent' or 'failed'.
# We'll do that.
pass # We'll implement below.
def process_outbox():
reset_stuck_processing()
with transaction.atomic():
# We are going to select pending records and try to claim them by setting to processing.
# We'll use a loop to claim one by one? Or we can do a bulk update with a condition?
# We can do:
# records = Outbox.objects.filter(status='pending').order_by('created_at')[:100]
# for record in records:
# updated = Outbox.objects.filter(id=record.id, status='pending').update(status='processing', processing_started_at=datetime.now())
# if updated == 0:
# continue
# # Now we have claimed this record, but we are still in the transaction? Actually, the update is done in a separate query and we are in the same transaction?
# # We are in the outer transaction, so the update is part of the transaction. But we want to commit the update immediately so that other pollers see the change?
# # We are in a transaction, so the update is not visible until we commit. But we are going to commit at the end of the `with` block?
# # We want to release the lock on the row? Actually, we are not using `select_for_update` so we are not locking. We are just doing an update with a condition.
# # The condition ensures that only one poller can update a given row from 'pending' to 'processing' at a time. But if two pollers try to update the same row at the same time, one will succeed (0 rows updated for the other).
# # But we are in a transaction and we haven't committed, so the other transaction won't see our update until we commit. So we need to commit after each update? That would be too many commits.
#
# Alternatively, we can do:
# with transaction.atomic():
# # We are going to select the records and then update them in a bulk update? But we want to update only those that are still pending.
# # We can do:
# ids = list(records.values_list('id', flat=True))
# # Now try to update all of them in one query:
# updated_count = Outbox.objects.filter(id__in=ids, status='pending').update(status='processing', processing_started_at=datetime.now())
# # But then we don't know which ones were updated? We can get the list of ids that were updated by doing:
# # Actually, the update will only update the rows that are still pending. So we can then fetch the records that are now in 'processing' and have id in ids.
# claimed_records = Outbox.objects.filter(id__in=ids, status='processing')
# # Then we process these records.
#
# But note: we are in a transaction, so the update is not visible to other transactions until we commit. But we are going to commit at the end of the `with` block. That means while we are processing the claimed records, other pollers might also try to claim the same records? But they will fail because the condition (status='pending') will not be true (because we haven't committed the update to 'processing' yet). So they will skip.
#
# However, if we have two pollers running at the same time, they both might select the same set of pending records (because they both see the same state) and then both try to update. But the update with condition will only update the rows that are still pending. So if poller A updates row 1 to processing, then when poller B tries to update row 1, it will fail (because row 1 is no longer pending) and so it will skip. But then poller B might have selected row 1 in its initial select, but then the update fails and it doesn't process it. That's okay.
#
# But note: the initial select (without lock) might return the same rows for both pollers, but then the update condition ensures only one claims each row.
#
# However, the problem is that we are updating the rows in a bulk update and then we are going to process them. But what if the bulk update updates 10 rows, and then while we are processing, one of the rows becomes a problem? We are processing outside the transaction? We are going to commit the transaction (which includes the update to 'processing') and then process each message? But if we commit, then the change is visible and other pollers will skip these rows. But if we crash after committing the update to 'processing' and before sending, then the record is stuck in 'processing' until the reset.
#
# So we need to commit the update to 'processing' before we send? But then we are in a transaction and we want to hold the lock? Actually, we are not using row locks, so we don't need to hold the transaction. We can commit after the bulk update and then process each record in a separate transaction? But then we have to update each record again (to 'sent' or 'failed') in a separate transaction.
#
# Let's break it down:
# Step 1: Claim a batch of pending records by updating them to 'processing' in one transaction and commit.
# Step 2: For each claimed record, send the message and then update the record to 'sent' or 'failed' (in a separate transaction for each? or in a batch?).
#
# But if we update each record in a separate transaction, we might have a problem if we crash in the middle: some records are sent and updated, some are not. But that's okay because the ones that are not updated will remain in 'processing' and then be reset.
#
# So:
# with transaction.atomic():
# # Claim a batch
# records = Outbox.objects.filter(status='pending').order_by('created_at')[:100]
# ids = [r.id for r in records]
# updated_count = Outbox.objects.filter(id__in=ids, status='pending').update(status='processing', processing_started_at=datetime.now())
# # Now commit the transaction (the `with` block will commit if no exception). So after the `with` block, the updates are committed.
#
# Then we get the claimed records (the ones that were updated to processing) and process them.
#
# But note: the update might have updated fewer records than we selected because some might have been updated by another poller in the meantime. So we need to fetch the records that are now in 'processing' and have id in ids.
#
# claimed_records = Outbox.objects.filter(id__in=ids, status='processing')
#
# Then for each record in claimed_records:
# try:
# send message
# record.status = 'sent'
# record.sent_at = datetime.now()
# record.save()
# except:
# record.retry_count += 1
# record.last_error = ...
# if record.retry_count >= MAX_RETRIES:
# record.status = 'failed'
# else:
# record.status = 'pending'
# record.save()
#
# But note: if we set back to 'pending', then another poller might pick it up immediately. We might want to set a delay? We can set `processing_started_at` to None and maybe set a `next_retry_at`? We'll skip for now.
#
# Also, we need to reset the `processing_started_at` when we set to 'sent' or 'failed' or back to 'pending'? We can set it to None.
pass # We'll implement below.
# FastAPI/Flask/Django example
from fastapi import FastAPI, HTTPException, BackgroundTasks
from pydantic import BaseModel
from typing import List, Optional
app = FastAPI()
class ReplayRequest(BaseModel):
message_ids: Optional[List[str]] = None
aggregate_id: Optional[str] = None
aggregate_type: Optional[str] = None
event_type: Optional[str] = None
status: Optional[str] = None
days_back: Optional[int] = 7
@app.get("/api/outbox/messages")
async def list_outbox_messages(
status: Optional[str] = None,
aggregate_type: Optional[str] = None,
aggregate_id: Optional[str] = None,
event_type: Optional[str] = None,
page: int = 1,
limit: int = 50
):
"""List outbox messages with filters"""
query = db.query(OutboxMessage)
if status:
query = query.filter(OutboxMessage.status == status)
if aggregate_type:
query = query.filter(OutboxMessage.aggregate_type == aggregate_type)
if aggregate_id:
query = query.filter(OutboxMessage.aggregate_id == aggregate_id)
if event_type:
query = query.filter(OutboxMessage.event_type == event_type)
total = query.count()
messages = query.order_by(
OutboxMessage.created_at.desc()
).offset((page-1)*limit).limit(limit).all()
return {
"total": total,
"page": page,
"limit": limit,
"messages": [m.to_dict() for m in messages]
}
@app.post("/api/outbox/replay")
async def replay_messages(request: ReplayRequest, background_tasks: BackgroundTasks):
"""Replay messages matching criteria"""
query = db.query(OutboxMessage)
# Build query based on filters
if request.message_ids:
query = query.filter(OutboxMessage.message_id.in_(request.message_ids))
if request.aggregate_id:
query = query.filter(OutboxMessage.aggregate_id == request.aggregate_id)
if request.aggregate_type:
query = query.filter(OutboxMessage.aggregate_type == request.aggregate_type)
if request.event_type:
query = query.filter(OutboxMessage.event_type == request.event_type)
if request.status:
query = query.filter(OutboxMessage.status == request.status)
if request.days_back:
cutoff = datetime.utcnow() - timedelta(days=request.days_back)
query = query.filter(OutboxMessage.created_at >= cutoff)
messages = query.all()
if not messages:
raise HTTPException(status_code=404, detail="No messages found matching criteria")
# Queue replay task
background_tasks.add_task(replay_messages_task, [m.message_id for m in messages])
return {
"message": f"Replaying {len(messages)} messages",
"message_ids": [str(m.message_id) for m in messages]
}
@app.post("/api/outbox/{message_id}/replay")
async def replay_single_message(message_id: str):
"""Replay a specific message"""
message = db.query(OutboxMessage).filter(
OutboxMessage.message_id == message_id
).first()
if not message:
raise HTTPException(status_code=404, detail="Message not found")
# Reset message for replay
message.status = 'pending'
message.retry_count = 0
message.last_error = None
message.next_retry_at = datetime.utcnow()
message.processed_at = None
db.commit()
return {"message": "Message queued for replay", "message_id": message_id}
@app.get("/api/outbox/stats")
async def get_outbox_stats():
"""Get outbox statistics for dashboard"""
stats = db.query(
OutboxMessage.status,
OutboxMessage.aggregate_type,
func.count(OutboxMessage.id)
).group_by(
OutboxMessage.status,
OutboxMessage.aggregate_type
).all()
return {
"by_status": {s: c for s, _, c in stats if _ is None},
"by_aggregate_type": {at: c for _, at, c in stats if s is None}
}