We are to design an event-driven architecture with the following components and considerations:
- Outbox pattern: to ensure reliable event publishing without two-phase commit.
- Idempotent consumers: to handle duplicate events safely.
- Ordering keys: to maintain order for events that need to be processed in order.
- Replays: the ability to replay events for recovery or reprocessing.
Let's break down the design:
-
Outbox Pattern:
- When a service performs a transaction that also needs to produce events, we write the events to an outbox table in the same database transaction.
- A separate process (outbox publisher) polls the outbox table for new events and publishes them to the message broker (e.g., Kafka, RabbitMQ).
- After successful publish, the outbox records are marked as published or deleted.
-
Idempotent Consumers:
- Each event should have a unique identifier (event ID) and the consumer must track which events it has already processed.
- We can use a database table in the consumer service to store the IDs of processed events (with a TTL or manual cleanup) and check before processing.
- Alternatively, if the message broker supports exactly-once semantics (like Kafka with idempotent producers and transactions) and the consumer uses transactional processing, we might rely on that, but we still need to design for at-least-once delivery in general.
-
Ordering Keys:
- For events that must be processed in order (e.g., for a given aggregate or entity), we use a partitioning key (ordering key) in the message broker.
- In Kafka, we can use the same partition for a given ordering key (like an aggregate ID) so that Kafka guarantees order within a partition.
- The consumer must process events from a partition sequentially (which Kafka ensures by giving one consumer per partition in a consumer group).
-
Replays:
- To replay events, we need to store events for a certain period (or indefinitely) in a durable log (like Kafka topics) and have consumers that can start from a given offset or event time.
- We must design events to be immutable and include all necessary data for reprocessing (or have a way to reconstruct state from events).
- The consumer should be able to reset its offset to an earlier point and reprocess events, but note that we must be careful with side effects (hence idempotency is important).
Let's design a system with these in mind:
Components:
Considerations:
-
Event Schema: Events should be versioned (using a schema registry) and contain all necessary data for processing without requiring external lookups (to avoid lost updates and to support replay).
-
Outbox Publisher Reliability: The outbox publisher must be reliable and handle failures. We can use a separate transaction for marking as published? But note: if we update the outbox record as published and then fail to publish, we lose the event. So we must first publish and then update. We can use a two-phase approach in the publisher? Or we can rely on the broker's exactly-once if using Kafka and the publisher is idempotent and transactional. However, the outbox pattern is often used to avoid two-phase commit. So the publisher must be idempotent and we must be able to retry publishing without duplicating events in the broker? Actually, if we publish the same event multiple times (with the same event_id) to Kafka, and we have idempotent producer, Kafka will deduplicate. But then the consumer must also be idempotent because the same event might be delivered multiple times (even with idempotent producer, at-least-once delivery to consumers). So we rely on consumer idempotency.
-
Ordering within an aggregate: We must ensure that for a given aggregate, events are published in the order of the business transaction. Since we are writing to the outbox in the same transaction, the created_at or id (auto-increment) will reflect the order. The outbox publisher must publish in that order (by selecting ordered by id or created_at). But note: if the publisher publishes in parallel for different aggregates, that's fine. But for the same aggregate, we must publish in order. So when selecting, we must order by the aggregate's event sequence? Actually, the outbox table might have multiple events for the same aggregate. We must publish them in the order they were committed. We can order by id (which is auto-increment and reflects commit order) but note: if two transactions for the same aggregate are committed in order, their outbox records will have increasing id. So if we order by id and publish one by one, we maintain order. However, if we have multiple publisher threads, we might break order. So we must either:
* Use one publisher thread and order by id (or created_at and id to break ties) and then publish.
* Or, partition the outbox by aggregate_id and have one publisher per partition? That might be complex.
Alternatively, we can rely on the fact that for the same aggregate, the events will have the same partition key and if we publish them in order (by the order of the outbox record creation) and the broker maintains order per partition, then as long as we publish in order, the broker will deliver in order. But note: if we have multiple publishers, they might publish out of order for the same partition. So we must ensure that for a given partition key, we publish in order. One way is to have a single publisher thread that processes the outbox in order and publishes. But that might be a bottleneck. Alternatively, we can use a queue per aggregate? That's not scalable.
- Consumer Idempotency:
We have a table processed_events with columns:
event_id (unique, primary key)
aggregate_id (maybe, for cleanup by aggregate)
processed_at
... maybe other metadata.
When processing an event:
START TRANSACTION;
IF NOT EXISTS (SELECT 1 FROM processed_events WHERE event_id = ?) THEN
process the event (update business state)
INSERT INTO processed_events (event_id, aggregate_id, processed_at) VALUES (?, ?, NOW());
END IF;
COMMIT;
But note: if the processing fails, we don't insert into processed_events and we can retry.
However, if the processing takes a long time, we might hold the transaction open for a long time. We can do:
Check if event_id exists -> if yes, skip.
If not, process and then insert.
But what if two events for the same aggregate are processed concurrently? They might both see that the event is not processed and then both process? But if they are for the same aggregate, they should be in the same partition and thus processed by the same consumer instance (same thread) sequentially. So we don't have concurrent processing for the same partition. However, if we have multiple partitions, then different aggregates can be processed concurrently. But for the same aggregate, they are in the same partition and thus processed by one consumer at a time. So we don't need to worry about concurrent processing for the same event_id? Actually, we might have multiple consumer instances in the same group, but each partition is assigned to only one consumer at a time. So for a given event_id (which is unique) we will only have one consumer processing it at a time. But we might have multiple consumers in the same group processing different partitions. So we might have two different events (with different event_id) for the same aggregate? No, because the same aggregate is in the same partition, so they are processed by the same consumer sequentially. So we don't have concurrent processing for the same aggregate. But we might have two different aggregates being processed concurrently. That's okay because they are independent.
However, what if we have two events for two different aggregates that happen to have the same event_id? We generate event_id as UUID? Then it's unique. So we are safe.
But note: the processed_events table must be in the same database as the business data? It can be in the same database and we use the same transaction for processing and recording the event as processed. That ensures atomicity.
However, if we are using a relational database, we can do:
START TRANSACTION;
-- check and process business data (which might involve multiple tables)
-- then insert into processed_events.
COMMIT;
This is safe.
But what if the consumer crashes after processing the business data but before inserting into processed_events? Then on restart, it will reprocess the event. But because the business processing might be non-idempotent, we have a problem. So we must make the business processing idempotent or we must insert the processed_events record before processing? But then if we insert and then crash before processing, we skip the event and the business state is not updated. That's also bad.
So we must do both in the same transaction. If we crash after committing the business data but before committing the processed_events, then the transaction rolls back and we retry. That's safe.
However, if the business processing is not idempotent and we do it in a transaction that also records the event as processed, then if we retry, we will try to do the same business update again? But we check the processed_events first. So if the transaction committed, then the processed_events record is there and we skip. If the transaction rolled back, then the processed_events is not there and we retry. But note: the business update might have been partially applied? No, because it's in a transaction. So it's all or nothing.
So the consumer must:
Read the event.
Start a transaction.
Check if event_id exists in processed_events -> if yes, rollback and skip.
Else, process the event (update business tables) and then insert into processed_events.
Commit.
This is safe.
But note: the check and the insert must be in the same transaction to avoid a race condition with another consumer? But we don't have two consumers for the same partition. So we don't have concurrent processing for the same event. However, if we have multiple consumers in the same group, they are processing different partitions. So they might try to process the same event_id? No, because the same event is only in one partition and delivered to one consumer. So we don't have concurrent processing for the same event. But we might have a scenario where the same event is redelivered (because of a rebalance) and then two consumers (at different times) might try to process the same event? But when a rebalance happens, the partitions are reassigned and the consumer that gets the partition will start from the last committed offset. If we commit the offset after processing, then we won't reprocess. But if we don't commit the offset (or commit before processing) then we might reprocess. So we must commit the offset after processing (and after the transaction commits). But note: if we commit the offset and then crash before committing the transaction, then the business update is lost and the offset is committed -> we skip the event. That's bad.
So we must commit the offset only after the transaction commits. But note: Kafka allows committing offsets in a transaction? Yes, if we use the consumer as part of a transaction (exactly-once). But we are not using exactly-once in the consumer? We are using at-least-once and idempotent processing.
Alternatively, we can commit the offset after the transaction commits (manually). But if we crash after committing the offset and before the transaction, then we skip. If we crash after the transaction but before committing the offset, then we might reprocess. But that's okay because we are idempotent.
So the safe way:
Process event in a transaction (including recording in processed_events).
After the transaction commits, commit the Kafka offset.
But note: if the transaction commits and then we crash before committing the offset, then on restart we will reprocess the event. But the transaction already committed, so the business update is there. Then we process again and we will see the event_id in processed_events and skip. So no harm.
If we commit the offset and then crash before the transaction, then the offset is committed but the business update is not. Then we skip the event and the business state is not updated. That's bad.
So we must commit the offset only after the transaction commits.
Steps:
consumer.poll()
for each record:
event = deserialize(record.value())
eventId = event.getEventId()
begin transaction
try:
if (processedEventRepository.existsById(eventId)) {
// skip
transaction.rollback()
} else {
// process event
businessService.process(event)
processedEventRepository.save(new ProcessedEvent(eventId, ...))
transaction.commit()
// commit offset after transaction commit
consumer.commitSync(Collections.singletonMap(topicPartition, new OffsetAndMetadata(record.offset() + 1)))
}
catch (Exception e) {
transaction.rollback()
// we don't commit offset, so we will retry
throw e; // or let the consumer loop continue? We should let the consumer continue and retry later? Actually, we should not commit the offset and then the same event will be retried in the next poll.
}
But note: if we are processing multiple events in a loop, we commit the offset for each event? That's inefficient. We can batch the offset commit after processing a batch of events. But then we must be careful: if we process a batch of events and then commit the offset for the entire batch, but one event in the batch fails, then we don't want to commit the offset for the events that succeeded? Actually, we want to commit the offset only for the events that were successfully processed (and recorded in processed_events). So we can do:
List<Event> batch = consumer.poll(...)
for (Event event : batch) {
// process each event in its own transaction? Or one transaction for the entire batch?
// If we do one transaction for the entire batch, then if one fails, we rollback the entire batch and then we will retry the entire batch. But then we might process some events twice? But if we are idempotent, it's okay. But note: if the batch is large, we might have a long transaction.
Alternatively, we can do one transaction per event. Then we can commit the offset for each event as we succeed. But that's a lot of commits.
Another idea: We can use the Kafka consumer's automatic commit? But that's dangerous because we might commit before processing.
Given the complexity, we might do:
for each event in the batch:
process in a separate transaction and then commit the offset for that event immediately after.
But that's a lot of database and Kafka commits.
Alternatively, we can process the batch in a single transaction and then commit the offset for the entire batch only if all succeed. If one fails, we rollback and then we will retry the entire batch. But then we might process events that already succeeded again? But if we are idempotent, it's okay. However, if the batch is large, we might have a long-running transaction and if one event fails, we rollback and then we have to reprocess the entire batch. That might be acceptable if batches are small.
Let's do:
consumer.poll() -> batch of records.
We sort the records by offset? Actually, Kafka returns records in order per partition, but we might have multiple partitions. We must process each partition's events in order, but we can process different partitions concurrently? But then we have to manage transactions per partition? And we cannot have a single transaction that spans multiple partitions? Actually, we can have one transaction per event and then commit the offset for that partition after each event? But then we are back to one transaction per event.
Given that we are using a relational database and we want to update the business state and record the event as processed in the same transaction, and we want to commit the offset only after the transaction, we can do:
For each record in the batch (in the order of the partition and offset):
event = ...
transaction.begin()
try:
if (not processed) {
process(event)
recordProcessed(event)
}
transaction.commit()
// We don't commit the offset immediately because we are in a loop. We can commit at the end of the batch? But then if we process 10 events and then commit the offset for the last one, we have committed the offset for the entire batch? Actually, we want to commit the offset for each partition up to the offset of the last event we processed in that partition.
} catch (Exception e) {
transaction.rollback()
// We don't commit the offset for this event, and we break? Or we continue with the next event? We must be careful: if we are processing multiple partitions, we might want to continue with other partitions? But for the same partition, we must stop at the failed event because we cannot skip. So we should process events in the batch by partition and in order. So we can group by partition and then for each partition, process in order until a failure, then stop for that partition.
Then after processing the batch, we commit the offsets for the partitions that we successfully processed up to the last successful event in that partition.
This is getting complex.
Alternatively, we can process the batch and if any event fails, we do not commit any offsets for that partition? But then we will retry the entire batch for that partition? That might be okay if batches are small.
Let's simplify: We assume that the consumer processes events one at a time (or in small batches) and we commit the offset after each event (or after a batch of events that are all for the same partition and we have processed them all). But note: the consumer might have events from multiple partitions in one batch. We can process each partition's events in order and commit the offset for that partition after processing all events for that partition in the batch? But then if one event in a partition fails, we don't commit the offset for that partition and we will retry from the last committed offset (which might be before the failed event). That would reprocess events that already succeeded? But they are idempotent, so it's okay.
Given the complexity, I would recommend:
- Process events in the order they are returned by the consumer (which is per partition order).
- For each event, process in a separate transaction and then commit the offset for that event immediately after the transaction commits.
But that's a lot of commits. We can do:
for (ConsumerRecord<String, String> record : records) {
Event event = deserialize(record.value());
TransactionTemplate.execute(status -> {
if (!processedEventRepository.existsByEventId(event.getEventId())) {
businessService.process(event);
processedEventRepository.save(new ProcessedEvent(event.getEventId(), ...));
}
});
// commit offset for this record
consumer.commitSync(Collections.singletonMap(
new TopicPartition(record.topic(), record.partition()),
new OffsetAndMetadata(record.offset() + 1)
));
}
But note: if the transaction fails, we don't commit the offset and we will retry the same event. That's correct.
However, if the transaction commits and then we crash before committing the offset, we will retry the event. But the transaction already committed, so we will see the event in processed_events and skip. That's okay.
But if we commit the offset and then crash before the transaction, then we skip the event and the business update is lost. That's bad.
So we must commit the offset only after the transaction commits. So:
TransactionTemplate.execute(status -> {
if (!processedEventRepository.existsByEventId(event.getEventId())) {
businessService.process(event);
processedEventRepository.save(new ProcessedEvent(event.getEventId(), ...));
}
// Now we are still in the transaction. We want to commit the offset after the transaction, so we cannot do it inside.
return null;
});
// transaction committed
consumer.commitSync(...);
But if the transaction commits and then we crash before committing the offset, we will retry. That's acceptable.
However, if the transaction commits and then we commit the offset, and then we crash, we have committed the offset and the transaction is committed. That's safe.
So:
try {
TransactionTemplate.execute(status -> {
if (!processedEventRepository.existsByEventId(event.getEventId())) {
businessService.process(event);
processedEventRepository.save(new ProcessedEvent(event.getEventId(), ...));
}
});
// If we get here, the transaction committed.
consumer.commitSync(Collections.singletonMap(
new TopicPartition(record.topic(), record.partition()),
new OffsetAndMetadata(record.offset() + 1)
));
} catch (Exception e) {
// transaction rolled back, we don't commit offset and we will retry.
log.error("Failed to process event {}", event.getEventId(), e);
}
But note: the `existsByEventId` and the `save` are in the same transaction, so we are safe from concurrent processing? As argued, for the same partition, we are sequential. But what if we have multiple consumers in the same group? They are processing different partitions. So two consumers might try to process the same event_id? No, because the same event is only in one partition. So we are safe.
However, if we have a rebalance and the same partition is assigned to a different consumer, then the new consumer will start from the last committed offset. If we had committed the offset for an event that was processed (and the transaction committed) then we skip. If we hadn't committed the offset, we will retry and see the event in processed_events and skip. So we are safe.
5. Replays:
To replay, we can:
a) Reset the consumer group offset to an earlier offset (using Kafka tools) and then start the consumer. The consumer will process from that offset. Because we are idempotent, processing the same events again will not change the business state (if we skip already processed events). But note: if we want to completely reset the state, we might need to delete the business data and the processed_events. Then reset the offset and replay. But that's a separate operation.
b) Alternatively, we can have a separate replay consumer group that always starts from the beginning (or a specific timestamp) and writes to a separate topic or updates the same state? But if we want to rebuild the state, we might need to delete the current state and then replay from the beginning. We can do:
Step 1: Stop the normal consumer.
Step 2: Delete the business data (or truncate tables) and the processed_events.
Step 3: Reset the consumer group offset to the beginning.
Step 4: Start the consumer.
But note: if we delete the business data and then replay, we will process all events again. That's the replay.
However, if we have a large dataset, we might want to do a snapshot and then replay only the events after the snapshot. That's a different pattern (event sourcing with snapshots). But we are not doing event sourcing here, we are just using events for integration. So we assume the business data is stored in a traditional database and we update it from events. Then to rebuild, we need to delete and replay.
But what if we have multiple services? We might need to replay each service independently.
So the replay mechanism is:
- For each service that needs to be replayed:
* Stop the service (or at least stop the consumer).
* Delete the business data (or truncate the tables that are built from events) and the processed_events table.
* Reset the consumer group offset for the topics that this service consumes to the earliest (or to a specific offset/timestamp).
* Start the service.
But note: if the service has multiple topics, we might need to reset all.
Alternatively, we can have a separate tool that does:
DELETE FROM business_tables;
DELETE FROM processed_events;
Then reset the offset.
But we must be careful: if the service is running, we might have a race condition. So we stop the service.
Another idea: We can have a flag in the consumer that, when set, will ignore the processed_events and reprocess everything? But then we would process events that are already in the business data? That would cause duplicates. So we must delete the business data first.
So the replay is a manual process.
6. Other Considerations:
- **Schema Registry**: Use Avro or Protobuf with a schema registry to ensure compatibility.
- **Monitoring**: Monitor the outbox table size, publisher lag, consumer lag, and replay capabilities.
- **Security**: Use SSL and authentication for Kafka.
- **Dead Letter Queue**: For events that fail after a number of retries, we can send them to a DLQ for manual inspection.
7. Diagram:
+----------------+ +----------------+ +----------------+
| Service A | | Kafka | | Service B |
| (with Outbox) |---->| Topic |---->| (Consumer) |
+----------------+ +----------------+ +----------------+
| | |
| (outbox table) | (partition by key) | (processed_events)
| | |
v v v
+----------------+ +----------------+ +----------------+
| Database | | Brokers | | Database |
+----------------+ +----------------+ +----------------+
8. Summary of Steps:
**Producer (Service A)**:
- In the same transaction that updates the business data, insert into the outbox table.
- The outbox publisher runs in a loop:
* Start transaction.
* Select a batch of outbox records (where published_at is null) ordered by id (or created_at) and lock them (FOR UPDATE SKIP LOCKED).
* For each record in the batch:
- Publish to Kafka with the aggregate_id as the partition key (if ordering is required) and the event_id as the message key (for deduplication in Kafka, if using idempotent producer).
- If publish succeeds, add the record to a list to mark.
- If publish fails, break the loop.
* Update the outbox records that were successfully published (set published_at = now()).
* Commit the transaction.
- The outbox publisher must be idempotent in the sense that if it fails after publishing but before updating, it will republish. But that's okay because of consumer idempotency.
**Consumer (Service B)**:
- For each event:
* Start a transaction.
* Check if event_id exists in processed_events. If yes, rollback and skip.
* If not, process the event (update business state) and then insert into processed_events.
* Commit the transaction.
* Commit the Kafka offset for that event (or for the partition up to that offset).
- The consumer must process events in order per partition (which Kafka guarantees by assigning one consumer per partition).
**Replay**:
- Stop the consumer.
- Delete the business data and the processed_events.
- Reset the consumer group offset to the earliest (or desired) offset.
- Start the consumer.
9. Potential Issues:
- **Outbox table growth**: We need to archive or delete old outbox records after they are published. We can have a TTL and a cleanup job.
- **Consumer processing time**: If processing an event takes too long, the consumer might be considered dead and a rebalance might occur. We need to adjust the max.poll.interval.ms and other timeouts.
- **Exactly-once vs at-least-once**: We are designing for at-least-once with idempotent consumers. If we need exactly-once, we would need to use Kafka transactions and the consumer as part of the transaction, which is more complex.
10. Code Sketches:
**Outbox Publisher (simplified)**:
while (true) {
List<Outbox> batch = outboxRepository.findUnpublishedOrderById(limit);
if (batch.isEmpty()) {
sleep(1000);
continue;
}
List<Outbox> toMark = new ArrayList<>();
for (Outbox outbox : batch) {
try {
kafkaTemplate.send(outbox.getTopic(), outbox.getAggregateId(), outbox.getEventId(), outbox.getPayload());
toMark.add(outbox);
} catch (Exception e) {
log.error("Failed to publish event: {}", outbox.getEventId(), e);
break;
}
}
outboxRepository.markAsPublished(toMark);
}
But note: we must lock the rows we select to avoid multiple publishers picking the same. So:
@Transactional
public List<Outbox> findUnpublishedOrderById(int limit) {
return outboxRepository.findFirstNByPublishedAtIsNullOrderByIdAsc(limit, LockModeType.PESSIMISTIC_WRITE);
}
And then we update and commit.
**Consumer**:
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) {
Event event = deserialize(record.value());
try {
transactionTemplate.execute(status -> {
if (!processedEventRepository.existsByEventId(event.getEventId())) {
businessService.process(event);
processedEventRepository.save(new ProcessedEvent(event.getEventId(), ...));
}
});
// Commit offset for this record's partition up to this offset.
consumer.commitSync(Collections.singletonMap(
new TopicPartition(record.topic(), record.partition()),
new OffsetAndMetadata(record.offset() + 1)
));
} catch (Exception e) {
log.error("Failed to process event: {}", event.getEventId(), e);
// We don't commit the offset, so it will be retried.
}
}
}
But note: the above commits after every event. We can batch the offset commit for the entire batch? But then if we have multiple partitions, we must commit the offset for each partition separately. We can do:
Map<TopicPartition, OffsetAndMetadata> offsetsToCommit = new HashMap<>();
for (ConsumerRecord<String, String> record : records) {
// ... same as above, but don't commit immediately.
// Instead, after processing the record, put the offset in the map.
offsetsToCommit.put(
new TopicPartition(record.topic(), record.partition()),
new OffsetAndMetadata(record.offset() + 1)
);
}
consumer.commitSync(offsetsToCommit);
But then if one event fails, we don't want to commit the offset for that partition? Actually, we want to commit only the events that succeeded. So we must track per partition the last successfully processed offset. And then commit that offset for each partition.
We can do:
Map<TopicPartition, Long> lastProcessedOffsetPerPartition = new HashMap<>();
for (ConsumerRecord<String, String> record : records) {
// process as above, but if success, update the lastProcessedOffsetPerPartition for that partition.
// if failure, we don't update and we break? But we might want to continue with other partitions?
// Actually, for a given partition, we must process in order and if one fails, we cannot skip. So we should stop processing that partition in this batch? But the records for a partition are in order and we are iterating in the order of the batch (which is per partition order? Not necessarily, the batch might have interleaved partitions). So we must process by partition.
Given the complexity, I think the simplest is to process one event at a time and commit the offset immediately. But that's inefficient.
Alternatively, we can process the batch and then commit the offset for each partition up to the last successful event in that partition. But we must process events in the order of the partition. The `ConsumerRecords` object has records grouped by partition? Actually, `ConsumerRecords` is a map of `TopicPartition` to `List<ConsumerRecord>`. So we can iterate by partition:
for (TopicPartition partition : records.partitions()) {
List<ConsumerRecord<String, String>> partitionRecords = records.records(partition);
long lastCommittedOffset = -1;
for (ConsumerRecord<String, String> record : partitionRecords) {
// process event
// if success, lastCommittedOffset = record.offset()
// if failure, break out of the inner loop and do not process further records in this partition for now.
}
if (lastCommittedOffset >= 0) {
consumer.commitSync(Collections.singletonMap(partition, new OffsetAndMetadata(lastCommittedOffset + 1)));
}
}
This way, we process each partition's events in order and commit the offset for that partition only up to the last successful event.
But note: if we break on a failure in a partition, we don't commit the offset for that partition and we will retry from the last committed offset (which might be before the failed event). That's acceptable because we will retry the failed event and then the ones after it.
However, if we have multiple events in the partition and the first one fails, we break and don't process the rest. Then we don't commit the offset for that partition and we will retry the same set (starting from the last committed offset). But note: the last committed offset might be before the first event in this batch? Actually, the consumer poll returns records starting from the last committed offset (or the assignment offset). So if we don't commit, the next poll will return the same records again (starting from the last committed offset). So we will retry the failed event and then the rest. That's acceptable.
So:
while (true) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (TopicPartition partition : records.partitions()) {
List<ConsumerRecord<String, String>> partitionRecords = records.records(partition);
long lastSuccessOffset = -1;
for (ConsumerRecord<String, String> record : partitionRecords) {
Event event = deserialize(record.value());
try {
transactionTemplate.execute(status -> {
if (!processedEventRepository.existsByEventId(event.getEventId())) {
businessService.process(event);
processedEventRepository.save(new ProcessedEvent(event.getEventId(), ...));
}
});
lastSuccessOffset = record.offset();
} catch (Exception e) {
log.error("Failed to process event: {} in partition {}", event.getEventId(), partition, e);
break; // break the inner loop for this partition
}
}
if (lastSuccessOffset >= 0) {
consumer.commitSync(Collections.singletonMap(partition, new OffsetAndMetadata(lastSuccessOffset + 1)));
}
}
}
This way, we commit the offset for a partition only up to the last successfully processed event in that batch. And we process events in order per partition.
But note: what if the transaction fails for an event that is not the first in the partition? We break and then we don't process the remaining events in that partition in this batch. Then we don't commit the offset for the last successful event? Actually, we do commit the offset for the last successful event. Then the next poll will start from that offset + 1? But wait: we are committing the offset for the last successful event in the batch. Then the next poll will start from that offset + 1? Actually, the commit is for the offset of the last event we processed + 1. Then the next poll will start from that offset. But we broke at event N (which failed). Then we committed up to event N-1. Then the next poll will start from event N (because the last committed offset is N-1, so the next offset is N). That's correct.
Example:
Partition events: [e1, e2, e3, e4] in the batch.
Process e1 -> success, lastSuccessOffset = offset(e1)
Process e2 -> success, lastSuccessOffset = offset(e2)
Process e3 -> failure, break.
Then we commit offset(e2)+1? Actually, we commit offset(e2)+1? We set lastSuccessOffset to offset(e2) and then commit offset(e2)+1? Wait: we are setting lastSuccessOffset to the offset of the record we just processed. Then when we commit, we do new OffsetAndMetadata(lastSuccessOffset + 1). So if we processed e2 and succeeded, then lastSuccessOffset is offset(e2). Then we commit offset(e2)+1. That means the next poll will start from offset(e2)+1, which is e3. But we haven't processed e3 yet. That's wrong.
Correction: We should commit the offset of the last event we processed, not the next one. Actually, the offset we commit is the offset of the next event we want to read. So if we have processed up to e2 (offset=1) and we want to start from offset=2 (e3) next, we commit offset=2. But we haven't processed e3. So we must not commit e3 until we have processed it.
So we must commit the offset of the last successfully processed event + 1? Actually, the offset we commit is the offset of the next message to read. So if we have processed e1 (offset0) and e2 (offset1) then we want to start from offset2 (e3). So we commit offset=2.
In our code:
for each record:
process record at offset X.
if success, then we have processed up to offset X, so the next offset to read is X+1. So we set lastSuccessOffset = X? and then commit lastSuccessOffset+1? That would be X+1.
But then when we break at e3 (offset=X2), we have lastSuccessOffset = offset of the last successful event (which is e2, offset=X1). Then we commit X1+1, which is the offset of e3. That's correct.
So the code is:
lastSuccessOffset = record.offset(); // when success
then commit lastSuccessOffset + 1.
But note: if we process the last event in the partition and succeed, then lastSuccessOffset is the offset of the last event. Then we commit lastSuccessOffset+1, which is the next offset (which might be beyond the current batch). That's correct.
So the above code is correct.
11. Conclusion:
This design provides:
- Reliable event publishing with the outbox pattern.
- Idempotent consumers with a processed_events table.
- Ordering by using partition keys and processing per partition sequentially.
- Replays by resetting offsets and clearing state.
However, note that the outbox publisher might become a bottleneck if we have a single thread. We can have multiple outbox publishers if we partition the outbox table by aggregate_id? But then we must ensure that for a given aggregate, the events are published by the same publisher? That's complex. Alternatively, we can use a single publisher and scale by having multiple instances of the service (with the same outbox table) but then we must partition the outbox table by service? That's not typical. Usually, the outbox pattern is implemented within the same service that produces the events. So if we need to scale the producer, we might have multiple instances of the same service, but then they are writing to the same outbox table? That would break because each service instance would have its own database? Actually, if we have multiple instances of the same service, they each have their own database? Then we have multiple outbox tables? And we need to publish from each. But then we have to coordinate? That's messy.
So the outbox pattern is typically for a single instance of the service. If we need to scale the producer, we might need to shard the service by aggregate_id so that each shard has its own database and outbox table. Then we can have multiple outbox publishers (one per shard). But that's a different architecture.
Given the complexity, we assume a single instance of the producer service.
For the consumer, we can scale by having multiple instances (in the same consumer group) and Kafka will assign partitions to them.
12. Additional Patterns:
- **Dead Letter Queue**: If an event fails after a certain number of retries, we can send it to a DLQ (another Kafka topic) for manual inspection.
- **Schema Evolution**: Use a schema registry and make sure events are backward and forward compatible.
- **Monitoring**: Monitor the size of the outbox table, the lag of the publisher, the consumer lag, and the number of events in the DLQ.
This design is a baseline and might need adjustments based on specific requirements.</think>
Here's a comprehensive event-driven architecture baseline incorporating the outbox pattern, idempotent consumers, ordering keys, and replay capabilities. This design prioritizes reliability, scalability, and debuggability.
1. Core Architecture Components
A. Event Producers (Services)
- Outbox Pattern: Each service maintains an
outbox table in its local database.
- Schema:
CREATE TABLE outbox (
id BIGSERIAL PRIMARY KEY,
aggregate_id VARCHAR(255) NOT NULL, -- Ordering key
event_id UUID NOT NULL UNIQUE, -- Global event ID
event_type VARCHAR(255) NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
published_at TIMESTAMP NULL,
retry_count INT DEFAULT 0,
error_message TEXT NULL
);
CREATE INDEX idx_outbox_unpublished ON outbox(published_at) WHERE published_at IS NULL;
CREATE INDEX idx_outbox_aggregate ON outbox(aggregate_id, created_at);
- Workflow:
- Business transaction updates local DB + writes event(s) to
outbox in the same transaction.
- Separate Outbox Publisher (async process) polls
outbox for unpublished events.
- Publishes events to Kafka (or Pulsar) with:
- Message Key:
aggregate_id (ensures ordering per aggregate).
- Headers:
event_id, event_type, source_service.
- On successful publish, marks
published_at. On failure, increments retry_count and logs error_message.
B. Message Broker (Kafka Recommended)
- Topic Configuration:
retention.ms: Long retention (e.g., 30 days) for replays.
cleanup.policy: delete (based on retention).
segment.bytes: Control segment size for efficient seeks.
- Partitioning: Use
aggregate_id as the key → events for same aggregate go to same partition (ordering guaranteed per partition).
- Idempotent Producer: Enable
enable.idempotence=true to avoid duplicates from producer retries.
C. Event Consumers
- Idempotency:
- Store processed
event_ids in a deduplication table:
CREATE TABLE processed_events (
event_id UUID PRIMARY KEY,
processed_at TIMESTAMP NOT NULL DEFAULT NOW(),
ttl TIMESTAMP GENERATED ALWAYS AS (processed_at + INTERVAL '90 days') STORED
);
CREATE INDEX idx_processed_events_ttl ON processed_events(ttl);
- Consumer Workflow:
- Poll events in order per partition (Kafka guarantees this).
- Check idempotency:
SELECT 1 FROM processed_events WHERE event_id = ?.
- If new, process event within a transaction (update state + insert
event_id).
- Commit offset only after transaction succeeds.
- Exactly-Once Processing:
- Use Kafka transactions (if supported) to atomically write to DB + commit offset.
- Fallback: Manual idempotency check + offset commit after DB transaction.
D. Replay Mechanism
- Tools:
- Kafka Consumer Groups: Reset offsets via
kafka-consumer-groups --reset-offsets.
- Dedicated Replay Service:
- Reads from a retained topic.
- Optionally filters by
aggregate_id or time range.
- Writes to a replay topic (same schema) for isolated testing.
- Snapshot + Replay (for large state):
- Periodically take state snapshots (e.g., every 1k events).
- Replay only events after the latest snapshot.
2. Ordering Guarantees
Key Design Points
- Partitioning: All events for an
aggregate_id must go to the same Kafka partition.
- Producer: Outbox Publisher must publish events in order of
created_at for same aggregate_id.
- Query:
SELECT * FROM outbox WHERE published_at IS NULL ORDER BY aggregate_id, created_at.
- Consumer: Single-threaded processing per partition (Kafka ensures one consumer per partition in a group).
- No Cross-Aggregate Ordering: Ordering is scoped to
aggregate_id, not globally.
3. Failure Handling & Retries
Producer Side (Outbox)
- Retry Policy: Exponential backoff (e.g., 1s, 2s, 4s...) up to N attempts.
- DLQ (Dead Letter Queue):
- After max retries, move event to
outbox_dlq table or Kafka topic.dlq.
- Alerting on DLQ growth.
- Monitoring: Outbox lag (
unpublished count), publish latency, error rates.
Consumer Side
- Poison Pill Handling: After N failures, move event to
consumer_dlq (Kafka topic) and skip.
- Rebalancing: During consumer rebalance, partitions are revoked/assigned. Ensure:
- Commit offsets before partition revocation.
- Use
ConsumerRebalanceListener to pause/resume processing.
4. Replay Strategies
| Scenario | Approach |
|---|
| Full Replay | Reset consumer group offset to earliest. |
| Partial Replay | Use kafka-consumer-groups --to-offset or --to-datetime. |
| Aggregate Replay | Replay service filters by aggregate_id (reads from retained topic). |
| Time-Based Replay | Seek to timestamp (--to-datetime). |
| Corrupted State Repair | 1. Stop consumer.2. Restore DB from backup.3. Reset offset + replay. |
5. Security & Schema Management
- Schema Registry (e.g., Confluent Schema Registry):
- Avro/Protobuf schemas with evolution rules (backward/forward compatible).
- Schema stored in event headers or separate topic.
- Encryption: TLS for Kafka, encrypted payloads (optional).
- Authorization: Kafka ACLs per service/topic.
6. Monitoring & Alerting
| Metric | Tool | Alert |
|---|
| Outbox unpublished count | DB query / Prometheus | > 1000 for > 5m |
| Consumer lag (per partition) | Kafka Lag Exporter | > 1000 events |
| DLQ size | Kafka / DB | Any event in DLQ |
| Publish latency (p50, p99) | Custom metrics | p99 > 5s |
| Duplicate event rate | Processed events table | > 0.1% |
7. Code Sketch: Outbox Publisher
public class OutboxPublisher {
private static final int BATCH_SIZE = 100;
public void publishBatch() {
List<Outbox> batch = outboxRepo.findUnpublishedOrdered(BATCH_SIZE);
if (batch.isEmpty()) return;
for (Outbox event : batch) {
try {
kafkaTemplate.send(
event.getTopic(),
event.getAggregateId(), // key for ordering
event.getEventId(),
event.getPayload()
).get(10, TimeUnit.SECONDS); // sync wait
event.setPublishedAt(Instant.now());
} catch (Exception e) {
event.setRetryCount(event.getRetryCount() + 1);
event.setErrorMessage(e.getMessage());
if (event.getRetryCount() >= MAX_RETRIES) {
moveToDlq(event);
}
}
}
outboxRepo.saveAll(batch);
}
}
8. Trade-offs & Considerations
| Pattern | Pros | Cons |
|---|
| Outbox | No 2PC, DB-broker decoupling. | Extra table, polling latency. |
| Idempotent Consumer | Safe retries, no duplicates. | Storage overhead for event_ids. |
| Ordering Keys | Per-aggregate consistency. | Hot partitions if skewed keys. |
| Replays | Full recovery, debugging. | Storage costs, reprocessing load. |
9. Evolution Path
- Phase 1: Implement outbox + idempotent consumers + ordering keys.
- Phase 2: Add DLQs, monitoring, replay tools.
- Phase 3: Introduce compacted topics for latest state (if needed).
- Phase 4: Implement schema registry, multi-region replication.
This baseline provides a robust, production-ready foundation. Adjust based on throughput needs (e.g., batch publishing, parallel outbox publishers per shard) and compliance (data retention policies). Always test failure scenarios (network partitions, broker downtime) in staging.