Exercise — CQRS: build a read projection kept in sync with the write side.
Topic: microservices, Data Management. Level: Hard.
Answer
Commands mutate the write DB and emit events; a projector consumes those events to (re)build a denormalized read table for fast queries. Make the projector idempotent (handle duplicate events) and track the last processed offset so it can resume. Queries hit only the read table.
```java
@Component
class OrderSummaryProjector {
@KafkaListener(topics = "orders", groupId = "order-summary")
void on(OrderEvent e) {
switch (e) {
case OrderPlaced p -> readDb.insertIfAbsent(p.id(), p.total(), "PLACED");
case OrderShipped s -> readDb.updateStatus(s.id(), "SHIPPED");
case OrderCancelled c-> readDb.updateStatus(c.id(), "CANCELLED");
default -> {}
}
}
}
// Query path is a trivial single-table read:
List<OrderSummary> recent() { return readDb.findTop50ByOrderByCreatedDesc(); }
```