Event-Driven Architecture Baseline Design
This design provides a robust, reliable baseline for event-driven systems using the outbox pattern, idempotent consumers, ordering keys, and replay capabilities. It assumes:
- Services maintain their own relational databases (e.g., PostgreSQL).
- Message broker: Apache Kafka (for durability, partitioning, ordering, and native replays).
- Key goals: Exactly-once semantics (EoS), at-least-once delivery with idempotency, ordered processing per entity, and easy reprocessing.
High-Level Architecture
[Service A] [Service B] [Kafka Cluster] [Service C (Consumer)]
| | | |
| 1. Tx: Update DB | | |
| + Insert Outbox | | |
+---------------------+ | |
| 2. Outbox Poller | | |
| (Dequeue & Pub) +---------------------+ |
| | 3. Publish Events | |
| | (w/ Ordering Key)| |
+---------------------+ | |
| | |
| v |
| [Topic: user-events] |
| Partitions keyed by user_id |
| | |
| | 4. Consume (Idempotent) |
| +------------+-------------+
| |
| | 5. Replay: Reset offsets
| | or use from specific offset
+----------------------------------+
Flow Summary
- Producer Transaction (Outbox): Atomic DB update + event insert.
- Relay/Poll: Dequeue outbox → publish to Kafka.
- Publish: Events keyed for ordering.
- Consume: Idempotent processing.
- Replay: Seek Kafka offsets for reprocessing.
1. Outbox Pattern (Reliable Publishing)
Purpose: Decouples DB transactions from external brokers, ensuring no lost events even on broker downtime.
Implementation:
- Outbox Table (per service DB):
CREATE TABLE event_outbox (
id UUID PRIMARY KEY,
aggregate_id UUID NOT NULL, -- For ordering key
aggregate_type VARCHAR(50) NOT NULL,
event_type VARCHAR(50) NOT NULL,
payload JSONB NOT NULL,
metadata JSONB, -- e.g., { "trace_id": "..." }
created_at TIMESTAMP DEFAULT NOW(),
published_at TIMESTAMP,
published_attempts INT DEFAULT 0,
UNIQUE(aggregate_id, aggregate_type, event_type, sequence_no) -- Prevent dupes
);
- Transactional Insert (in service code):
BEGIN TRANSACTION;
UPDATE users SET balance = balance - 100 WHERE id = ?;
INSERT INTO event_outbox (id, aggregate_id, event_type, payload)
VALUES (uuid(), user_id, 'UserDebited', '{"amount": 100}');
COMMIT;
- Outbox Relay/Poller (background job, e.g., via Debezium CDC or cron/Kafka Connect):
- Poll
WHERE published_at IS NULL AND published_attempts < 5.
- Publish to Kafka (with
aggregate_id as key).
- On success:
UPDATE SET published_at = NOW(), published_attempts = ....
- Retries: Exponential backoff; DLQ on failure.
- Idempotency in Outbox: Use sequence numbers per aggregate to dedupe.
Benefits: ACID compliance, no dual-writes.
2. Idempotent Consumers
Purpose: Handles at-least-once delivery (duplicates from retries/crashes) without side-effects.
Implementation:
- Event Schema (Avro/JSON with schema registry):
{
"event_id": "uuid-v4",
"aggregate_id": "user-123",
"aggregate_type": "User",
"event_type": "UserDebited",
"sequence_no": 42, // Per-aggregate monotonic counter
"payload": { ... },
"timestamp": "2023-..."
}
- Consumer State (in consumer's DB/Redis):
CREATE TABLE processed_events (
event_id UUID PRIMARY KEY,
aggregate_id UUID NOT NULL,
sequence_no BIGINT NOT NULL,
processed_at TIMESTAMP
);
- Consumer Logic (e.g., Kafka Streams or ksqlDB):
consume(event):
IF EXISTS processed_events(event.event_id):
ACK; RETURN; // Idempotent skip
process(event); // Business logic (idempotent ops like UPSERT)
INSERT processed_events(event); // Or Redis SETNX
COMMIT;
- Cleanup: TTL on processed_events (e.g., 7 days) or sliding window.
Benefits: EoS without broker transactions (e.g., Kafka idempotent producers + transactions optional).
3. Ordering Keys
Purpose: Guarantees in-order processing per business entity (e.g., all events for user-123 in sequence).
Implementation:
Trade-offs: Single-threaded per partition; use multiple partitions for parallelism across aggregates.
4. Replays
Purpose: Reprocess historical events (e.g., new service onboarding, bug fixes, schema evolution).
Implementation:
- Kafka Native:
- Consumers set
auto.offset.reset=earliest or seekToBeginning().
- Replay from timestamp/offset:
consumer.seekToTimestamp(timestamp).
- Tools:
| Use Case | Method |
|---|
| Full replay | Reset group offsets to 0 (kafka-consumer-groups.sh) |
| Partial (post-X) | Seek to offset/timestamp |
| Selective | MirrorMaker2 or custom replay topic |
| Schema changes | Use Schema Registry + backwards-compatible schemas |
- Safe Replay Process:
- Backup consumer offsets.
- Scale consumers to 0 → Replay → Scale up.
- Idempotency ensures no duplicates.
- Dual-write to temp table for validation.
- Compaction: Use log-compacted topics for state snapshots (e.g., Kafka Streams changelog).
Monitoring: Prometheus + Grafana for lag, throughput.
Integration & Best Practices
- End-to-End EoS: Outbox (atomicity) + Idempotent Producer (Kafka
enable.idempotence=true) + Idempotent Consumer.
- Error Handling:
| Error Type | Action |
|---|
| Transient | Retry (dead-letter on fail) |
| Permanent | DLQ topic |
| Ordering Break | Pause partition |
- Observability:
- Trace IDs across outbox → Kafka → consumer.
- Metrics: Outbox backlog, consumer lag, dedupe rate.
- Scaling:
- Horizontal: More Kafka partitions/services.
- Vertical: Tune poll batch sizes.
- Tech Stack Example:
| Component | Tools |
|---|
| DB | Postgres |
| Broker | Kafka + Schema Registry |
| Relay | Debezium/Kafka Connect |
| Consumers | Spring Kafka/AutoOffset |
| Monitoring | Prometheus + Grafana |
Benefits & Trade-offs
| Benefits | Trade-offs |
|---|
| Reliable, ordered, replayable | Added latency (outbox poll) |
| EoS w/o distributed txns | Storage overhead (outbox/Kafka) |
| Fault-tolerant | Operational complexity |
This baseline scales to high-volume systems (e.g., 1M+ events/sec). Customize for specifics like non-relational DBs (use change streams) or brokers (RabbitMQ + plugins). Questions?