A pluggable event bus built on Kafka for reliable async communication between microservices — with schema validation at publish time, per-topic dead-letter queuing, exponential backoff retry, and Prometheus observability.
At Intuit I consumed and produced Kafka events as part of the Sales & Invoicing platform. I wanted to understand the framework layer — how schema enforcement, DLQ routing, and retry policies actually work under the hood. This is that implementation.
┌──────────────────┐ ┌──────────────────────────┐ ┌─────────────────────┐
│ │ │ │ │ │
│ order-service │ publish │ Kafka: orders topic │ consume │ inventory-service │
│ POST /orders │ ───────► │ (3 partitions) │ ───────► │ @KafkaListener │
│ │ │ │ │ AbstractSubscriber │
└──────────────────┘ └──────────────────────────┘ └──────────┬──────────┘
│
┌──────────────────────────┐ │ retry (1s→2s→4s)
│ │ ◄─────────────────┤ or
│ Kafka: orders.DLQ topic │ │ hard failure
│ (1 partition) │ │
└──────────────────────────┘ │
▼
┌──────────────────────────────────────────────────────────────────────────────────────────┐
│ Prometheus + Grafana │
│ Scrapes /actuator/prometheus on both services │
│ Metrics: eventbus_publish_total, eventbus_retry_total, eventbus_dlq_total, │
│ kafka_consumer_lag_records │
└──────────────────────────────────────────────────────────────────────────────────────────┘
EventPublisher runs Bean Validation on every event before calling KafkaTemplate.send(). If required fields (eventId, correlationId, eventType, timestamp) are missing, it throws EventSchemaViolationException and the message never enters Kafka.
Why this matters: Kafka is an append-only log. A malformed message you write is there permanently — you cannot delete it without log compaction workarounds. Validating at the producer prevents poisoned messages from entering the pipeline at all.
In production: this validation layer would delegate to a Confluent Schema Registry with Avro or Protobuf for schema evolution with backward/forward compatibility guarantees.
Failed messages route to orders.DLQ, not a shared DLQ topic.
Why this matters: A global DLQ creates blast radius — an order failure flood would drown unrelated payment failures in the same queue. Different DLQs allow targeted replay by the team that owns each topic, without reprocessing unrelated failures.
DLQ messages carry diagnostic headers: X-DLQ-Reason, X-DLQ-OriginalTopic, X-DLQ-Timestamp plus all original headers, so failures are fully debuggable without touching the application.
correlationId is written into the JSON event body AND as a X-Correlation-Id Kafka header.
Why this matters: Kafka headers can be read without deserializing the payload — critical for log aggregation tools (Datadog, Jaeger, OpenTelemetry) that need to trace a request across services without understanding domain-specific event schemas.
AbstractEventSubscriber uses @Retryable with maxAttempts=4 and delay=1000ms, multiplier=2.0 — waits 1s, 2s, 4s between attempts before routing to DLQ.
notRecoverable=IllegalArgumentException.class allows hard failures (malformed data that can never succeed) to bypass all retries and go directly to DLQ.
Why this matters: @Retryable retries in-memory without re-fetching from Kafka. This is correct for transient failures (DB timeouts, downstream unavailability). For Kafka-native retry you'd use SeekToCurrentErrorHandler with backoff — same pattern, different scope.
The producer is configured with enable.idempotence=true and acks=all.
Why this matters: Without idempotence, if the broker ACKs a message but the network drops before the producer receives the ACK, the producer retries and creates a duplicate. With idempotence, each message gets a sequence number — the broker deduplicates within a producer session. This is the strongest per-partition delivery guarantee short of full transactional producers.
OrderService uses customerId as the Kafka partition key.
Why this matters: All events for the same customer land on the same partition, preserving per-customer event ordering. If you used a random key, two orders from the same customer could be consumed out of sequence.
Prerequisites: Docker Desktop, Java 17+, Maven 3.8+
# 1. Start Kafka, Zookeeper, Prometheus, Grafana
docker compose up -d
# 2. Build all modules (installs event-bus-core to local Maven repo first)
./mvnw clean install -DskipTests
# 3. Run services (two separate terminals)
./mvnw spring-boot:run -pl order-service
./mvnw spring-boot:run -pl inventory-serviceServices are ready when you see:
order-service→Started OrderServiceApplication on port 8081inventory-service→Started InventoryServiceApplication on port 8082
POST /orders — create an order and publish to Kafka
curl -X POST http://localhost:8081/orders \
-H "Content-Type: application/json" \
-d '{
"customerId": "cust-001",
"correlationId": "trace-abc-123",
"totalAmount": 59.99,
"items": [
{"sku": "WIDGET-A", "quantity": 2, "unitPrice": 29.99}
]
}'
# 201 → {"orderId": "...", "status": "published"}
# 400 → missing required fields (Bean Validation)
# 422 → schema validation rejected the eventGET /inventory — current stock levels
curl http://localhost:8082/inventory
# {"WIDGET-A": 98, "WIDGET-B": 50, "GADGET-X": 25}POST /inventory/simulate — toggle failure modes for demo
# Enable soft failure: triggers exponential backoff retries → DLQ after max attempts
curl -X POST http://localhost:8082/inventory/simulate \
-H "Content-Type: application/json" \
-d '{"softFailure": true, "hardFailure": false}'
# Enable hard failure: bypasses retry → immediate DLQ
curl -X POST http://localhost:8082/inventory/simulate \
-H "Content-Type: application/json" \
-d '{"softFailure": false, "hardFailure": true}'
# Reset
curl -X POST http://localhost:8082/inventory/simulate \
-H "Content-Type: application/json" \
-d '{"softFailure": false, "hardFailure": false}'Check DLQ messages:
docker exec kafka kafka-console-consumer \
--bootstrap-server localhost:9092 \
--topic orders.DLQ --from-beginning --max-messages 5Both services expose metrics at /actuator/prometheus, scraped by Prometheus at localhost:9090.
| Metric | Labels | Description |
|---|---|---|
eventbus_publish_total |
topic, eventType |
Events successfully queued for send |
eventbus_publish_failure_total |
topic, eventType |
Kafka send callback failures |
eventbus_consume_total |
topic, eventType, group |
Events picked up by consumer |
eventbus_retry_total |
topic, eventType, group |
Spring Retry attempts triggered |
eventbus_dlq_total |
topic, eventType, group |
Messages routed to DLQ |
kafka_consumer_lag_records |
topic, partition, group |
Consumer lag per partition (auto-exported by Micrometer) |
Grafana is available at http://localhost:3000 (admin/admin). Add Prometheus as a data source at http://prometheus:9090.
# Unit tests only (no Kafka required)
./mvnw test -pl event-bus-core
# All tests including integration tests with embedded Kafka
./mvnw test| Component | Version |
|---|---|
| Java | 17 |
| Spring Boot | 3.2.5 |
| Apache Kafka | 3.1.x (via spring-kafka) |
| Spring Retry | 2.0.5 |
| Micrometer / Prometheus | 1.12.5 |
| Docker | 24+ |
| Lombok | Latest via Spring Boot BOM |
What this demo doesn't include (and what you'd add in production):
- Schema Registry — Confluent Schema Registry with Avro/Protobuf for versioned schema evolution with backward/forward compatibility
- Transactional producers —
isolation.level=read_committedon consumers for true end-to-end exactly-once semantics - Kubernetes deployment — HorizontalPodAutoscaler for inventory-service scaled to match Kafka partition count (3 replicas → 3 consumers, one per partition)
- Kafka Streams — for stateful event processing (joins, windowing, aggregations) beyond simple consume-and-act
- Dead letter replay automation — a replay service that reads
orders.DLQand re-publishes toordersafter the root cause is fixed