In a CQRS architecture with event sourcing, the write model (commands mutate aggregates, append events to an event store) is separated from the read model (projections build denormalized views for queries). Read models achieve eventual consistency by asynchronously processing domain events.
This design focuses on:
Robust refresh/catch-up for projections.
Lag monitoring to detect stale projections.
Alerting on excessive staleness.
Key Assumptions:
Event store: Apache Kafka (topics partitioned by aggregate ID for ordering; compacted for snapshots).
Projections run as stateless services in consumer groups (one group per projection type for independent scaling). They process events in at-least-once semantics with checkpoints.
Applies to read model (idempotent: MERGE SQL or version checks).
Commits offset as checkpoint (stored in Kafka __consumer_offsets or external DB).
Refresh Modes:
Live Tail (normal): Process new events from current offset.
Catch-up (on lag/failure): Replay from last checkpoint to HEAD.
Triggered automatically on consumer rebalance/restart.
Batch size: 1000 events (configurable).
Full Rebuild (rare, admin-triggered): Drop read model, reset offset to 0.
Refresh Flow
code
1. Projection starts/rebalances.
2. Fetch last checkpoint (offset X) from Kafka/DB.
3. Compute lag: HEAD_OFFSET - X.
4. If lag > 0:
a. Replay historical events (X to HEAD) in order.
b. Apply to read model (parallel per partition).
c. Update checkpoint incrementally (every N events).
5. Switch to live tail.
6. Health check: Emit metric `projection_lag_seconds`.
Time Lag: Approximate age of oldest unprocessed event (using event timestamp).
Processing Rate: Events/sec processed.
Global Head Tracker:
Lightweight service publishing current_head_offset metric to Prometheus every 10s.
Computed via Kafka admin API: describeLogEndOffset().
Monitor Flow
code
1. Fetch HEAD offset from Kafka.
2. For each projection:
a. Fetch checkpoints (Kafka offsets API or projection DB table: `{projection_id, partition, offset, updated_at}`).
b. Lag = HEAD - max(checkpoint_offsets).
c. Time_lag = now() - min(event_timestamps in lag).
3. Export to Prometheus:
- `cqrs_projection_lag_events{projection="orders", partition="0"} 1500`
- `cqrs_projection_lag_seconds{projection="orders"} 300`
- `cqrs_projection_is_stale{projection="orders"} 1` (if lag > threshold)
4. Grafana Dashboard: Lag heatmaps, throughput graphs.
Integrations: Webhooks to auto-scale projection replicas or trigger catch-up jobs.
Thresholds (Tunable):
Metric
Warning
Critical
Rationale
Event Lag
1k
10k
Business tolerance (e.g., orders)
Time Lag
1min
5min
User-facing staleness
Processing Rate
<10/s
<1/s
Detect slowdowns
Considerations & Best Practices
Fault Tolerance:
Idempotent projections: Use event aggregate ID + version.
Dead Letter Queue (DLQ) for poison events.
Snapshots: Periodically snapshot aggregates to skip replay.
Ordering & Consistency:
Kafka partitioning by aggregate ID.
Exactly-once via transactional outbox (if needed).
Performance:
Parallelism: One consumer thread/partition.
Backpressure: Throttle on read DB overload.
Warm-up: Pre-populate caches during catch-up.
Testing:
Chaos: Inject lag/failures (e.g., Chaos Mesh).
Load: Replay 1M events, measure catch-up time.
Deployment:
Helm charts for projections/monitors.
CI/CD: Blue-green for projection versions (dual-write during migration).
This design ensures read models stay fresh (99.9% <1min lag in practice) while handling failures gracefully. For implementation in a specific stack (e.g., Axon Framework, Eventuate), adaptations are straightforward. Questions on details?