Intermediate LevelSoftware Engineering Principles
How do Projections project Event Sourced data streams into fast Read Models in CQRS?
❓ Interview Prompt: Explain Projections, consuming event streams, building optimized SQL/NoSQL read views, and handling eventual consistency lag.
In a CQRS + Event Sourcing system, Projections listen to the stream of domain events and update specialized Read Models optimized for query performance:
How Projections Work:
•
Event: 'OrderPlaced { orderId: '101', customerName: 'Alice', total: 50 }'.
•
Projection Function: Intercepts event and inserts a formatted JSON row into an ElasticSearch index or PostgreSQL read table.
•
Note: Read models are eventually consistent with the write event store.
Code Implementation Example
typescript
class OrderReadModelProjection {
async onOrderPlaced(event: OrderPlacedEvent) {
// Project event payload into flat JSON view in Redis / ElasticSearch
await searchClient.index({
index: 'order_summary_views',
id: event.orderId,
body: { id: event.orderId, customer: event.customerName, total: event.total }
});
}
}💡Projecting domain events into a fast read model index.
🎯 Interview Key Takeaway
Use Projections to transform immutable event streams into optimized, queryable read model views.
#Projections#CQRS#Event Sourcing#Intermediate
Back to all Software Engineering Principles Questions→