Event-Driven Architecture with Exactly-Once Semantics
This design achieves exactly-once semantics in an event-driven system using microservices, a relational database (e.g., PostgreSQL), Apache Kafka as the event broker, and idempotent consumers. It incorporates:
- Idempotency: Consumer-side tracking of processed events.
- Deduplication: Kafka idempotent producers + consumer idempotency store.
- Outbox pattern: Atomic DB writes + event publishing.
- Retries/DLQs: Exponential backoff retries with dead letter queues.
- Observability: Structured logging, metrics, and distributed tracing.
High-Level Architecture Diagram (Text-Based)
[Service A (Producer)]
|
| 1. Business Tx: INSERT business_data, INSERT outbox_event (atomic)
v
[Shared DB] <--- 2a. Debezium CDC (or Poller) reads outbox ---> 2b. Kafka Transactional Producer (idempotent)
| |
| v
| 3. UPDATE outbox_event.processed = true ---------------------------- [Kafka Topic: orders.events]
| / | \
| / | \
v v | v
[DB_A (Business State)] [Service B] [Service C] [DLQ Topic]
(Metrics/Logs/Trace) ^ (Consumer) (Replay)
| Idempotency Store (Redis/DB)
| - Check event_id
| - Process if new (idempotent)
| - Retries: Exp backoff (3x)
| - DLQ after max retries
|
[DB_B (Business State)]
Core Components and Flows
1. Producers (e.g., Service A - Order Service)
- Outbox Pattern for Atomicity:
- When business logic requires a DB change + event emit (e.g.,
OrderCreated):
BEGIN;
INSERT INTO orders (id, status) VALUES ('order-123', 'created');
INSERT INTO outbox_events (id, aggregate_id, type, payload, created_at)
VALUES (uuid_generate_v4(), 'order-123', 'OrderCreated', '{"id": "order-123"}', NOW());
COMMIT;
- Ensures exactly-once delivery guarantee: Event is only published if DB commit succeeds.
- Event Publishing:
- Debezium CDC (Change Data Capture) monitors
outbox_events table for new inserts.
- Config: Capture only
INSERT on outbox_events where processed = false.
- CDC connector acts as idempotent Kafka producer:
- Kafka producer config:
enable.idempotence=true, transactional.id=true.
- Publishes to topic with partition key =
aggregate_id (for ordering).
- After publish: Updates
outbox_events.processed = true in a Kafka transaction.
- Deduplication: Kafka's idempotent producer assigns Producer ID (PID) + sequence numbers; duplicates auto-dropped.
- Fallback: Custom poller (e.g., Spring Boot scheduler) if CDC unavailable.
2. Message Broker: Apache Kafka
3. Consumers (e.g., Service B - Inventory Service)
- Processing Flow (Exactly-Once via Idempotency):
- Consume event from Kafka (
event_id, aggregate_id, payload).
- Idempotency Check:
- Process Idempotently:
- Business logic: e.g.,
UPDATE inventory SET stock = stock - 1 WHERE product_id = ? (idempotent if using version/ETag).
- Insert:
INSERT INTO idempotency_log (event_id, service, processed_at, trace_id) VALUES (?, 'inventory', NOW(), ?);.
- Commit Offset Transactionally:
- Use Kafka transactions:
producer.initTransactions(), process, producer.commitTransaction() (includes idempotency insert).
- Retries & DLQs:
| Attempt | Delay | Action |
|---|
| 1 | 1s | Retry |
| 2 | 5s | Retry |
| 3 | 30s | Retry |
| 4+ | N/A | Send to orders.dlq with metadata (original event + error + attempt count). |
- Config: Kafka consumer
enable.auto.commit=false; manual offset commit only on success.
- DLQ Handler: Separate consumer replays/alerts (e.g., notify ops via PagerDuty).
- Consumer Group:
inventory-processor-v1 for scalability (multiple instances).
4. Data Stores
| Store | Purpose | Tech |
|---|
| Business DB | Orders/Inventory state. | Postgres |
| Outbox | Pending events. | Postgres (same DB) |
| Idempotency | Track processed event_ids. | Redis (TTL=7d) + Postgres replica |
- Schema for idempotency:
CREATE TABLE idempotency_log (
event_id UUID PRIMARY KEY,
service VARCHAR(50),
aggregate_id VARCHAR(100),
processed_at TIMESTAMP,
trace_id VARCHAR(100)
);
INDEX on (service, aggregate_id);
Exactly-Once Guarantees
- Producer: Outbox + transactional publish → No lost events, no duplicates (idempotent producer).
- Kafka: At-least-once delivery + idempotent semantics.
- Consumer: Idempotency store + transactional offset commit → Duplicates ignored, no reprocessing.
- End-to-End: Combines to exactly-once (idempotent processing even on retries/failovers).
Observability
- Logging: Structured JSON logs (e.g., via SLF4J + Logback).
- Levels: INFO (processed), WARN (retry), ERROR (DLQ).
- Include
event_id, trace_id, aggregate_id.
- Metrics (Prometheus + Grafana):
| Metric | Type | Description |
|---|
events_processed_total | Counter | By service/topic/success. |
processing_latency_ms | Histogram | End-to-end latency. |
retry_attempts_total | Counter | By reason. |
dlq_events_total | Counter | Failed events. |
idempotency_hits_total | Counter | Duplicate skips. |
- Distributed Tracing (OpenTelemetry + Jaeger):
- Producer: Span
outbox-publish → Kafka.
- Consumer: Span
process-event → Idempotency check → Business logic.
- Propagate
traceparent via Kafka headers.
- Dashboards/Alerts:
- Grafana: Error rate >5%, DLQ size >100.
- Alertmanager: High retry rates.
Implementation Notes
- Tech Stack Example: Java/Spring Boot (Kafka Streams/Kafka Clients), Debezium, Redis, Postgres.
- Scaling: Kafka partitions scale consumers; shard idempotency by
aggregate_id.
- Testing:
- Unit: Mock idempotency store.
- Integration: Testcontainers (Kafka + Postgres + Debezium).
- Chaos: Kill consumer → Verify no duplicates.
- Trade-offs:
| Pro | Con |
|---|
| Strong guarantees | Latency (idempotency DB lookup). |
| Fault-tolerant | Storage overhead (outbox/idempotency). |
This design is production-ready, battle-tested in e-commerce/payment systems. Extend with event sourcing (Kafka as source of truth) if needed.