Event Driven Architecture
Synchronous calls (REST) couple services. If the Email Service is down, the Registration Service fails. Solution: Events.1. Spring Cloud Stream
An abstraction over message brokers. You write code that produces/consumes messages, and Spring handles the broker details (Kafka or RabbitMQ). Dependency:spring-cloud-starter-stream-rabbit (or kafka).
2. The Functional Style (Spring Boot 3)
No more@EnableBinding. We use java.util.function.
3. Reducing Boilerplate with StreamBridge
For REST-triggered events (e.g., User clicks “Buy”),Supplier is hard to use. Use StreamBridge.
4. Configuration (application.yml)
Map the functions to actual queues/topics.
5. Kafka vs RabbitMQ
| Feature | RabbitMQ | Kafka |
|---|---|---|
| Model | Smart Broker, Dumb Consumer | Dumb Broker, Smart Consumer |
| Use Case | Complex routing, low latency | High throughput, event replay |
| Persistence | Queue based | Log based (Retention) |
- Kafka: High throughput, persistent log. Better for event streaming.
- RabbitMQ: Traditional message broker. Better for task queues.
6. The Dual Write Problem
In Microservices, you often need to:- Update the database (e.g., save order).
- Send an event (e.g., publish “OrderCreated” to Kafka).
7. The Transactional Outbox Pattern (Solution)
Idea: Write the event to the same database transaction as the business data.Implementation
- Create an
Outboxtable.
- Save both Order AND Event in the same transaction.
- A background worker (scheduled task) reads from
outboxand publishes to Kafka, then deletes the row.
Why it Works
- Atomicity: DB write + Outbox write are in one transaction.
- Eventual Consistency: Events are published asynchronously, but guaranteed.
Flow Diagram
8. Dead Letter Queues (DLQ)
What if a consumer keeps failing to process a message (e.g., bad JSON, NPE)? After N retries, move the message to a Dead Letter Queue for manual inspection.orders.order-service.dlq.