We are going to design a resilient eventing platform that includes:
- Outbox pattern: to ensure that events are published even if the service fails after committing to the database.
- Inbox pattern: to handle idempotent consumption of events (deduplication).
- Replay UI: a user interface to trigger replay of events for a given aggregate or time range.
We'll break down the components:
A. Outbox Pattern:
- We have an application that produces events. Instead of publishing events directly to a message broker, we write them to an outbox table in the same database transaction that updates the business data.
- A separate process (or the same service with a background thread) reads the outbox table and publishes the events to the message broker, then marks them as published (or deletes them).
B. Inbox Pattern:
- When consuming events, we need to handle duplicates (at-least-once delivery). We use an inbox table to track processed events.
- The consumer first checks the inbox table for the event ID. If it's already processed, skip. Otherwise, process and mark as processed.
C. Replay UI:
- A UI that allows an operator to select an aggregate (by ID) or a time range and trigger a replay of events for that aggregate.
- The replay would involve reading the outbox events (or the event store) and republishing them, but note: we must avoid re-processing already processed events (so we might need to reset the inbox for those events?).
- Alternatively, we might have a separate store for events (event sourcing) and then we can replay by reading from that store and publishing again.
However, note that the outbox pattern is typically for transactional consistency between the database and the message broker. For replay, we might want to have an event store (like a log) that keeps all events. The outbox table might be transient (deleted after publishing). So we need to think about how to store events for replay.
Let's consider two approaches:
-
Event Sourcing: The state changes are stored as a sequence of events. Then we can reconstruct state by replaying. This is a separate pattern and might be too heavy if not required.
-
We can have a permanent event store that is append-only and used for replay. The outbox pattern can be implemented by writing to both the business tables and the event store (in the same transaction). Then, the outbox process reads from the event store (or a separate outbox table that is actually a projection of the event store) and publishes.
But note: the outbox pattern as described by Chris Richardson uses a separate outbox table. We can combine:
- Write the event to an event store (or an outbox table that is not deleted immediately) and then have a publisher that reads from there.
Alternatively, we can have:
- An
events table that is the source of truth for events (with columns: id, aggregate_id, type, payload, version, etc.). This table is written in the same transaction as the business data (if we are using domain events). Then we have an outbox table that is a projection of the events table (or we publish directly from the events table?).
However, the outbox pattern typically uses a separate table to avoid locking issues with the event store. But we can also use the same table and then have a separate process that reads and marks as published.
Let's design:
events table:
id (primary key, event id)
aggregate_id (the id of the aggregate that produced the event)
type (event type)
payload (json)
version (for the aggregate, to ensure ordering)
created_at
published (boolean, default false) -- this is for outbox
Then the publisher reads events where published = false, publishes them, and sets published = true.
But note: we might have multiple publishers? We need to handle concurrent publishing. We can use a "claim" mechanism (like setting a processing flag with a timestamp and then only process events with processing flag expired). Alternatively, we can use a queue.
However, the problem with the above is that if we have a high volume, we might be updating the same table frequently. Also, if we want to replay, we need to reset the published flag? That might be dangerous because then we would re-publish events that might have already been processed by consumers.
So for replay, we might want to have a separate mechanism: maybe we have a separate table for the outbox (which is a copy of the events that need to be published) and then we can clear that table and repopulate for replay? Or we have a separate "replay" table?
Alternatively, we can have:
outbox table:
id, aggregate_id, type, payload, version, created_at, status (pending, published, processing), published_at, processing_at, etc.
Then the publisher updates the status. For replay, we can reset the status of events for a given aggregate (or time range) to pending.
But note: the outbox pattern is for ensuring that events are published. The same event might be published multiple times (if the publisher fails after publishing but before updating the status) but consumers must be idempotent. So resetting the status for replay is safe because the consumers will ignore duplicates.
However, if we reset the status for events that were already published and then published again, we must ensure that the consumers are idempotent. That is already the case because of the inbox pattern.
So let's design:
Tables:
outbox:
id: UUID (event id, same as the event id? or separate?)
aggregate_id: string
type: string
payload: json
version: integer (for the aggregate, to ensure ordering per aggregate)
created_at: timestamp
status: enum('pending', 'processing', 'published')
processing_at: timestamp (nullable, set when we start processing)
published_at: timestamp (nullable, set when published)
attempts: integer (default 0)
We can also have an index on (status, created_at) for the publisher to query.
Publisher process:
1. Find a batch of pending events (with status = 'pending') ordered by created_at, and try to claim them by setting status = 'processing' and processing_at = now() (and increment attempts?).
2. Then publish each event.
3. If successful, set status = 'published' and published_at = now().
4. If fails, set status back to 'pending' (or leave as processing and let a later process reset if processing_at is too old).
But note: we might have multiple publisher instances. We need to avoid two publishers processing the same event. So the claim step must be atomic. We can do:
UPDATE outbox
SET status = 'processing', processing_at = NOW(), attempts = attempts + 1
WHERE id IN (SELECT id FROM outbox WHERE status = 'pending' ORDER BY created_at LIMIT 100 FOR UPDATE SKIP LOCKED)
But note: FOR UPDATE SKIP LOCKED is available in PostgreSQL, but not in all databases. We can also use a compare-and-set with a version? Alternatively, we can use a separate "lock" table or a distributed lock.
Alternatively, we can have a single publisher (or leader election) to avoid concurrency. But that might not be resilient.
Let's assume we are using PostgreSQL and we can use FOR UPDATE SKIP LOCKED.
Steps:
BEGIN;
SELECT id FROM outbox WHERE status = 'pending' ORDER BY created_at LIMIT 100 FOR UPDATE SKIP LOCKED;
Then update those ids to 'processing'.
COMMIT;
Then we publish and update again.
But what if the publisher crashes after setting to processing? Then we have a processing event that is stuck. We can have a background job that resets events that have been in processing for more than, say, 5 minutes.
Inbox pattern:
inbox table:
event_id (UUID, unique) -- the id from the outbox (or the event id)
aggregate_id (string, might be useful for queries)
type (string)
payload (json, maybe not necessary if we don't need to reprocess? but for audit we might store)
processed_at (timestamp, nullable)
processed_by (string, the consumer name, if we have multiple consumers for the same event type)
status: enum('pending', 'processed', 'failed')? but we might not need status if we just have processed_at.
But note: we might have different consumers for the same event? Then we need to track per consumer. Alternatively, we can have:
consumer_name (string) and event_id as composite primary key.
But then if we have many consumers, the table might be large. Alternatively, we can have:
event_id (UUID, foreign key to outbox? but we might not want to keep the outbox forever) and then a list of consumers that have processed it? That would be a separate table.
Let's keep it simple: we assume one consumer per event type. Then we can have:
event_id (UUID, primary key) and processed_at.
But if we have multiple consumers for the same event, then we need to track each one. So:
event_id, consumer_name -> primary key.
Then when a consumer receives an event, it checks if (event_id, consumer_name) exists in inbox. If not, it processes and inserts a row.
Replay:
We want to replay events for a given aggregate (or time range). We need to:
1. Find all events from the outbox (or event store) for that aggregate (or time range) that are in a state that we want to replay (maybe only published? or all?).
2. Reset their status in the outbox? But note: if we reset the outbox status, then the publisher will republish them. But what if the events were already processed by consumers? They will ignore because of the inbox.
3. So we can reset the outbox events for that aggregate to 'pending' (or we can create new outbox events?).
But note: the outbox events are the source of truth for what needs to be published. So if we reset, we are saying these events need to be published again.
However, if the events were already published and we reset, then the publisher will publish again. The consumers will ignore because they have already processed (if we are using the inbox pattern with the same consumer name). But what if we want to replay to a different consumer? Then we might need to reset the inbox for that consumer? Or we might have a different consumer name for replay?
Alternatively, we can have a separate process for replay that reads events from the event store (or outbox) and then sends them directly to a different topic? But then we break the pattern.
Let's assume we are using the same topic and the same consumer group (so same consumer name). Then resetting the outbox is safe.
Steps for replay:
- Select events from outbox where aggregate_id = ? (and maybe created_at between ? and ?) and set status = 'pending' (and reset processing_at, attempts?).
- Then the publisher will pick them up and publish again.
But note: if the events were already published and we reset, then we are going to publish duplicates. That's okay because the consumer will deduplicate.
However, what if the events were never published because of a failure? Then we are just retrying.
So the replay UI would:
1. Allow the user to input an aggregate ID or a time range.
2. When the user clicks replay, we update the outbox events for that aggregate (or time range) to status = 'pending' (and maybe reset processing_at and attempts?).
3. Then the publisher will republish them.
But we must be cautious: we don't want to reset events that are already being processed? We can reset only the ones that are published or failed?
Alternatively, we can have a separate "replay" flag in the outbox? Or we can have a separate table for replay requests?
Another idea: we don't reset the outbox. Instead, we have a separate "replay" service that reads from the event store (or outbox) and then publishes again, but with a different event id? That would break idempotency.
So resetting the outbox might be the simplest.
However, if we reset the outbox, then the publisher might pick up the same event again while it's already being processed by a consumer? But the consumer will deduplicate.
So let's go with resetting the outbox.
But note: what if the event was never in the outbox? Then we cannot replay. So we must have all events in the outbox? That means we don't delete from the outbox? Then the outbox table grows indefinitely.
Alternatively, we can have:
- We keep the outbox for a certain period (say 30 days) and then archive? Or we have a separate event store that is append-only and we use that for replay.
Let's change the design:
We have an events table that is the event store (append-only). Then we have an outbox table that is a projection of the events table for events that need to be published. The outbox table can be truncated after successful publishing? But then we lose the ability to replay.
So we can:
- Keep the `events` table forever (or for a long time) and then for replay, we read from `events` and then insert into `outbox`? But then we are duplicating events.
Alternatively, we can have:
- The `outbox` table is the event store? But then we are updating the same table for publishing status, which might cause contention.
Let's split:
- `events` table:
id (UUID, primary key)
aggregate_id
type
payload
version
created_at
- `outbox` table:
event_id (UUID, foreign key to events.id)
status (pending, processing, published)
processing_at
published_at
attempts
Then the publisher reads from `outbox` and publishes. When we want to replay, we can insert into `outbox` for events that are not already in outbox? Or we can reset the status of existing outbox rows for the given aggregate.
But note: if we delete from outbox after publishing, then we lose the ability to replay. So we must keep the outbox rows? Then we can reset the status of outbox rows for that aggregate.
However, what if we have a new event that was not in the outbox? Then we need to insert it. But if we keep the outbox as a projection, then we need to insert into outbox when we insert into events? That is the outbox pattern: we write to both in the same transaction.
So:
When an application produces an event:
BEGIN;
INSERT INTO events ...;
INSERT INTO outbox (event_id, status) VALUES (..., 'pending');
COMMIT;
Then the publisher picks up from outbox and publishes, then updates outbox status to 'published'.
For replay:
We want to replay events for an aggregate. We look at the events table for that aggregate, and for each event that is not in the outbox (or has status != 'published')? But note: if the event was already published and we want to replay, we need to reset the outbox status.
So:
UPDATE outbox
SET status = 'pending', processing_at = NULL, published_at = NULL, attempts = 0
WHERE event_id IN (SELECT id FROM events WHERE aggregate_id = ? AND created_at BETWEEN ? AND ?);
But note: what if the event is not in the outbox? Then we need to insert it? But if we are using the outbox pattern, every event should be in the outbox. So we can assume that every event in `events` has a corresponding row in `outbox`.
Then we just reset the status.
However, what about events that were never published because the application failed after writing to events but before writing to outbox? That cannot happen because we write in the same transaction. So every event in events must have an outbox row.
So the replay UI would:
Step 1: Query the events table for the given aggregate and time range (or without time range if not provided).
Step 2: Get the event ids and update the outbox table for those event ids to set status = 'pending' and reset the other fields.
But note: we might have a lot of events. We might want to do this in batches.
Also, we might want to replay only events that were already published? Or we might want to replay all events for that aggregate, including ones that are still pending?
If we reset the status of events that are still pending, then they will be published again (duplicate). But if they are already in the outbox as pending, then they are going to be published anyway. So we might only reset the ones that are already published.
So:
UPDATE outbox
SET status = 'pending', processing_at = NULL, published_at = NULL, attempts = 0
WHERE event_id IN (SELECT id FROM events WHERE aggregate_id = ? AND created_at BETWEEN ? AND ?)
AND status = 'published';
This way we only reset the ones that were already published.
But what if we want to replay events that failed? They are not published. Then we might want to reset those too? Actually, if they are in status 'processing' and stuck, we might want to reset them. But the replay might be for a specific aggregate and we want to make sure all events for that aggregate are sent again. So we might reset any status except 'pending'?
Alternatively, we can reset all events for that aggregate (regardless of status) to 'pending'. But then we might be resetting events that are already in the publisher's queue (status 'processing') and then we get duplicates. But the publisher will try to publish again and the consumer will deduplicate.
So we can reset all for that aggregate:
UPDATE outbox
SET status = 'pending', processing_at = NULL, published_at = NULL, attempts = 0
WHERE event_id IN (SELECT id FROM events WHERE aggregate_id = ? AND created_at BETWEEN ? AND ?);
But note: if we reset an event that is already in the publisher's queue (status 'processing'), then we might have two publishers trying to publish the same event? Because the first publisher might have claimed it and then we reset, and then another publisher might claim it again? That's okay because the first publisher might have already published (but not updated the outbox because of a crash) and then the second publisher publishes again -> duplicate. But the consumer will ignore.
So it's safe.
However, we must be cautious about the performance: updating many rows in the outbox table.
Let's design the tables:
events:
id UUID PRIMARY KEY,
aggregate_id VARCHAR(255) NOT NULL,
type VARCHAR(255) NOT NULL,
payload JSONB NOT NULL,
version INTEGER NOT NULL, -- for optimistic concurrency and ordering per aggregate
created_at TIMESTAMP NOT NULL DEFAULT NOW()
outbox:
event_id UUID PRIMARY KEY REFERENCES events(id) ON DELETE CASCADE, -- if we delete events, we delete outbox? But we might not delete events.
status VARCHAR(20) NOT NULL DEFAULT 'pending', -- or use enum if the DB supports
processing_at TIMESTAMP,
published_at TIMESTAMP,
attempts INTEGER NOT NULL DEFAULT 0,
CONSTRAINT chk_status CHECK (status IN ('pending', 'processing', 'published'))
Indexes:
events:
index on aggregate_id (for replay queries)
index on created_at (for time range)
outbox:
index on status (for the publisher to find pending events)
index on processing_at (for the reset job of stuck events)
Publisher:
We'll have a service that:
1. Claims a batch of pending events (with status = 'pending') by setting them to 'processing' and setting processing_at to now() and incrementing attempts.
2. For each event, publish to the message broker.
3. If publish succeeds, set status = 'published' and published_at = now().
4. If publish fails, set status back to 'pending' (or leave as processing and let the reset job handle it?).
We can do step 1 in a transaction with SKIP LOCKED to avoid conflicts.
Inbox:
We have a table for each consumer? Or a single table for all consumers?
Let's have a single table for all consumers:
inbox:
event_id UUID NOT NULL,
consumer_name VARCHAR(255) NOT NULL,
processed_at TIMESTAMP NOT NULL DEFAULT NOW(),
PRIMARY KEY (event_id, consumer_name)
Then when a consumer receives an event, it checks if there is a row for that event_id and consumer_name. If not, it processes and then inserts.
But note: the event_id is from the outbox (which is the same as the event id in the events table). So we can join if needed.
Replay UI:
We need a simple UI (web page) that allows:
- Input: aggregate_id (text) and optional start and end datetime.
- Button: Replay
When the button is clicked, we send a request to the backend (which must be authenticated and authorized) to reset the outbox events for that aggregate (and time range) to pending.
Steps in the backend:
1. Validate the input (aggregate_id must be provided, time range optional).
2. Build a query to find event ids from the events table for that aggregate and time range.
3. Update the outbox table for those event ids (if they exist) to set status='pending', processing_at=NULL, published_at=NULL, attempts=0.
But note: we might have a large number of events. We might want to do this in batches and maybe show progress.
However, we are not going to implement the UI in detail here, but we can design the API endpoint.
Let's design the API:
POST /api/replay
Body:
{
"aggregate_id": "123",
"start_time": "2024-01-01T00:00:00Z", // optional
"end_time": "2024-01-02T00:00:00Z" // optional
}
Response: 202 Accepted, and maybe a job id to track the replay progress.
But note: the update might be heavy and we don't want to do it in the HTTP request. So we can enqueue a job and then return a job id.
Alternatively, we can do it in the request if the number of events is small? But we don't know.
So we can:
- Validate the input.
- Count the number of events to be replayed (SELECT COUNT(*) FROM events WHERE aggregate_id = ? AND ...). If too many, we might reject? Or we can enqueue a job.
Let's assume we enqueue a job:
We have a `replay_jobs` table:
id UUID PRIMARY KEY,
aggregate_id VARCHAR(255) NOT NULL,
start_time TIMESTAMP,
end_time TIMESTAMP,
status VARCHAR(20) DEFAULT 'pending', -- pending, in_progress, completed, failed
total_events INTEGER,
processed_events INTEGER,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP
Then we create a job and then a background worker picks it up and does:
UPDATE outbox
SET status = 'pending', processing_at = NULL, published_at = NULL, attempts = 0
WHERE event_id IN (SELECT id FROM events WHERE aggregate_id = ? AND (created_at >= ? AND created_at <= ?));
Then update the job status to completed.
But we want to track progress? We can count the number of events before the update and then after? But the update might be one query.
Alternatively, we can update in batches and update the job progress.
However, the update is one statement and we don't get the number of rows updated easily? We can get the number of rows affected by the update and then update the job.
So:
Step 1: Count the number of events to be replayed.
Step 2: Update the outbox and get the number of rows updated (in the same transaction?).
But we are doing:
UPDATE outbox ... WHERE event_id IN (SELECT ...)
We can get the number of rows updated by the update statement.
So the worker:
total = SELECT COUNT(*) FROM events WHERE aggregate_id = ? AND ...;
updated = UPDATE outbox ... (and then return the number of updated rows).
Then update the job with total and processed = updated.
But note: the update might update rows that are already pending? Then we are resetting them again? That's okay.
However, we might have events that are not in the outbox? Then the update will not affect them. But by our design, every event should have an outbox row. So we can assume that the number of events from the events table equals the number of outbox rows for that aggregate and time range? Not necessarily, because we might have events that were produced but not in the outbox? But we write to both in the same transaction, so they should be in sync.
But what if we have a bug and some events are missing in outbox? Then the replay will not replay them. So we might want to insert missing outbox rows? That complicates.
Alternatively, we can change the replay to:
For each event in the events table (for that aggregate and time range) that does not have an outbox row, insert one? But then we are changing the outbox pattern?
Let's stick to resetting existing outbox rows.
So the replay job:
1. Count the total events from events table for the given criteria.
2. Update the outbox table for the event_ids that are in the events table (with the same criteria) and reset the status.
3. Record the number of rows updated (which might be less than total if some events are missing in outbox).
But note: the update might be heavy if there are many events. We can do:
UPDATE outbox o
SET status = 'pending', processing_at = NULL, published_at = NULL, attempts = 0
FROM events e
WHERE o.event_id = e.id
AND e.aggregate_id = ?
AND (e.created_at >= ? AND e.created_at <= ?) -- if time range provided
AND o.status != 'pending'; -- only reset if not already pending? But we want to reset even if pending? Actually, if it's already pending, we don't need to reset.
But we might want to reset even if it's pending? Because if it's pending, it will be published anyway. So we can skip resetting if already pending? Then we avoid unnecessary writes.
So:
AND o.status != 'pending'
Then we update only the ones that are not pending (i.e., processing or published).
However, if we want to replay events that are already in the publisher's queue (status 'processing'), we reset them and then the publisher might pick them up again? That's okay.
But if we don't reset the pending ones, then they are already going to be published. So we don't need to reset them.
So:
UPDATE outbox o
SET status = 'pending', processing_at = NULL, published_at = NULL, attempts = 0
FROM events e
WHERE o.event_id = e.id
AND e.aggregate_id = ?
AND (e.created_at >= ? AND e.created_at <= ?)
AND o.status != 'pending';
Then we get the number of rows updated.
But note: what if the event is not in the outbox? Then it won't be updated. We can left join? But then we are updating only existing outbox rows.
Alternatively, we can insert missing outbox rows? But that would be a different operation.
Let's not insert. We assume that every event has an outbox row.
So the replay job:
total_events = count of events for the aggregate and time range.
updated_rows = the number of rows updated by the above update.
Then we set the job as completed with total_events and processed_events = updated_rows.
But note: the update might be expensive and lock rows. We might want to do it in batches? But we are updating by a condition that might match many rows.
Alternatively, we can do:
Instead of updating, we can delete and re-insert? But then we lose the history of attempts? We are resetting anyway.
But we are resetting the same row. So update is fine.
However, if we have a huge number of events, we might want to update in batches to avoid long transactions.
We can do:
UPDATE outbox o
SET ...
WHERE o.event_id IN (
SELECT e.id FROM events e
WHERE e.aggregate_id = ?
AND (e.created_at >= ? AND e.created_at <= ?)
AND o.status != 'pending'
LIMIT 1000
)
Then loop until no more rows.
But then we need to run multiple updates. We can do that in a loop in the worker.
However, for simplicity, we can do one update and hope it's not too big. Or we can set a maximum number of events to replay? Or we can require the user to narrow the time range.
Let's not overcomplicate. We can do one update and if it takes too long, we can break? But SQL doesn't have a built-in way to break.
Alternatively, we can use a cursor in the application and update in batches.
But for the design, we can say:
The replay job updates in batches of 1000 until no more rows to update.
Now, what about the UI? We can show:
- Total events found for the aggregate and time range.
- Number of events that were reset (i.e., were not already pending).
And then the publisher will eventually publish them.
We might also want to show the status of the replay job (pending, in_progress, completed, failed).
So the API:
POST /api/replay_jobs
Body: { aggregate_id, start_time?, end_time? }
Returns: { job_id }
GET /api/replay_jobs/{job_id}
Returns: { status, total_events, processed_events, created_at, updated_at }
The UI polls this endpoint until the job is completed.
Now, let's think about the overall architecture:
We have:
- Application service: writes to `events` and `outbox` in the same transaction.
- Publisher service: reads from `outbox` and publishes to message broker, then updates `outbox`.
- Consumer service: reads from message broker, checks `inbox` for duplicates, processes, and writes to `inbox`.
- Replay service: (the API and worker) that resets the `outbox` for a given aggregate and time range.
But note: the consumer might be down? Then the events accumulate in the outbox? That's okay.
Also, the publisher might be down? Then events are in outbox with status pending.
Now, what about the event ordering? We have version in the events table for each aggregate. The publisher should publish in order of version for the same aggregate? But the outbox table is ordered by created_at? We might have multiple aggregates, so we can publish in order of created_at? But that might not be the same as the aggregate version?
However, the version is per aggregate. We want to publish events for the same aggregate in the order of version. But if we publish by created_at, and two events for the same aggregate are created at the same time (unlikely) then we might have out-of-order. But we have the version in the event, so the consumer can reorder? But the consumer might not have the full history?
We can have the publisher order by aggregate_id and version? But then we might be blocked by one aggregate? We can use a separate outbox per aggregate? That's not feasible.
Alternatively, we can have the consumer reorder by version for the same aggregate. But then the consumer must store the last version processed for each aggregate? That's complex.
The outbox pattern does not guarantee ordering across aggregates, but for the same aggregate, we must publish in order. How?
We can have the publisher:
SELECT * FROM outbox
WHERE status = 'pending'
ORDER BY aggregate_id, version
LIMIT 100
FOR UPDATE SKIP LOCKED
But then if we have many aggregates, we might be waiting for one aggregate to be processed? We can do:
We process in batches of 100 events, but ordered by aggregate_id and version. Then we update the status of these 100 events to 'processing'. Then we publish them one by one? But note: the publish might fail for one event, then we set that one back to pending? Then the next batch might include events from the same aggregate that are after the failed one? That might break ordering.
So we must ensure that for a given aggregate, we only have one event in processing at a time? Or we publish in order and then update the status only after all are published?
Alternatively, we can have a separate outbox per aggregate? Not feasible.
Let's think: the events for the same aggregate are written in order (because the application increments the version). The outbox table has the version. We can:
Claim a batch of events ordered by aggregate_id, version. But then we might claim events from different aggregates. We can publish them in any order? But for the same aggregate, we must publish in order. So we must publish the batch in order of aggregate_id, version.
But if we publish in order and one fails, we might not update the status of the ones after it? Then the next batch might include events from the same aggregate that are after the failed one? That would break ordering because the failed event might be retried later and then the events after it are already published?
So we must not claim events from the same aggregate until the previous one is published? That would be slow.
Alternatively, we can have a separate "lock" per aggregate? Or we can have a separate outbox table per aggregate? Not.
This is a hard problem. The outbox pattern does not solve ordering. It only ensures that events are eventually published.
For ordering, we might need to use a message broker that supports ordering per partition (like Kafka with key=aggregate_id). Then we can publish to the same partition for the same aggregate and the broker will preserve order. Then we don't need to worry about the publisher ordering? But we must publish in order to the same partition?
If we use Kafka, we can set the key to aggregate_id and then the producer will send to the same partition. But the producer might batch events from different aggregates and then send them out of order? Actually, Kafka preserves order within a partition. So if we send events for the same aggregate to the same partition, they will be in order. But we must send them in order? The producer might send a batch of events for different aggregates, but for the same aggregate, the events must be sent in order?
The producer sends batches to a partition. If we have two events for the same aggregate, they might be in the same batch and then the order is preserved because they are in the same batch and the same partition. But if we have two batches for the same aggregate, the first batch might be sent after the second batch? That would break order.
So we must ensure that for a given aggregate, we don't have two batches in flight at the same time? That's the same problem.
Alternatively, we can use a single thread per aggregate? Not feasible.
Given the complexity, we might assume that the events for the same aggregate are written sequentially (the application processes one command at a time for an aggregate) and then the version increases. Then we can have the publisher process events in order of version for the same aggregate by having a separate queue per aggregate? Not.
This is a known problem. The outbox pattern with a relational database and multiple publishers cannot guarantee ordering without additional mechanisms.
For simplicity, we can:
- Have only one publisher instance (so we don't have concurrent processing of the same aggregate). Then we can claim events ordered by aggregate_id, version and then publish in that order. But if we have one publisher, then we are limited by the speed of one publisher.
- Or we can use a message broker that guarantees ordering per key (like Kafka) and then we set the key to aggregate_id and then we must ensure that we send events for the same aggregate in order. We can do that by having a separate thread per aggregate? Not.
Alternatively, we can use a single partition per aggregate? That's not scalable.
Given the time, we might not solve ordering completely. We can document that the platform does not guarantee ordering across aggregates and for the same aggregate it's best effort if we have multiple publishers.
But if we have one publisher and we process in order of aggregate_id and version, then we are safe for the same aggregate.
So let's assume we have one publisher and we process in order of aggregate_id, version.
Then the publisher query:
SELECT * FROM outbox
WHERE status = 'pending'
ORDER BY aggregate_id, version
LIMIT 100
FOR UPDATE SKIP LOCKED
But note: the version is per aggregate. So ordering by aggregate_id, version will group by aggregate and then by version.
However, what if we have two aggregates and we claim 100 events, and the first 50 are for aggregate A and the next 50 for aggregate B. Then we publish the first 50 for A, then the 50 for B. That's okay because ordering is only per aggregate.
But if we have a batch that includes events for aggregate A and B, and we publish A then B, that's okay.
But if we have a batch that includes events for aggregate A (version 1,2,3) and aggregate B (version 1,2,3) and we publish in that order, then we are safe.
So the one publisher and ordering by aggregate_id, version should work.
But what if we have multiple publishers? Then two publishers might claim events for the same aggregate? We can avoid that by having a separate "lock" per aggregate? Or we can use a distributed lock on the aggregate_id? That's heavy.
Alternatively, we can use a single partition in the outbox table for each aggregate? Not.
Given the complexity, let's stick to one publisher for simplicity.
We can have multiple publishers if we use a message broker that guarantees ordering per key and we set the key to aggregate_id, and then we must ensure that the same aggregate is always sent to the same partition and we don't have two publishers sending to the same partition at the same time? That's not trivial.
So for now, we design for one publisher.
Now, let's summarize the design:
Tables:
events:
id (UUID, PK)
aggregate_id (VARCHAR)
type (VARCHAR)
payload (JSON)
version (INTEGER)
created_at (TIMESTAMP)
outbox:
event_id (UUID, FK to events.id, PK)
status (ENUM: pending, processing, published)
processing_at (TIMESTAMP)
published_at (TIMESTAMP)
attempts (INTEGER)
inbox:
event_id (UUID)
consumer_name (VARCHAR)
processed_at (TIMESTAMP)
PK (event_id, consumer_name)
replay_jobs:
id (UUID, PK)
aggregate_id (VARCHAR)
start_time (TIMESTAMP, nullable)
end_time (TIMESTAMP, nullable)
status (ENUM: pending, in_progress, completed, failed)
total_events (INTEGER)
processed_events (INTEGER)
created_at (TIMESTAMP)
updated_at (TIMESTAMP)
Indexes:
events:
idx_events_aggregate_id ON events(aggregate_id)
idx_events_created_at ON events(created_at)
outbox:
idx_outbox_status ON outbox(status)
idx_outbox_processing_at ON outbox(processing_at)
inbox:
idx_inbox_event_id ON inbox(event_id)
idx_inbox_consumer_name ON inbox(consumer_name)
replay_jobs:
idx_replay_jobs_aggregate_id ON replay_jobs(aggregate_id)
idx_replay_jobs_status ON replay_jobs(status)
Publisher:
- Runs in a loop (or scheduled).
- In each iteration:
1. Begin transaction.
2. Select a batch of events (e.g., 100) from outbox where status = 'pending' order by aggregate_id, version limit 100 for update skip locked.
3. Update the selected events to status = 'processing', processing_at = now(), attempts = attempts + 1.
4. Commit.
5. For each event in the batch, publish to the message broker (with key = aggregate_id if using Kafka for ordering).
6. If publish succeeds for an event, update that event to status = 'published', published_at = now().
7. If publish fails for an event, update that event to status = 'pending' (or leave as processing? We set back to pending so it can be retried).
8. We can also have a delay between retries? We can set a next_retry_at? But we don't have that column. We can use the attempts and processing_at? We can also have a separate job that resets events that have been in processing for more than X minutes.
But note: if we set back to pending immediately, we might retry too fast. We can have a backoff? We can set processing_at to now() + backoff? Then the publisher will not pick it up until the processing_at is in the future? But then we need to change the query to:
WHERE status = 'pending' OR (status = 'processing' AND processing_at <= NOW())
Actually, we can have:
The publisher only picks events with status = 'pending' OR (status = 'processing' AND processing_at <= NOW() AND attempts < max_attempts)?
But we don't have a max_attempts. We can have:
When we set to processing, we set processing_at = NOW() + interval '5 minutes'? Then we only pick events that are pending or processing with processing_at <= now().
Alternatively, we can have a separate column `next_retry_at` and then:
WHERE status = 'pending' OR (status = 'processing' AND next_retry_at <= NOW())
But we don't have that.
Let's keep it simple: we set status back to pending and let the publisher pick it up immediately. Then we might have a lot of retries. We can have a delay by setting processing_at to now() + interval '5 minutes' and then change the query to:
WHERE status = 'pending' OR (status = 'processing' AND processing_at <= NOW())
Then when we set to processing, we set processing_at = NOW() + interval '5 minutes'. Then if we fail, we set status = 'processing' and processing_at = NOW() + interval '5 minutes'? But then we are in a loop: we set to processing, then we fail, then we set to processing again with a new time. But we are already in processing? We can set to pending and then the next claim will set to processing with a new processing_at?
Alternatively, we can have:
When we claim, we set processing_at = NOW() and then we update the event to published or back to pending.
And we have a separate job that resets events that have been in processing for more than 5 minutes (to avoid stuck events). Then we don't need to set a next_retry_at.
Let's do:
Publisher claims by setting status to 'processing' and processing_at = NOW().
Then if publish fails, we set status back to 'pending' (and processing_at = NULL). Then it will be picked up immediately.
But then we might have a tight loop of failures. We can have a delay by not setting back to pending immediately, but setting to processing with a future processing_at? Then the publisher will not pick it up until that time.
So:
When we claim, we set processing_at = NOW().
If publish fails, we set status = 'processing' and processing_at = NOW() + interval '5 minutes'. Then the publisher will not pick it up until 5 minutes later.
Then we don't need a separate reset job? We can have both: if an event is in processing for more than 30 minutes, we reset it to pending? That's for stuck events (like if the publisher crashes after setting to processing but before publishing).
So:
Publisher:
Claim events: set status='processing', processing_at=NOW(), attempts=attempts+1.
For each event:
Try to publish.
If success: set status='published', published_at=NOW(), processing_at=NULL.
If fail: set status='processing', processing_at=NOW() + interval '5 minutes' (and keep attempts).
Then we have a separate job that runs every 10 minutes:
UPDATE outbox
SET status = 'pending', processing_at = NULL
WHERE status = 'processing' AND processing_at <= NOW() - interval '30 minutes';
This resets events that have been in processing for more than 30 minutes (stuck).
Replay job:
We update the outbox for the selected events (that are not pending) to set status='pending', processing_at=NULL, published_at=NULL, attempts=0.
But note: if an event is in processing (and stuck) we reset it? Yes, because we want to replay.
However, if an event is already pending, we skip.
So:
UPDATE outbox o
SET status = 'pending', processing_at = NULL, published_at = NULL, attempts = 0
FROM events e
WHERE o.event_id = e.id
AND e.aggregate_id = ?
AND (e.created_at >= ? AND e.created_at <= ?)
AND o.status != 'pending';
Then we count the number of rows updated.
Consumer:
When receiving an event:
1. Extract event_id and consumer_name (from configuration or from the event? We assume the consumer is configured with a name).
2. Check if there is a row in inbox with (event_id, consumer_name). If yes, skip.
3. If not, process the event.
4. Then insert into inbox (event_id, consumer_name) values (..., ...).
But note: what if the processing fails? Then we don't insert and we might retry (if the message broker redelivers). That's okay.
This design is resilient and provides deduplication and replay.
However, we are not addressing:
- Event schema evolution? We are storing the payload as JSON. We might need to handle schema changes.
- Security: the replay UI must be secured.
- Monitoring: we need to monitor the outbox table size, the publisher lag, etc.
- Scalability: the outbox table can become large. We might need to partition by time? But then replay by aggregate might be hard if the aggregate spans partitions.
- Retention: we need to decide how long to keep events and outbox rows. We might archive old events.
But for the purpose of this design, we have the core patterns.
Now, let's write the SQL for table creation.
We assume PostgreSQL.
Let's write the DDL:
events:
CREATE TABLE events (
id UUID PRIMARY KEY,
aggregate_id VARCHAR(255) NOT NULL,
type VARCHAR(255) NOT NULL,
payload JSONB NOT NULL,
version INTEGER NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_events_aggregate_id ON events(aggregate_id);
CREATE INDEX idx_events_created_at ON events(created_at);
outbox:
CREATE TABLE outbox (
event_id UUID PRIMARY KEY REFERENCES events(id) ON DELETE CASCADE,
status VARCHAR(20) NOT NULL DEFAULT 'pending',
processing_at TIMESTAMP,
published_at TIMESTAMP,
attempts INTEGER NOT NULL DEFAULT 0,
CONSTRAINT chk_outbox_status CHECK (status IN ('pending', 'processing', 'published'))
);
CREATE INDEX idx_outbox_status ON outbox(status);
CREATE INDEX idx_outbox_processing_at ON outbox(processing_at);
inbox:
CREATE TABLE inbox (
event_id UUID NOT NULL,
consumer_name VARCHAR(255) NOT NULL,
processed_at TIMESTAMP NOT NULL DEFAULT NOW(),
PRIMARY KEY (event_id, consumer_name)
);
CREATE INDEX idx_inbox_event_id ON inbox(event_id);
CREATE INDEX idx_inbox_consumer_name ON inbox(consumer_name);
replay_jobs:
CREATE TABLE replay_jobs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
aggregate_id VARCHAR(255) NOT NULL,
start_time TIMESTAMP,
end_time TIMESTAMP,
status VARCHAR(20) NOT NULL DEFAULT 'pending',
total_events INTEGER,
processed_events INTEGER,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_replay_jobs_aggregate_id ON replay_jobs(aggregate_id);
CREATE INDEX idx_replay_jobs_status ON replay_jobs(status);
We are using gen_random_uuid() for the replay_jobs id (PostgreSQL 13+).
Now, the application code:
When producing an event:
We assume we have an aggregate root that has an id and a version.
We generate a UUID for the event id.
Then:
BEGIN;
INSERT INTO events (id, aggregate_id, type, payload, version, created_at)
VALUES (event_id, aggregate_id, type, payload, version, NOW());
INSERT INTO outbox (event_id, status)
VALUES (event_id, 'pending');
COMMIT;
Then the publisher will pick it up.
Publisher code (pseudocode):
while true:
events = []
BEGIN;
SELECT id, aggregate_id, type, payload FROM outbox
WHERE status = 'pending'
ORDER BY aggregate_id, version
LIMIT 100
FOR UPDATE SKIP LOCKED;
UPDATE outbox
SET status = 'processing', processing_at = NOW(), attempts = attempts + 1
WHERE id IN (selected_ids);
COMMIT;
For each event in the selected events:
try:
publish_to_message_broker(event)
UPDATE outbox SET status = 'published', published_at = NOW(), processing_at = NULL
WHERE id = event.id;
except:
UPDATE outbox SET status = 'processing', processing_at = NOW() + interval '5 minutes'
WHERE id = event.id;
Then sleep for a short time.
And the reset job for stuck events:
Every 10 minutes:
UPDATE outbox
SET status = 'pending', processing_at = NULL
WHERE status = 'processing' AND processing_at <= NOW() - interval '30 minutes';
Replay job:
We have a worker that picks pending replay_jobs.
job = SELECT * FROM replay_jobs WHERE status = 'pending' ORDER BY created_at LIMIT 1 FOR UPDATE SKIP LOCKED;
Then:
total = SELECT COUNT(*) FROM events
WHERE aggregate_id = job.aggregate_id
AND (job.start_time IS NULL OR events.created_at >= job.start_time)
AND (job.end_time IS NULL OR events.created_at <= job.end_time);
updated = UPDATE outbox o
SET status = 'pending', processing_at = NULL, published_at = NULL, attempts = 0
FROM events e
WHERE o.event_id = e.id
AND e.aggregate_id = job.aggregate_id
AND (job.start_time IS NULL OR e.created_at >= job.start_time)
AND (job.end_time IS NULL OR e.created_at <= job.end_time)
AND o.status != 'pending';
Then update the job:
UPDATE replay_jobs
SET status = 'completed', total_events = total, processed_events = updated, updated_at = NOW()
WHERE id = job.id;
If there's an error, set job status to 'failed'.
The UI would:
- POST /replay_jobs to create a job.
- GET /replay_jobs/{id} to get the status.
This is a basic design. We might need to handle more edge cases and performance considerations.
Let me know if you have any questions.
I'll design a comprehensive resilient eventing platform with outbox/inbox patterns, deduplication, and replay capabilities. Here's the complete solution:
Architecture Overview
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Service A │ │ Event Store │ │ Service B │
│ (Producers) │───▶│ (Outbox Pattern)│◀──│ (Consumers) │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│ │ │
▼ ▼ ▼
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Service C │ │ Replay Service │ │ Monitoring │
│ (Producers) │ │ & UI │ │ & Dashboard │
└─────────────────┘ └──────────────────┘ └─────────────────┘
1. Database Schema
-- Event Store (Append-only)
CREATE TABLE events (
event_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
aggregate_id VARCHAR(255) NOT NULL,
aggregate_type VARCHAR(100) NOT NULL,
event_type VARCHAR(255) NOT NULL,
event_version INTEGER NOT NULL,
payload JSONB NOT NULL,
metadata JSONB,
timestamp TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
INDEX idx_aggregate (aggregate_id, aggregate_type, event_version),
INDEX idx_timestamp (timestamp),
INDEX idx_event_type (event_type)
);
-- Outbox Table (Transactional Integrity)
CREATE TABLE outbox (
outbox_id BIGSERIAL PRIMARY KEY,
event_id UUID NOT NULL REFERENCES events(event_id) ON DELETE CASCADE,
topic VARCHAR(255) NOT NULL,
partition_key VARCHAR(255),
status VARCHAR(50) NOT NULL DEFAULT 'PENDING',
attempts INTEGER NOT NULL DEFAULT 0,
last_attempt_at TIMESTAMP WITH TIME ZONE,
error_message TEXT,
scheduled_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
INDEX idx_status_scheduled (status, scheduled_at),
INDEX idx_topic (topic),
UNIQUE (event_id, topic) -- Prevent duplicate publishing
);
-- Inbox Table (Idempotency)
CREATE TABLE inbox (
inbox_id BIGSERIAL PRIMARY KEY,
event_id UUID NOT NULL REFERENCES events(event_id) ON DELETE CASCADE,
consumer_id VARCHAR(255) NOT NULL, -- Service/consumer identifier
processed_at TIMESTAMP WITH TIME ZONE,
status VARCHAR(50) NOT NULL DEFAULT 'RECEIVED',
processing_time_ms INTEGER,
error_count INTEGER DEFAULT 0,
last_error TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
UNIQUE (event_id, consumer_id),
INDEX idx_consumer_status (consumer_id, status),
INDEX idx_processed_at (processed_at)
);
-- Replay Jobs
CREATE TABLE replay_jobs (
job_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
aggregate_id VARCHAR(255),
aggregate_type VARCHAR(100),
event_type VARCHAR(255),
start_timestamp TIMESTAMP WITH TIME ZONE,
end_timestamp TIMESTAMP WITH TIME ZONE,
status VARCHAR(50) NOT NULL DEFAULT 'PENDING',
total_events INTEGER,
processed_events INTEGER DEFAULT 0,
filter_criteria JSONB, -- Additional filter criteria
created_by VARCHAR(255),
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
started_at TIMESTAMP WITH TIME ZONE,
completed_at TIMESTAMP WITH TIME ZONE,
error_message TEXT
);
-- Replay Job Events (Track which events were replayed)
CREATE TABLE replay_job_events (
job_id UUID NOT NULL REFERENCES replay_jobs(job_id) ON DELETE CASCADE,
event_id UUID NOT NULL REFERENCES events(event_id),
status VARCHAR(50) NOT NULL DEFAULT 'PENDING',
attempted_at TIMESTAMP WITH TIME ZONE,
error_message TEXT,
PRIMARY KEY (job_id, event_id)
);
2. Outbox Service Implementation
# outbox/publisher.py
import asyncio
from datetime import datetime, timedelta
from typing import List
import asyncpg
class OutboxPublisher:
def __init__(self, db_pool, message_broker):
self.db_pool = db_pool
self.broker = message_broker
self.batch_size = 100
self.max_attempts = 5
async def publish_loop(self):
"""Main publishing loop"""
while True:
try:
await self.publish_batch()
await asyncio.sleep(1) # Adjust based on load
except Exception as e:
logger.error(f"Publisher error: {e}")
await asyncio.sleep(5)
async def publish_batch(self):
"""Publish a batch of pending events"""
async with self.db_pool.acquire() as conn:
# Atomically claim events (SKIP LOCKED for concurrency)
events = await conn.fetch("""
SELECT o.outbox_id, o.event_id, o.topic, o.partition_key,
e.event_type, e.payload, e.metadata
FROM outbox o
JOIN events e ON o.event_id = e.event_id
WHERE o.status = 'PENDING'
AND o.scheduled_at <= NOW()
AND o.attempts < $1
ORDER BY o.scheduled_at
LIMIT $2
FOR UPDATE SKIP LOCKED
""", self.max_attempts, self.batch_size)
if not events:
return
# Mark as processing
outbox_ids = [e['outbox_id'] for e in events]
await conn.execute("""
UPDATE outbox
SET status = 'PROCESSING',
last_attempt_at = NOW(),
attempts = attempts + 1
WHERE outbox_id = ANY($1)
""", outbox_ids)
# Publish each event
for event in events:
try:
await self.broker.publish(
topic=event['topic'],
key=event['partition_key'],
value={
'event_id': str(event['event_id']),
'event_type': event['event_type'],
'payload': event['payload'],
'metadata': event['metadata']
}
)
# Mark as published
await conn.execute("""
UPDATE outbox
SET status = 'PUBLISHED',
published_at = NOW()
WHERE outbox_id = $1
""", event['outbox_id'])
except Exception as e:
logger.error(f"Failed to publish event {event['event_id']}: {e}")
# Schedule retry with exponential backoff
next_attempt = datetime.utcnow() + timedelta(
seconds=min(300, 2 ** event['attempts']) # Max 5 minutes
)
await conn.execute("""
UPDATE outbox
SET status = 'PENDING',
scheduled_at = $1,
error_message = $2
WHERE outbox_id = $3
""", next_attempt, str(e), event['outbox_id'])
3. Inbox Consumer with Deduplication
# inbox/consumer.py
import asyncpg
from datetime import datetime
class IdempotentConsumer:
def __init__(self, db_pool, consumer_id: str):
self.db_pool = db_pool
self.consumer_id = consumer_id
async def process_event(self, event: dict, message):
"""Process event with deduplication"""
event_id = event['event_id']
async with self.db_pool.acquire() as conn:
# Check if already processed (idempotency check)
already_processed = await conn.fetchrow("""
SELECT processed_at, status
FROM inbox
WHERE event_id = $1 AND consumer_id = $2
""", event_id, self.consumer_id)
if already_processed:
if already_processed['status'] == 'PROCESSED':
logger.info(f"Event {event_id} already processed, skipping")
return True
elif already_processed['status'] == 'FAILED':
# Allow retry for failed events
logger.info(f"Event {event_id} previously failed, retrying")
# Mark as received
await conn.execute("""
INSERT INTO inbox (event_id, consumer_id, status)
VALUES ($1, $2, 'RECEIVED')
ON CONFLICT (event_id, consumer_id)
DO UPDATE SET status = 'RECEIVED'
""", event_id, self.consumer_id)
try:
start_time = datetime.utcnow()
# Business logic here
await self.handle_event(event)
processing_time = (datetime.utcnow() - start_time).total_seconds() * 1000
# Mark as processed
await conn.execute("""
UPDATE inbox
SET status = 'PROCESSED',
processed_at = NOW(),
processing_time_ms = $1,
error_count = 0,
last_error = NULL
WHERE event_id = $2 AND consumer_id = $3
""", processing_time, event_id, self.consumer_id)
return True
except Exception as e:
logger.error(f"Failed to process event {event_id}: {e}")
await conn.execute("""
UPDATE inbox
SET status = 'FAILED',
error_count = error_count + 1,
last_error = $1
WHERE event_id = $2 AND consumer_id = $3
""", str(e), event_id, self.consumer_id)
return False
4. Replay Service & API
# replay/service.py
from datetime import datetime
from typing import Optional, Dict, List
import asyncpg
class ReplayService:
def __init__(self, db_pool, message_broker):
self.db_pool = db_pool
self.broker = message_broker
async def create_replay_job(self,
aggregate_id: Optional[str] = None,
aggregate_type: Optional[str] = None,
event_type: Optional[str] = None,
start_timestamp: Optional[datetime] = None,
end_timestamp: Optional[datetime] = None,
filter_criteria: Optional[Dict] = None,
created_by: str = "system") -> str:
"""Create a replay job"""
async with self.db_pool.acquire() as conn:
# Count matching events
count_query = """
SELECT COUNT(*) as total
FROM events
WHERE 1=1
"""
params = []
param_count = 1
if aggregate_id:
count_query += f" AND aggregate_id = ${param_count}"
params.append(aggregate_id)
param_count += 1
if aggregate_type:
count_query += f" AND aggregate_type = ${param_count}"
params.append(aggregate_type)
param_count += 1
if event_type:
count_query += f" AND event_type = ${param_count}"
params.append(event_type)
param_count += 1
if start_timestamp:
count_query += f" AND timestamp >= ${param_count}"
params.append(start_timestamp)
param_count += 1
if end_timestamp:
count_query += f" AND timestamp <= ${param_count}"
params.append(end_timestamp)
param_count += 1
total = await conn.fetchval(count_query, *params)
# Create job
job_id = await conn.fetchval("""
INSERT INTO replay_jobs
(aggregate_id, aggregate_type, event_type,
start_timestamp, end_timestamp,
total_events, filter_criteria, created_by, status)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'PENDING')
RETURNING job_id
""", aggregate_id, aggregate_type, event_type,
start_timestamp, end_timestamp,
total, filter_criteria, created_by)
# Get matching event IDs
events_query = """
SELECT event_id FROM events WHERE 1=1
"""
if aggregate_id:
events_query += f" AND aggregate_id = ${param_count}"
params.append(aggregate_id)
param_count += 1
if aggregate_type:
events_query += f" AND aggregate_type = ${param_count}"
params.append(aggregate_type)
param_count += 1
if event_type:
events_query += f" AND event_type = ${param_count}"
params.append(event_type)
param_count += 1
if start_timestamp:
events_query += f" AND timestamp >= ${param_count}"
params.append(start_timestamp)
param_count += 1
if end_timestamp:
events_query += f" AND timestamp <= ${param_count}"
params.append(end_timestamp)
param_count += 1
event_ids = await conn.fetch(events_query, *params)
# Insert into replay_job_events
if event_ids:
values = [(job_id, e['event_id']) for e in event_ids]
await conn.executemany("""
INSERT INTO replay_job_events (job_id, event_id)
VALUES ($1, $2)
""", values)
return str(job_id)
async def execute_replay_job(self, job_id: str):
"""Execute replay job"""
async with self.db_pool.acquire() as conn:
# Get job details
job = await conn.fetchrow("""
SELECT * FROM replay_jobs WHERE job_id = $1
""", job_id)
if not job:
raise ValueError(f"Job {job_id} not found")
# Update status
await conn.execute("""
UPDATE replay_jobs
SET status = 'RUNNING', started_at = NOW()
WHERE job_id = $1
""", job_id)
try:
# Get pending events for this job
events = await conn.fetch("""
SELECT e.event_id, e.event_type, e.payload, e.metadata,
rje.status as job_event_status
FROM replay_job_events rje
JOIN events e ON rje.event_id = e.event_id
WHERE rje.job_id = $1
AND rje.status = 'PENDING'
ORDER BY e.timestamp
""", job_id)
for event in events:
try:
# Re-publish event
await self.broker.publish(
topic=event['event_type'].lower().replace('.', '_'),
key=str(event['event_id']),
value={
'event_id': str(event['event_id']),
'event_type': event['event_type'],
'payload': event['payload'],
'metadata': event['metadata'],
'_replay': True,
'_replay_job_id': job_id
}
)
# Mark as replayed
await conn.execute("""
UPDATE replay_job_events
SET status = 'REPLAYED', attempted_at = NOW()
WHERE job_id = $1 AND event_id = $2
""", job_id, event['event_id'])
except Exception as e:
logger.error(f"Failed to replay event {event['event_id']}: {e}")
await conn.execute("""
UPDATE replay_job_events
SET status = 'FAILED',
attempted_at = NOW(),
error_message = $1
WHERE job_id = $2 AND event_id = $3
""", str(e), job_id, event['event_id'])
# Update job completion
processed = await conn.fetchval("""
SELECT COUNT(*) FROM replay_job_events
WHERE job_id = $1 AND status = 'REPLAYED'
""", job_id)
await conn.execute("""
UPDATE replay_jobs
SET status = 'COMPLETED',
processed_events = $1,
completed_at = NOW()
WHERE job_id = $2
""", processed, job_id)
except Exception as e:
logger.error(f"Replay job {job_id} failed: {e}")
await conn.execute("""
UPDATE replay_jobs
SET status = 'FAILED', error_message = $1
WHERE job_id = $2
""", str(e), job_id)
5. REST API Endpoints
# api/replay_api.py
from fastapi import FastAPI, HTTPException, Depends, BackgroundTasks
from pydantic import BaseModel, Field
from typing import Optional, List
from datetime import datetime
import uuid
app = FastAPI(title="Eventing Platform Replay API")
class ReplayRequest(BaseModel):
aggregate_id: Optional[str] = None
aggregate_type: Optional[str] = None
event_type: Optional[str] = None
start_timestamp: Optional[datetime] = None
end_timestamp: Optional[datetime] = None
filter_criteria: Optional[dict] = None
class ReplayJobResponse(BaseModel):
job_id: str
status: str
total_events: Optional[int]
processed_events: Optional[int]
created_at: datetime
started_at: Optional[datetime]
completed_at: Optional[datetime]
@app.post("/api/v1/replay", response_model=ReplayJobResponse)
async def create_replay_job(
request: ReplayRequest,
background_tasks: BackgroundTasks,
current_user: str = Depends(get_current_user)
):
"""Create a new replay job"""
try:
job_id = await replay_service.create_replay_job(
aggregate_id=request.aggregate_id,
aggregate_type=request.aggregate_type,
event_type=request.event_type,
start_timestamp=request.start_timestamp,
end_timestamp=request.end_timestamp,
filter_criteria=request.filter_criteria,
created_by=current_user
)
# Execute replay in background
background_tasks.add_task(
replay_service.execute_replay_job,
job_id
)
return await get_replay_job(job_id)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/v1/replay/{job_id}", response_model=ReplayJobResponse)
async def get_replay_job(job_id: str):
"""Get replay job status"""
job = await db.fetchrow("""
SELECT job_id, status, total_events, processed_events,
created_at, started_at, completed_at
FROM replay_jobs WHERE job_id = $1
""", job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
return dict(job)
@app.get("/api/v1/replay", response_model=List[ReplayJobResponse])
async def list_replay_jobs(
status: Optional[str] = None,
limit: int = 50,
offset: int = 0
):
"""List replay jobs with optional filter"""
query = """
SELECT job_id, status, total_events, processed_events,
created_at, started_at, completed_at
FROM replay_jobs
WHERE 1=1
"""
params = []
if status:
query += " AND status = $1"
params.append(status)
query += " ORDER BY created_at DESC LIMIT $%d OFFSET $%d" % (len(params)+1, len(params)+2)
params.extend([limit, offset])
jobs = await db.fetch(query, *params)
return [dict(job) for job in jobs]
@app.post("/api/v1/replay/{job_id}/cancel")
async def cancel_replay_job(job_id: str):
"""Cancel a running replay job"""
result = await db.execute("""
UPDATE replay_jobs
SET status = 'CANCELLED', completed_at = NOW()
WHERE job_id = $1 AND status IN ('PENDING', 'RUNNING')
""", job_id)
if result == "0":
raise HTTPException(status_code=400, detail="Job cannot be cancelled")
return {"message": "Job cancelled successfully"}
6. React UI Components
// ReplayDashboard.jsx
import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Select, DatePicker, message, Progress, Card, Row, Col } from 'antd';
import { PlayCircleOutlined, StopOutlined, EyeOutlined } from '@ant-design/icons';
const { RangePicker } = DatePicker;
const ReplayDashboard = () => {
const [jobs, setJobs] = useState([]);
const [loading, setLoading] = useState(false);
const [selectedJob, setSelectedJob] = useState(null);
const [createModalVisible, setCreateModalVisible] = useState(false);
const [form] = Form.useForm();
const fetchJobs = async (filters = {}) => {
setLoading(true);
try {
const params = new URLSearchParams();
if (filters.status) params.append('status', filters.status);
const response = await fetch(`/api/v1/replay?${params}`);
const data = await response.json();
setJobs(data);
} catch (error) {
message.error('Failed to fetch replay jobs');
} finally {
setLoading(false);
}
};
const createReplayJob = async (values) => {
try {
const response = await fetch('/api/v1/replay', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(values),
});
if (!response.ok) throw new Error('Failed to create job');
message.success('Replay job created successfully');
setCreateModalVisible(false);
form.resetFields();
fetchJobs();
} catch (error) {
message.error(error.message);
}
};
const cancelJob = async (jobId) => {
try {
await fetch(`/api/v1/replay/${jobId}/cancel`, { method: 'POST' });
message.success('Job cancelled');
fetchJobs();
} catch (error) {
message.error('Failed to cancel job');
}
};
const getStatusColor = (status) => {
const colors = {
PENDING: 'gold',
RUNNING: 'blue',
COMPLETED: 'green',
FAILED: 'red',
CANCELLED: 'default',
};
return colors[status] || 'default';
};
useEffect(() => {
fetchJobs();
const interval = setInterval(fetchJobs, 5000); // Auto-refresh every 5s
return () => clearInterval(interval);
}, []);
const columns = [
{
title: 'Job ID',
dataIndex: 'job_id',
key: 'job_id',
render: (text) => text.substring(0, 8) + '...',
},
{
title: 'Status',
dataIndex: 'status',
key: 'status',
render: (status) => (
<Tag color={getStatusColor(status)}>{status}</Tag>
),
},
{
title: 'Filter',
key: 'filter',
render: (_, record) => (
<div>
{record.aggregate_id && <div>Agg: {record.aggregate_id}</div>}
{record.event_type && <div>Type: {record.event_type}</div>}
{record.start_timestamp && (
<div>From: {new Date(record.start_timestamp).toLocaleString()}</div>
)}
</div>
),
},
{
title: 'Progress',
key: 'progress',
render: (_, record) => (
<Progress
percent={record.total_events ?
Math.round((record.processed_events / record.total_events) * 100) : 0}
status={record.status === 'FAILED' ? 'exception' : 'active'}
/>
),
},
{
title: 'Created',
dataIndex: 'created_at',
key: 'created_at',
render: (date) => new Date(date).toLocaleString(),
},
{
title: 'Actions',
key: 'actions',
render: (_, record) => (
<Space>
<Button
icon={<EyeOutlined />}
onClick={() => setSelectedJob(record)}
size="small"
/>
{record.status === 'RUNNING' && (
<Button
icon={<StopOutlined />}
onClick={() => cancelJob(record.job_id)}
size="small"
danger
/>
)}
</Space>
),
},
];
return (
<div className="replay-dashboard">
<Card
title="Event Replay Dashboard"
extra={
<Button
type="primary"
icon={<PlayCircleOutlined />}
onClick={() => setCreateModalVisible(true)}
>
New Replay
</Button>
}
>
<Table
columns={columns}
dataSource={jobs}
loading={loading}
rowKey="job_id"
pagination={{ pageSize: 20 }}
/>
</Card>
<Modal
title="Create Replay Job"
visible={createModalVisible}
onCancel={() => setCreateModalVisible(false)}
footer={null}
width={600}
>
<Form form={form} onFinish={createReplayJob} layout="vertical">
<Row gutter={16}>
<Col span={12}>
<Form.Item name="aggregate_id" label="Aggregate ID">
<Input placeholder="e.g., user-12345" />
</Form.Item>
</Col>
<Col span={12}>
<Form.Item name="aggregate_type" label="Aggregate Type">
<Select
placeholder="Select type"
options={[
{ value: 'User', label: 'User' },
{ value: 'Order', label: 'Order' },
{ value: 'Payment', label: 'Payment' },
]}
/>
</Form.Item>
</Col>
</Row>
<Row gutter={16}>
<Col span={12}>
<Form.Item name="event_type" label="Event Type">
<Select
placeholder="Select event type"
options={[
{ value: 'UserCreated', label: 'User Created' },
{ value: 'OrderPlaced', label: 'Order Placed' },
{ value: 'PaymentCompleted', label: 'Payment Completed' },
]}
/>
</Form.Item>
</Col>
</Row>
<Form.Item name="timeRange" label="Time Range">
<RangePicker showTime />
</Form.Item>
<Form.Item>
<Space>
<Button type="primary" htmlType="submit" loading={loading}>
Create Replay Job
</Button>
<Button onClick={() => setCreateModalVisible(false)}>
Cancel
</Button>
</Space>
</Form.Item>
</Form>
</Modal>
{selectedJob && (
<Modal
title={`Job Details: ${selectedJob.job_id.substring(0, 8)}...`}
visible={!!selectedJob}
onCancel={() => setSelectedJob(null)}
footer={null}
width={800}
>
<Descriptions bordered>
<Descriptions.Item label="Status">
<Tag color={getStatusColor(selectedJob.status)}>
{selectedJob.status}
</Tag>
</Descriptions.Item>
<Descriptions.Item label="Total Events">
{selectedJob.total_events}
</Descriptions.Item>
<Descriptions.Item label="Processed">
{selectedJob.processed_events}
</Descriptions.Item>
<Descriptions.Item label="Created">
{new Date(selectedJob.created_at).toLocaleString()}
</Descriptions.Item>
{selectedJob.started_at && (
<Descriptions.Item label="Started">
{new Date(selectedJob.started_at).toLocaleString()}
</Descriptions.Item>
)}
{selectedJob.completed_at && (
<Descriptions.Item label="Completed">
{new Date(selectedJob.completed_at).toLocaleString()}
</Descriptions.Item>
)}
{selectedJob.error_message && (
<Descriptions.Item label="Error" span={3}>
<Alert type="error" message={selectedJob.error_message} />
</Descriptions.Item>
)}
</Descriptions>
<Divider>Event Details</Divider>
<EventList jobId={selectedJob.job_id} />
</Modal>
)}
</div>
);
};
7. docker-compose Setup
version: '3.8'
services:
postgres:
image: postgres:15
environment:
POSTGRES_DB: eventing_platform
POSTGRES_USER: event_user
POSTGRES_PASSWORD: event_pass
volumes:
- postgres_data:/var/lib/postgresql/data
- ./init.sql:/docker-entrypoint-initdb.d/init.sql
ports:
- "5432:5432"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U event_user"]
interval: 10s
timeout: 5s
retries: 5
redis:
image: redis:7-alpine
ports:
- "6379:6379"
command: redis-server --appendonly yes
zookeeper:
image: confluentinc/cp-zookeeper:7.3.0
environment:
ZOOKEEPER_CLIENT_PORT: 2181
ZOOKEEPER_TICK_TIME: 2000
kafka:
image: confluentinc/cp-kafka:7.3.0
depends_on:
- zookeeper
environment:
KAFKA_BROKER_ID: 1
KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:9092
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
ports:
- "9092:9092"
publisher:
build: ./publisher
depends_on:
postgres:
condition: service_healthy
kafka:
condition: service_started
environment:
DATABASE_URL: postgresql://event_user:event_pass@postgres/eventing_platform
KAFKA_BOOTSTRAP_SERVERS: kafka:9092
restart: unless-stopped
consumer-example:
build: ./consumer-example
depends_on:
- publisher
environment:
DATABASE_URL: postgresql://event_user:event_pass@postgres/eventing_platform
KAFKA_BOOTSTRAP_SERVERS: kafka:9092
CONSUMER_ID: "consumer-1"
restart: unless-stopped
replay-service:
build: ./replay-service
depends_on:
postgres:
condition: service_healthy
kafka:
condition: service_started
environment:
DATABASE_URL: postgresql://event_user:event_pass@postgres/eventing_platform
KAFKA_BOOTSTRAP_SERVERS: kafka:9092
ports:
- "8000:8000"
restart: unless-stopped
frontend:
build: ./frontend
depends_on:
- replay-service
ports:
- "3000:3000"
environment:
REACT_APP_API_URL: http://localhost:8000
volumes:
postgres_data:
8. Monitoring & Alerts
# prometheus.yml
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'postgres'
static_configs:
- targets: ['postgres:5432']
metrics_path: /metrics
params:
database: [eventing_platform]
- job_name: 'publisher'
static_configs:
- targets: ['publisher:8000']
- job_name: 'replay-service'
static_configs:
- targets: ['replay-service:8000']
- job_name: 'consumer'
static_configs:
- targets: ['consumer-example:8000']
-- Key Metrics Queries
-- 1. Outbox lag (events waiting to be published)
SELECT
status,
COUNT(*) as count,
MIN(scheduled_at) as oldest,
MAX(scheduled_at) as newest
FROM outbox
WHERE status IN ('PENDING', 'PROCESSING')
GROUP BY status;
-- 2. Consumer processing lag
SELECT
i.consumer_id,
COUNT(*) as pending_count,
MAX(e.timestamp) as latest_event_time,
NOW() - MAX(e.timestamp) as processing_lag
FROM inbox i
JOIN events e ON i.event_id = e.event_id
WHERE i.status = 'RECEIVED'
GROUP BY i.consumer_id;
-- 3. Replay job stats
SELECT
status,
COUNT(*) as job_count,
AVG(EXTRACT(EPOCH FROM (completed_at - started_at))) as avg_duration_secs
FROM replay_jobs
WHERE completed_at IS NOT NULL
GROUP BY status;
-- 4. Event throughput by type
SELECT
event_type,
DATE_TRUNC('hour', timestamp) as hour,
COUNT(*) as event_count
FROM events
WHERE timestamp > NOW() - INTERVAL '24 hours'
GROUP BY event_type, hour
ORDER BY hour DESC, event_count DESC;
9. Key Features Implemented
✅ Outbox Pattern
- Atomic write to events + outbox in same transaction
- Scheduled retries with exponential backoff
- SKIP LOCKED for concurrent publishers
- Dead letter handling via error tracking
✅ Inbox Pattern & Deduplication
- Consumer-specific idempotency (event_id + consumer_id)
- Status tracking (RECEIVED → PROCESSED/FAILED)
- Processing time metrics
- Automatic retry for failed events
✅ Replay System
- Flexible filtering (aggregate, type, time range)
- Background job execution with status tracking
- Progress tracking per job
- Isolation: replay events marked with
_replay metadata
- Cancellable jobs
✅ Observability
- Comprehensive metrics (lag, throughput, errors)
- Job progress tracking
- Detailed error logging
- Dashboard with auto-refresh
✅ Resilience Features
- Message broker integration (Kafka example)
- Exponential backoff
- Stuck message detection (30+ min in PROCESSING)
- Transactional integrity
- Schema evolution support via JSONB payloads
10. Deployment Considerations
-
Scalability:
- Partition outbox by topic/aggregate for high throughput
- Use separate databases per microservice if needed
- Consumer group scaling (each consumer gets unique consumer_id)
-
Data Retention:
-- Archive old events (partition by month)
CREATE TABLE events_2024_01 PARTITION OF events
FOR VALUES FROM ('2024-01-01') TO ('2024-02-01');
-- Drop old partitions after archive
DETACH PARTITION events_2023_01;
-
Backup Strategy:
- WAL archiving for point-in-time recovery
- Separate backup for outbox/inbox (smaller tables)
- Event store critical for replay - ensure durability
-
Security:
- JWT authentication for API
- Role-based access control (who can trigger replays)
- Encrypt sensitive payloads at rest
- Network segmentation between services
This architecture provides a production-ready, resilient eventing platform with full replay capabilities while maintaining exactly-once processing semantics through the outbox/inbox patterns.