Event Sourcing & CQRS · CQRS and Projections
Eventual Consistency in the UI
Keep users from seeing stale data right after they act.
After a command, the read model may lag by milliseconds or seconds. Techniques: return the new state (or version) from the command and render it directly; read-your-writes by waiting until the projection reaches the returned position (with a short timeout); optimistic UI updates; show "processing" states; or query the write model for the user's own fresh data. Choose per screen based on how jarring staleness would be.
Hiding read-model lag
| Technique | How | Trade-off |
|---|---|---|
| Return result from command | Command response includes new state | Simple; only for the acting user |
| Wait for projection position | Poll read model until checkpoint ≥ event position | Small delay; strongly consistent for user |
| Optimistic UI | Update client state immediately | Must roll back on failure |
| Pending state | Show 'processing' until confirmed | Honest; extra UI states |
| Read from write model | Load aggregate for own data | Bypasses read model optimizations |
POST /orders → 202 {"order_id": "ord_1", "position": 918273}
GET /orders/ord_1?min_position=918273
server waits up to 2 s until order_summaries checkpoint ≥ 918273, then responds
Common pitfalls
- Redirecting to a list that doesn't show the just-created item.
- Long blocking waits for projections.
- Ignoring lag metrics for projections.
Key points
- Return state or positions from commands
- Read-your-writes where it matters
- Monitor projection lag
Further reading: Azure Architecture: CQRS pattern
Practice questions
How can a client read its own write in a CQRS system?
Answer
The command returns the event position; the query asks the read side to wait until its checkpoint reaches that position (with a timeout) before answering.
Which metric should you monitor for every projection?
Answer
Projection lag: the difference between the latest event position (or time) and the projection's checkpoint.
Open in the app to mark lessons complete, take notes and track your progress.