We are designing a CQRS read model refresh process with eventual consistency monitors and alerting for stale projections.
Steps:
We have a write model (command side) that updates the state of the application and produces events.
The read model (query side) is built from these events. It is eventually consistent, meaning there is a delay between the event generation and the read model update.
We need to monitor the read model for staleness (i.e., the read model is too far behind the write model) and set up alerts.
How to approach:
We can have a process that periodically:
a. Checks the current state of the read model (e.g., the latest event number or timestamp that has been processed).
b. Compares it with the write model's latest event (or a high-water mark).
c. If the difference is beyond a threshold, trigger an alert.
However, note that in CQRS, the write model might not have a single high-water mark because events are stored in an event store.
We can use the event store's last committed event number (or timestamp) as the high-water mark.
Alternatively, if we are using a message broker (like Kafka) we can use the offset of the latest message in the topic that the read model is consuming from.
But note: the read model might be built from multiple event streams (if using domain events from multiple aggregates). In that case, we might need to track the latest event across all streams.
However, for simplicity, let's assume we are using a single event stream (or a single topic) for all events that affect the read model.
Steps for the monitor:
Determine the current high-water mark (HWM) from the write side. This could be:
The latest event number in the event store.
The latest offset in the Kafka topic (if using Kafka).
Determine the current low-water mark (LWM) of the read model, i.e., the event number or offset up to which the read model has processed.
Calculate the lag: HWM - LWM.
If the lag is above a configured threshold (in terms of event count or time), then alert.
But note: the read model might be updated in batches, so we might also want to monitor the time since the last update.
We can have two metrics:
Event lag: number of events not processed.
Time lag: time since the last update (if we have timestamps on events).
However, if events are not coming in (the system is idle), then the lag might be zero but the read model might be stale because no new events are being produced.
So we need to consider:
a. If there are new events being produced, then we care about the event lag.
b. If no new events are being produced, then we don't want to alert just because the read model is not updating (because there's nothing to update).
How to distinguish?
We can check if the HWM has advanced in the last X minutes. If the HWM hasn't advanced, then we don't care about the lag. But if the HWM has advanced and the LWM hasn't, then we have a problem.
Alternatively, we can set up two alerts:
Alert 1: Event lag threshold (e.g., more than 1000 events behind) and the HWM has advanced in the last 5 minutes (so there are new events).
Alert 2: Time lag threshold (e.g., the read model hasn't updated in the last 10 minutes) and the HWM has advanced in the last 10 minutes (so there are new events that should have been processed).
However, note that the read model might be updated in batches and might not update for a while even if events are coming in. So we need to set thresholds accordingly.
Implementation:
Let's assume we are using an event store that assigns an increasing sequence number to each event. We can store the last processed sequence number in the read model's database (or in a separate table for monitoring).
// Check if there are new events in the last N minutes?
// We can also store the timestamp of the latest event in the event store? Or we can check if the high_water_mark has increased since last check.
// Alternatively, we can have two thresholds:
// - max_event_lag: if lag > max_event_lag and we have new events (HWM increased) then alert.
// - max_time_lag: if current_time - last_update_time_of_read_model > max_time_lag and we have new events (HWM increased) then alert.
But note: the read model might not have a last_update_time. We can record the time when we last updated the low_water_mark.
Alternatively, we can compute the time lag by looking at the timestamp of the event at the low_water_mark and compare to the current time? But that might not be accurate if the event at the low_water_mark is old and new events are coming in.
Let's think: we want to know if the read model is up to date with the events that have been published.
So we can do:
if (high_water_mark > low_water_mark) {
// There are unprocessed events.
if (lag > max_event_lag) {
trigger_alert("Event lag too high: " + lag + " events behind");
}
code
// Also, we can check the time of the latest event (at high_water_mark) and see how long it has been since that event was produced and the read model hasn't processed it?
// But note: the read model might be processing but slow, so we don't want to alert on every event if the processing is slow but steady.
// Alternatively, we can check the time since the last time the read model updated (i.e., when the low_water_mark was updated). If the read model hasn't updated in the last N minutes and there are unprocessed events, then alert.
last_update_time = get_last_update_time_of_read_model() // This could be stored in a separate table or we can use the timestamp of the event at low_water_mark? But note: the event at low_water_mark might be old and the read model might have updated since then with a newer event? Actually, the low_water_mark is the last processed event, so we can store the time when we processed that event.
if (current_time - last_update_time > max_time_lag) {
trigger_alert("Read model hasn't updated in " + (current_time - last_update_time) + " seconds");
}
}
But note: if the event stream is idle (no new events) then we don't want to alert. So we need to know if there are new events.
How to know if there are new events? We can compare the current high_water_mark with the high_water_mark from the last check. If it has increased, then there are new events.
So we can store the previous high_water_mark and compare.
previous_hwm = get_previous_high_water_mark() // stored from last run
if (current_hwm > previous_hwm) {
// There are new events since last check.
if (current_hwm - current_lwm > max_event_lag) {
trigger_alert("Event lag too high: " + (current_hwm - current_lwm) + " events behind");
}
// Check time lag: we need the last update time of the read model.
last_update_time = get_last_update_time_of_read_model()
if (current_time - last_update_time > max_time_lag) {
trigger_alert("Read model hasn't updated in " + (current_time - last_update_time) + " seconds while new events are available");
}
}
// Update the previous_hwm for next run.
store_previous_high_water_mark(current_hwm)
However, note that the read model might be updated multiple times between our monitor runs, so the last_update_time might be recent even if the current_lwm is still low? Actually, the last_update_time should be updated every time the read model processes an event (or a batch). So if the read model is processing, then the last_update_time will be recent.
But if the read model is stuck, then the last_update_time will be old.
So the above checks seem reasonable.
But what if the event store does not have a sequence number? Then we might use timestamps. However, timestamps might not be strictly increasing (clock skew) and might not be unique. So sequence numbers are better.
If we are using Kafka, we can use the offset and partition. But note: the read model might be consuming from multiple partitions. Then we need to track the lag per partition and then aggregate? Or we can use the total lag across all partitions? But note: if one partition is stuck, then the entire read model might be stale.
So in the case of multiple partitions, we might want to monitor the lag per partition and alert if any partition has a lag above a threshold.
For simplicity, let's assume we are using a single partition or we are using an event store that gives a global sequence number.
If we are using Kafka with multiple partitions, we can:
code
For each partition:
current_offset = get_latest_offset_in_partition(partition)
consumer_offset = get_consumer_offset_for_partition(partition)
lag = current_offset - consumer_offset
if (lag > max_partition_lag) and (current_offset has increased since last check) then alert for that partition.
But note: the read model might be using a consumer group, so we can get the consumer offset for each partition.
Alternatively, we can use Kafka's consumer lag metrics (like the ones provided by Kafka itself or by tools like Burrow). But we are designing our own.
Since the problem says "design a CQRS read model refresh process", we are focusing on the general case.
Let's stick to a single sequence number for simplicity.
Steps for the monitor:
We'll run this monitor periodically (every minute, for example).
We need to store:
- The previous high_water_mark (from the last run) to detect if there are new events.
- The last update time of the read model (when we last updated the low_water_mark).
But note: the read model might update the low_water_mark and the last update time as part of its normal processing. So we need to read that from the read model's database.
Alternatively, we can have a separate table for monitoring that we update every time the read model processes an event (or batch). But that would add overhead to the read model.
Instead, we can have the monitor read the read model's database to get the last processed event's sequence number and the time when that event was processed.
However, the read model might not store the processing time. So we might need to store it.
Proposed schema for the read model's metadata table:
code
Table: read_model_metadata
id: primary key (maybe a single row for the entire read model, or one row per event type if multiple)
last_processed_sequence_number: bigint
last_processed_time: timestamp
Then the monitor can:
code
SELECT last_processed_sequence_number, last_processed_time FROM read_model_metadata WHERE id = 1;
And then compare with the event store's latest sequence number.
But note: the event store might have events for multiple aggregates, and the read model might process them in order? Usually, the event store guarantees order per aggregate, but not globally. However, if we are using a global sequence number (like in some event stores) then we can use that.
If we don't have a global sequence number, we might need to use a timestamp. But then we have to worry about clock skew.
Alternatively, we can use the event's version (which is per aggregate) but then we cannot compare across aggregates.
So it's better to have a global sequence number. If the event store doesn't provide one, we can assign one at the time of appending events (like a monotonically increasing number). But that might be tricky in a distributed system.
Given the complexity, let's assume we have a global sequence number.
Steps:
Monitor process (every N minutes):
code
1. Read the current high_water_mark (latest global sequence number) from the event store.
2. Read the current low_water_mark (last_processed_sequence_number) and last_processed_time from the read_model_metadata.
3. Read the previous_high_water_mark from the monitor's state (stored in a file or database).
4. If current_hwm > previous_hwm:
a. Compute event_lag = current_hwm - current_lwm.
b. If event_lag > max_event_lag, alert.
c. Compute time_since_last_update = current_time - last_processed_time.
d. If time_since_last_update > max_time_lag, alert.
5. Update the previous_water_mark to current_hwm for the next run.
But note: what if the read model is updated between our monitor runs? Then the last_processed_time and last_processed_sequence_number will be updated by the read model, so we don't need to update them in the monitor.
Also, we might want to have a way to reset the alert if the lag goes back to normal. So we can have a "recovery" condition.
We can also have:
code
if (event_lag <= max_event_lag and time_since_last_update <= max_time_lag) then clear_alert()
But note: we might have two separate alerts (one for event lag and one for time lag). We might want to clear each when the condition is resolved.
Alternatively, we can have a single alert that is triggered when either condition is met and cleared when both are okay.
However, for operational clarity, we might want two separate alerts.
Let's have two alerts:
code
Alert 1: Event lag too high (if event_lag > max_event_lag and there are new events)
Alert 2: Read model update too old (if time_since_last_update > max_time_lag and there are new events)
And we clear each independently.
But note: if there are no new events, then we don't trigger either alert even if the read model is stale? Actually, if there are no new events, then the read model being stale is not a problem because there's nothing to update. So we only care when there are new events.
How to know if there are new events? We compare current_hwm and previous_hwm. If current_hwm > previous_hwm, then there are new events.
But what if the event store is idle for a long time and then we get a burst of events? Then the read model might fall behind. We want to alert then.
So the condition for alerting is:
code
condition_new_events = (current_hwm > previous_hwm)
condition_event_lag = (event_lag > max_event_lag)
condition_time_lag = (time_since_last_update > max_time_lag)
if (condition_new_events and condition_event_lag) -> trigger event_lag_alert
if (condition_new_events and condition_time_lag) -> trigger time_lag_alert
And if (not condition_event_lag) then clear event_lag_alert.
not condition_time_lag then clear time_lag_alert.
But note: the condition_new_events might be true for one run and then false the next (if no new events). Then we might clear the alerts even if the read model is still stale? But if there are no new events, then the read model being stale is not a problem because there's nothing to process. However, if the read model is so stale that even old events are not processed, then we might want to alert? But that would be captured by the time_lag condition because if the read model hasn't updated in a long time, then time_since_last_update will be large, and if there are new events (condition_new_events) then we alert. But if there are no new events, condition_new_events is false, so we don't alert.
However, what if the read model is stuck and never processes events, even old ones? Then we might not have an alert because there are no new events? But if the read model is stuck, then the last_processed_time will be old and if we ever get new events, we will alert. But if we never get new events, we won't know the read model is stuck? That might be acceptable because if there are no new events, the read model being stuck doesn't affect the system? Actually, it does because if there are no new events, then the read model is up to date (because there's nothing new). But if the read model is stuck and there are old events that haven't been processed, then the read model is incomplete. However, in an eventually consistent system, we assume that all events will eventually be processed. So if the read model is stuck, then it's a problem even if there are no new events? Because it means the system is not making progress.
So we might want to alert if the read model hasn't updated in a long time, regardless of whether there are new events? But then we might get false positives if the system is idle.
Let's think: the read model should be processing events as they come. If the system is idle (no new events) then the read model should be up to date (i.e., it has processed all events). But if it hasn't processed all events (even old ones) then it's broken.
So we need to know if the read model has processed all events that were in the event store at the time it last updated? We don't have that information.
Alternatively, we can set a maximum allowed time for the read model to process any event. For example, if an event is produced and not processed within X minutes, then alert. But we don't know when each event was produced.
Given the complexity, it's common to only alert when there are new events and the read model is not keeping up.
So we stick to the condition that we only alert when there are new events (i.e., the event store has advanced) and the read model is not keeping up.
But note: if the read model is completely stuck and never processes any event, then when the first new event comes, we will alert (because condition_new_events becomes true and the lag will be at least 1). And then every monitor run after that (as long as new events are coming) we will alert.
That seems acceptable.
Implementation details:
We need to store the previous_high_water_mark. We can store it in a file or a database table.
Let's create a table for the monitor state:
code
Table: cqrs_monitor_state
id: int (primary key, maybe 1 for the main monitor)
previous_high_water_mark: bigint
last_check_time: timestamp
Then the monitor:
code
SELECT previous_high_water_mark FROM cqrs_monitor_state WHERE id = 1;
// Do the checks
UPDATE cqrs_monitor_state SET previous_high_water_mark = current_hwm, last_check_time = current_time WHERE id = 1;
But note: we might want to run the monitor from multiple instances? Then we need to coordinate. Alternatively, we can have a single instance of the monitor.
Alternatively, we can store the previous_high_water_mark in a distributed configuration store (like ZooKeeper, etcd) if we have multiple monitor instances.
But for simplicity, assume one monitor.
Now, what about the read model's metadata? We are reading the read_model_metadata table. What if the read model is down? Then we cannot read the last_processed_sequence_number and last_processed_time. We need to handle that.
We can have:
code
If we cannot read the read_model_metadata, then we cannot compute the lag. We might want to alert that the read model is down.
So we can have a third alert for read model availability.
1. Event store unavailable.
2. Read model metadata unavailable.
3. Event lag too high (when there are new events).
4. Read model update too old (when there are new events).
But note: if the event store is unavailable, we cannot get the current_hwm, so we cannot compute the lag. So we just alert the unavailability.
Similarly for the read model metadata.
Now, what about the thresholds?
code
max_event_lag: this depends on the event rate and the acceptable delay. For example, if we have 1000 events per second and we want the read model to be within 1 second, then max_event_lag=1000. But if the event rate is variable, we might set a fixed number (like 10000) or a time-based threshold (like 5 minutes of events).
max_time_lag: the maximum time we allow the read model to be behind, even if the event lag is low? Actually, if the event lag is low, then the time lag should be low too. But if events are coming in slowly, then the time lag might be high even if the event lag is low? For example, if we get 1 event per hour, then the read model might take 1 hour to process that event, and the time lag would be 1 hour. But the event lag would be 0 or 1. So we might want to set max_time_lag to, say, 1 hour? But then if the read model is down for 1 hour and then processes the event, the time lag would be 1 hour and we alert? But note: we only alert when there are new events. If the read model is down for 1 hour and then processes the event, then during that hour there were no new events? Actually, if the event store is updated during that hour, then we would have new events and the read model would be behind. So we would alert.
But if the event store is idle for 1 hour, then we don't alert even if the read model is down? That might be acceptable.
Alternatively, we can have a maximum allowed time for the read model to process any event, regardless of whether there are new events. But then we need to know when each event was produced.
Given the complexity, let's stick to the two conditions with the condition that there are new events.
However, we might want to have an alert if the read model hasn't updated in a very long time (say 24 hours) even if there are no new events? Because that indicates the read model is broken and if new events come, it will be very behind.
So we can have:
code
condition_always_time_lag = (current_time - last_processed_time > max_always_time_lag)
and alert on that regardless of new events.
But then we might get false positives if the system is idle for a long time and the read model is up to date? How do we know the read model is up to date? We can check if the last_processed_sequence_number is equal to the high_water_mark at the time of the last update? But we don't store the high_water_mark at the time of the last update.
Alternatively, we can store:
code
In the read_model_metadata, we store:
last_processed_sequence_number
last_processed_time
And we also store the high_water_mark at the time of the last update? That would be redundant because we can get the current high_water_mark and if the read model is up to date, then last_processed_sequence_number should be equal to the current high_water_mark (if there are no new events). But if there are new events, then the read model is not up to date.
So if we want to alert if the read model hasn't updated in 24 hours, we can:
code
if (current_time - last_processed_time > 24 hours) {
// But we need to check if there are events that the read model hasn't processed? We don't know because the event store might have advanced.
// If the read model is up to date (last_processed_sequence_number == current_hwm) then it's okay? But then if the event store is idle, the read model being idle is okay.
// So we can check: if (last_processed_sequence_number < current_hwm) then there are unprocessed events, and if the read model hasn't updated in 24 hours, then it's stuck.
// But if last_processed_sequence_number == current_hwm, then the read model is up to date and we don't care if it hasn't updated because there's nothing to update.
// So we can do:
if (last_processed_sequence_number < current_hwm) {
trigger_alert("Read model hasn't updated in 24 hours and there are unprocessed events")
}
}
But note: if the event store is idle, then current_hwm == last_processed_sequence_number (if the read model was up to date when the event store became idle). So we don't alert.
This condition doesn't require that there are new events since the last check? Actually, if the read model is stuck and there are unprocessed events (even if no new events in the last check, but there are old unprocessed events) then we alert.
But how do we know there are unprocessed events? We compare last_processed_sequence_number and current_hwm. If current_hwm > last_processed_sequence_number, then there are unprocessed events (either new or old).
So we can have:
code
if (current_hwm > last_processed_sequence_number) {
// There are unprocessed events.
if (current_time - last_processed_time > max_stuck_time) {
trigger_alert("Read model stuck: unprocessed events and no update for " + (current_time - last_processed_time))
}
}
And note: this condition does not depend on whether there are new events since the last check. It depends on the current state.
So we can have three alerts:
code
Alert 1: Event store unavailable.
Alert 2: Read model metadata unavailable.
Alert 3: Read model stuck (unprocessed events and no update for max_stuck_time).
Alert 4: Event lag too high (when there are new events and event_lag > max_event_lag).
Alert 5: Time lag too high (when there are new events and time_since_last_update > max_time_lag).
But note: Alert 3 and 4/5 might overlap. We can decide to only have Alert 3 for the stuck condition and then use the event lag and time lag for when the read model is active but slow.
Alternatively, we can have:
code
Alert for high event lag: when event_lag > max_event_lag and there are new events (current_hwm > previous_hwm) [or even without new events? But if there are no new events, the event lag might be constant and we might not want to alert?]
Alert for high time lag: when time_since_last_update > max_time_lag and there are new events.
And a separate alert for the read model being completely stuck (no update for a long time and unprocessed events).
But note: if the read model is stuck (no update for a long time) then the time lag will be high and we will trigger the time lag alert. And if there are new events, we will trigger the event lag alert too. So we might not need a separate stuck alert? Actually, the time lag alert will trigger if the read model hasn't updated for max_time_lag and there are new events. But what if there are no new events? Then we don't get the time lag alert, but we might still have unprocessed events (old ones). So we need the stuck alert for that case.
So:
code
Stuck alert: if (current_hwm > last_processed_sequence_number) and (current_time - last_processed_time > max_stuck_time)
This alert is independent of whether there are new events since the last check.
And the time lag alert: if (current_hwm > previous_hwm) and (current_time - last_processed_time > max_time_lag)
But note: if the read model is stuck, then the time lag will be high and if there are new events, we will also trigger the time lag alert. That's okay because we might want to know both: the read model is stuck and it's also falling behind.
We can have:
code
Stuck alert: when the read model hasn't updated for max_stuck_time and there are unprocessed events (current_hwm > last_processed_sequence_number).
Time lag alert: when there are new events (current_hwm > previous_hwm) and the time since last update is > max_time_lag.
Event lag alert: when there are new events and the event lag is > max_event_lag.
And note: the stuck alert might be more severe because it indicates the read model is not processing at all, while the time lag and event lag might indicate it's slow but making progress.
Now, thresholds:
code
max_stuck_time: e.g., 1 hour? This means if the read model hasn't updated for 1 hour and there are unprocessed events, then it's stuck.
max_time_lag: e.g., 5 minutes? This means if the read model hasn't updated for 5 minutes and there are new events, then it's too slow.
max_event_lag: e.g., 1000 events? This means if there are more than 1000 unprocessed events and there are new events, then it's too slow.
But note: if the event rate is high, then 1000 events might be just a few seconds. So we might want to set max_event_lag based on the event rate? Or we can set both and let the time lag be the primary indicator? Actually, we want to catch both: too many events and too much time.
We can have:
code
Stuck: no update for 1 hour and unprocessed events.
Slow: time lag > 5 minutes and new events, or event lag > 1000 and new events.
But note: if the event rate is 1 event per second, then 1000 events is about 16 minutes, which is more than 5 minutes. So the time lag might trigger first.
We might want to set the time lag threshold based on the SLA for the read model.
Implementation:
We'll run the monitor every minute.
Steps:
code
try:
current_hwm = get_event_store_latest_sequence_number()
(current_lwm, last_processed_time) = get_read_model_metadata()
previous_hwm = get_previous_hwm_from_monitor_state()
// Check for stuck condition
if (current_hwm > current_lwm) {
if (current_time - last_processed_time > max_stuck_time) {
trigger_alert("Read model stuck: unprocessed events and no update for " + (current_time - last_processed_time))
}
}
// Check if there are new events since last check
if (current_hwm > previous_hwm) {
// There are new events
event_lag = current_hwm - current_lwm
if (event_lag > max_event_lag) {
trigger_alert("Event lag too high: " + event_lag + " events behind")
}
time_lag = current_time - last_processed_time
if (time_lag > max_time_lag) {
trigger_alert("Time lag too high: " + time_lag + " seconds behind")
}
}
// Update monitor state
update_monitor_state(current_hwm)
except EventStoreUnavailable:
trigger_alert("Event store unavailable")
except ReadModelMetadataUnavailable:
trigger_alert("Read model metadata unavailable")
We also need to consider: what if the read model metadata shows that the last_processed_sequence_number is greater than the current_hwm? That shouldn't happen, but if it does, we might want to alert? Or ignore? It could be because of clock skew or because the event store lost events? We can alert:
code
if (current_lwm > current_hwm) {
trigger_alert("Read model processed more events than the event store has! Possible data loss.")
}
So we add:
code
if (current_lwm > current_hwm) {
trigger_alert("Read model is ahead of the event store. Possible data loss or clock skew.")
}
Now, what about the read model update process? We haven't designed that. We are only monitoring.
But we assume that the read model update process is running and updating the read_model_metadata table.
How does the read model update process work?
code
It subscribes to the event store (or message broker) and processes events in order. It updates the read model's projections and also updates the read_model_metadata table with the last processed event's sequence number and the current time.
We might want to update the read_model_metadata table in the same transaction as updating the projection? Or at least atomically? So that if the projection update fails, we don't update the metadata.
But if we update the metadata only after successfully applying the event to the projection, then the metadata reflects the last successfully processed event.
That's good.
However, if the read model processes events in batches, then we update the metadata after each batch? Then the last_processed_time might be the time when the batch was processed, and the last_processed_sequence_number might be the last event in the batch.
That's acceptable.
But note: if the batch is large, then the time lag might be high even if the batch is being processed? Actually, if the batch is being processed, then the read model is updating. But the last_processed_time might be old because the batch started a long time ago? We update the last_processed_time when we finish the batch. So if the batch takes a long time, then the last_processed_time might be old until the batch finishes.
We might want to update the metadata more frequently? For example, after each event? That might be too heavy.
Alternatively, we can have two timestamps:
code
- The time when the read model started processing the batch.
- The time when the read model finished processing the batch.
But we only store one last_processed_time. We can store the time when we finished the last batch.
Then, if the batch is taking a long time, the last_processed_time will be old until the batch finishes. And then we update it to the current time.
So if we have a batch that takes 10 minutes, then for 10 minutes the last_processed_time will be the time when the previous batch finished. Then the time lag will be increasing and might trigger the time lag alert even though the read model is working? That's a problem.
We might want to adjust the time lag threshold to account for batch processing? Or we can have the read model update the metadata more frequently (like every event) if the batch is large? But that might be heavy.
Alternatively, we can have the read model update the metadata with the time of the last event in the batch, and then the time lag would be the time since that event was produced? But we don't store the event time in the metadata.
We can store the event time of the last processed event? Then we can compute the time lag as current_time - event_time_of_last_processed_event. But note: if the event store uses a global sequence number, we can get the event time for a given sequence number? Not necessarily.
Given the complexity, let's assume the read model processes events one by one and updates the metadata after each event. Then the last_processed_time is the time when the last event was processed.
But if we are batching, we can update the metadata after each event in the batch? That would be heavy.
Alternatively, we can update the metadata at the end of the batch, but then we don't have a good way to compute the time lag because the last_processed_time is the time when the batch finished, but the events in the batch might have been produced a long time ago.
So maybe we should store the event time of the last processed event? Then we can compute:
And the event lag is still the sequence number difference.
This way, if the read model processes a batch, we update the metadata with the last event's time in the batch. Then the time lag will be the time since that event was produced, which is what we want.
But note: the event store must store the event time for each event.
If we don't have event times, we cannot do this.
So if we don't have event times, we have to rely on the processing time (last_processed_time) and that might be misleading for batches.
Given the trade-offs, let's assume we have event times.
Then the monitor:
code
current_hwm = get_latest_sequence_number()
(current_lwm, last_processed_event_time) = get_read_model_metadata()
previous_hwm = get_previous_hwm()
// Check for stuck condition: if there are unprocessed events (current_hwm > current_lwm) and the time since the last processed event is too old?
// Actually, the stuck condition is: the read model hasn't processed an event in a long time, and there are unprocessed events.
if (current_hwm > current_lwm) {
if (current_time - last_processed_event_time > max_stuck_time) {
trigger_alert("Read model stuck: unprocessed events and last processed event is more than " + max_stuck_time + " old")
}
}
if (current_hwm > previous_hwm) {
event_lag = current_hwm - current_lwm
if (event_lag > max_event_lag) {
trigger_alert("Event lag too high: " + event_lag + " events behind")
}
time_lag = current_time - last_processed_event_time
if (time_lag > max_time_lag) {
trigger_alert("Time lag too high: " + time_lag + " seconds behind")
}
}
// Also, if current_lwm > current_hwm, alert about possible data loss.
update_monitor_state(current_hwm)
This seems better because the time lag is based on the event time, not the processing time.
But note: the read model might process events out of order? In CQRS with event sourcing, we usually process events in the order they were stored (by sequence number). So the last_processed_event_time should be the time of the event with the highest sequence number that we processed.
However, if the read model processes events in parallel, it might process a later event before an earlier one? That would break the consistency. We assume the read model processes events in order.
So we are safe.
Now, what about the read model update process? It should:
code
For each event (in order of sequence number):
Apply the event to the projection.
Update the read_model_metadata:
last_processed_sequence_number = event.sequence_number
last_processed_event_time = event.timestamp
And commit the metadata update in the same transaction as the projection update? Or at least atomically? We want to avoid the situation where we update the projection but not the metadata, or vice versa.
So we should update the metadata in the same transaction as the projection update.
But if the projection update is done in a separate database, then we cannot have a distributed transaction. Then we might update the metadata after the projection update, and if that fails, we have a problem: the projection is updated but the metadata is not. Then the monitor will think the read model is behind when it's not.
To avoid that, we can use an outbox pattern? Or we can update the metadata first? But then if the projection update fails, we have updated the metadata but not the projection.
So we need a way to make the two updates atomic. If they are in the same database, we can use a transaction. If they are in different databases, we might need a two-phase commit or a saga.
Given the complexity, let's assume the projection and the metadata are in the same database, so we can update in one transaction.
Alternatively, we can store the metadata in the same table as the projection? Then we can update both in one transaction.
But the metadata is per read model (or per projection) and might be a single row. We can have a table for metadata and update it in the same transaction as the projection.
If the projection is updated in a different database, we might need to use a different approach.
However, the problem is about designing the refresh process and monitoring, so we'll assume we can update the metadata atomically with the projection.
Summary:
We have:
Event store with global sequence numbers and timestamps for events.
Gets current_lwm and last_processed_event_time from read_model_metadata.
Gets previous_hwm from its state.
Checks for stuck condition (unprocessed events and last_processed_event_time too old).
Checks for new events (current_hwm > previous_hwm) and then event lag and time lag.
Updates its state with current_hwm.
Alerts for:
Event store unavailable.
Read model metadata unavailable.
Stuck condition.
Event lag too high (when there are new events).
Time lag too high (when there are new events).
This design assumes:
code
- The read model processes events in order and updates the metadata for each event (or batch, but then we use the last event's time in the batch).
- The event store provides a global sequence number and each event has a timestamp.
- The monitor runs on a single instance.
If we have multiple read model instances (for scaling), then we might have multiple consumers. In that case, we need to monitor each consumer group? Or the read model might be partitioned? Then we need to monitor each partition.
But that's an advanced scenario.
For simplicity, we assume a single consumer for the read model.
If we have multiple consumers, we might need to aggregate the lag across all partitions.
We leave that as an extension.
Now, let's write the design in a structured way.
We can write:
Components:
Event Store: Stores events with a global sequence number and a timestamp.
Read Model:
Projection tables.
Metadata table (read_model_metadata) with last_processed_sequence_number and last_processed_event_time.
Read Model Refresh Process:
Subscribes to the event store (or reads from it) and processes events in order.
For each event (or batch of events), updates the projection and then updates the metadata in the same transaction.
Monitor:
Runs periodically (e.g., every minute).
Reads the current high-water mark (latest sequence number) from the event store.
Reads the current low-water mark (last_processed_sequence_number) and last_processed_event_time from the read_model_metadata.
Reads the previous high-water mark from its state (stored in a file or database).
Performs checks and triggers alerts.
Updates its state with the current high-water mark.
Alerts:
Event store unavailable.
Read model metadata unavailable.
Stuck condition:
Condition: (current_hwm > current_lwm) and (current_time - last_processed_event_time > max_stuck_time)
Message: "Read model is stuck. Last processed event was at {last_processed_event_time}, and there are {current_hwm - current_lwm} unprocessed events."
Event lag too high:
Condition: (current_hwm > previous_hwm) and (current_hwm - current_lwm > max_event_lag)
Message: "Event lag is {current_hwm - current_lwm} events. Threshold: {max_event_lag}."
Time lag too high:
Condition: (current_hwm > previous_hwm) and (current_time - last_processed_event_time > max_time_lag)
Message: "Time lag is {current_time - last_processed_event_time} seconds. Threshold: {max_time_lag}."
- If current_lwm > current_hwm, alert about possible data loss.
Edge Cases:
code
- If the event store is empty (current_hwm = 0) and the read model is also empty (current_lwm = 0), then no alerts.
- If the read model is ahead (current_lwm > current_hwm), then we alert about possible data loss.
This design should cover the basic requirements.
Now, we can write the design document.
Let me structure it:
CQRS Read Model Refresh Process with Eventual Consistency Monitors and Alerting for Stale Projections
Overview
In a CQRS architecture, the read model (query side) is eventually consistent with the write model (command side). This design describes a process to monitor the staleness of the read model and trigger alerts when the read model is not keeping up with the write model.
Assumptions
The event store provides a global, monotonically increasing sequence number for each event.
Each event has a timestamp (the time when the event was produced).
The read model processes events in the order of their sequence numbers.
The read model updates its metadata (last processed sequence number and event time) in the same transaction as updating the projection.
There is a single consumer for the read model (i.e., the read model is not partitioned across multiple consumers). If there are multiple consumers, the design would need to be extended to monitor each consumer group/partition.
Components
Event Store
Stores all events. Each event has:
- sequence_number: a global, monotonically increasing integer.
- timestamp: the time when the event was produced (in UTC).
Provides an API to get the latest sequence number (high-water mark).
Read Model Database
Contains:
- Projection tables (the actual read model data).
- A metadata table named read_model_metadata with one row (or one per projection if multiple) containing:
- last_processed_sequence_number: the sequence number of the last event successfully processed.
- last_processed_event_time: the timestamp of the last event successfully processed.
Read Model Refresh Process
A process that:
1. Subscribes to the event store (or polls it) for new events, starting from the last processed sequence number.
2. For each event (or batch of events) in order:
a. Applies the event to the projection (updating the projection tables).
b. Updates the read_model_metadata with the last event's sequence number and timestamp.
c. Commits the transaction (ensuring the projection and metadata update are atomic).
Monitor
A separate process that runs periodically (e.g., every minute) and performs the following steps:
Fetch current high-water mark (HWM): Get the latest sequence number from the event store.
Fetch current low-water mark (LWM) and last processed event time: Read the read_model_metadata table.
Fetch previous HWM: Read the monitor's state from a persistent storage (e.g., a database table monitor_state).
Check for unprocessed events: If current_hwm > current_lwm, then there are unprocessed events.
Stuck condition: If there are unprocessed events and the time since the last processed event is greater than max_stuck_time, trigger a stuck alert.
Check for new events: If current_hwm > previous_hwm, then there are new events since the last monitor run.
Event lag: If there are new events and the event lag (current_hwm - current_lwm) is greater than max_event_lag, trigger an event lag alert.
Time lag: If there are new events and the time lag (current_time - last_processed_event_time) is greater than max_time_lag, trigger a time lag alert.
Data loss check: If current_lwm > current_hwm, trigger a data loss alert (the read model has processed more events than the event store currently has).
Update monitor state: Store the current HWM as the previous HWM for the next run.
Alerts
The monitor triggers the following alerts:
Event store unavailable: When the event store cannot be queried for the current HWM.
Read model metadata unavailable: When the read model's metadata table cannot be read.
Read model stuck: Triggered when there are unprocessed events and the last processed event is older than max_stuck_time. This indicates the read model is not processing events at all.
Event lag too high: Triggered when there are new events and the number of unprocessed events exceeds max_event_lag. This indicates the read model is falling behind in terms of event count.
Time lag too high: Triggered when there are new events and the time since the last processed event exceeds max_time_lag. This indicates the read model is falling behind in terms of time.
Possible data loss: Triggered when the read model's last processed sequence number is greater than the current HWM from the event store.
Configuration
The following thresholds are configurable:
max_stuck_time: The maximum allowed time (in seconds) that the read model can be stuck with unprocessed events. Default: 3600 (1 hour).
max_event_lag: The maximum allowed number of unprocessed events when there are new events. Default: 1000.
max_time_lag: The maximum allowed time (in seconds) that the read model can be behind when there are new events. Default: 300 (5 minutes).
Monitor State
The monitor stores its state in a table named monitor_state:
Column
Type
Description
id
int
Primary key (always 1)
previous_high_water_mark
bigint
The HWM from the last monitor run.
last_check_time
timestamp
The time of the last monitor run.
Error Handling
If the event store is unavailable, the monitor logs an error and triggers the "Event store unavailable" alert. It does not perform further checks.
If the read model metadata is unavailable, the monitor logs an error and triggers the "Read model metadata unavailable" alert. It does not perform further checks.
If the read model is ahead (current_lwm > current_hwm), the monitor triggers the "Possible data loss" alert. This might indicate a serious issue (like event loss or clock skew).
Extensions
Multiple Consumers: If the read model is scaled out with multiple consumers (each processing a subset of events), the monitor would need to be adjusted to monitor each consumer group or partition. The design above assumes a single consumer.
Multiple Projections: If there are multiple read models (projections) that are updated independently, each might have its own metadata. The monitor would need to check each one.
Batched Processing: If the read model processes events in batches, the last_processed_event_time should be set to the timestamp of the last event in the batch. The monitor's time lag calculation will then reflect the age of the newest event in the batch.
Example
Suppose:
- Current HWM: 1000
- Current LWM: 950
- Last processed event time: 10 minutes ago (from current time)
- Previous HWM: 980 (so there are new events: 981-1000)
Then:
- Event lag = 50 events.
- Time lag = 10 minutes.
- If max_event_lag is 100 and max_time_lag is 300 seconds (5 minutes), then both event lag and time lag alerts would trigger.
If the read model hasn't processed any event for 2 hours and there are unprocessed events (say HWM=1000, LWM=950, last processed event time=2 hours ago), and max_stuck_time is 1 hour, then the stuck alert would trigger.
Conclusion
This design provides a way to monitor the staleness of the read model in an eventually consistent CQRS system and alert when the read model is not keeping up with the write model. It accounts for both the number of unprocessed events and the time since the last update, and it distinguishes between the read model being actively slow and being completely stuck.
Note: The monitor itself should be highly available and its alerts should be integrated with the operations team's alerting system (e.g., PagerDuty, Opsgenie).
Let me know if you have any questions or need further details.
I'll design a comprehensive CQRS read model monitoring system with eventual consistency verification and alerting. Here's a production-ready solution:
// Event Processor with offset tracking
public class ProjectionUpdater {
private final EventStore eventStore;
private final ProjectionRepository projectionRepo;
private final OffsetManager offsetManager;
public void refreshProjections() {
// 1. Get last processed offset per projection
Map<String, Long> lastOffsets = offsetManager.getLastOffsets();
// 2. Fetch events since last offset (batching)
List<DomainEvent> events = eventStore.getEventsSince(lastOffsets);
// 3. Process in order with idempotency
for (DomainEvent event : events) {
// Apply to all relevant projections
applyToProjections(event);
// Update offset for each projection type
offsetManager.updateOffset(event.getProjectionType(),
event.getOffset());
}
// 4. Update projection health metrics
updateHealthMetrics(events);
}
private void applyToProjections(DomainEvent event) {
// Using idempotent event handlers
projectionRepo.updateUserProjection(event);
projectionRepo.updateOrderProjection(event);
// ... other projections
}
}
1.2 Offset Management Pattern
sql
-- Offset tracking table
CREATE TABLE projection_offsets (
projection_name VARCHAR(100) PRIMARY KEY,
last_processed_offset BIGINT NOT NULL,
last_processed_time TIMESTAMP NOT NULL,
last_event_timestamp TIMESTAMP,
processing_lag_ms INT,
is_stale BOOLEAN DEFAULT FALSE,
last_heartbeat TIMESTAMP
);
-- Materialized view for lag calculation
CREATE VIEW projection_lag_view AS
SELECT
p.projection_name,
p.last_processed_offset,
e.max_offset as event_store_offset,
e.max_offset - p.last_processed_offset as offset_lag,
EXTRACT(EPOCH FROM (NOW() - p.last_processed_time)) as time_lag_seconds,
CASE
WHEN (e.max_offset - p.last_processed_offset) > 1000
OR EXTRACT(EPOCH FROM (NOW() - p.last_processed_time)) > 300
THEN TRUE
ELSE FALSE
END as is_stale
FROM projection_offsets p
CROSS JOIN (SELECT MAX(offset) as max_offset FROM event_store) e;
// Heartbeat publisher from projection updater
@Component
public class HeartbeatPublisher {
@Scheduled(fixedDelay = 30000) // Every 30 seconds
public void publishHeartbeat() {
ProjectionHealth health = new ProjectionHealth();
health.setProjectionName("user_projection");
health.setLastUpdated(Instant.now());
health.setLastProcessedOffset(offsetManager.getCurrentOffset());
health.setProcessingRate(calculateRecentRate());
health.setStatus(Status.HEALTHY);
kafkaTemplate.send("projection-health", health);
}
}
// Health consumer that updates metadata
@KafkaListener(topics = "projection-health")
public void handleHealth(ProjectionHealth health) {
projectionMetadataRepository.updateHealth(
health.getProjectionName(),
health.getLastUpdated(),
health.getLastProcessedOffset()
);
}
3. Alerting System
3.1 Alert Definitions
yaml
alerts:
- name: "projection_stale_offset"
expr: |
projection_lag_offset{projection="user_projection"} > 1000
for: "5m"
labels:
severity: warning
component: read-model
annotations:
summary: "User projection offset lag high"
description: "User projection is {{ $value }} events behind"
- name: "projection_stale_time"
expr: |
projection_time_lag_seconds{projection="order_projection"} > 300
for: "5m"
labels:
severity: critical
component: read-model
annotations:
summary: "Order projection time lag critical"
description: "Order projection hasn't updated in {{ $value }}s"
- name: "projection_no_progress"
expr: |
projection_last_updated_seconds{projection="*"} > 600
for: "10m"
labels:
severity: critical
component: read-model
annotations:
summary: "Projection not making progress"
description: "No events processed for {{ $value }}s"
- name: "eventual_consistency_sla_violation"
expr: |
sum(projection_time_lag_seconds{projection=~".+"})
/ count(projection_time_lag_seconds{projection=~".+"}) > 60
for: "15m"
labels:
severity: critical
component: read-model
annotations:
summary: "SLA violation: Average consistency lag too high"
description: "Average read model lag is {{ $value }}s (SLA: <60s)"
3.2 Alert Routing & Escalation
python
class AlertManager:
def __init__(self):
self.routing_rules = {
'critical': ['oncall-engineer', 'team-lead', 'slack-alerts'],
'warning': ['team-slack', 'dashboard'],
'info': ['dashboard']
}
def route_alert(self, alert):
# Determine severity based on projection type and lag
severity = self.calculate_severity(alert)
# Apply deduplication (same alert within 10 minutes)
if self.is_duplicate(alert):
return
# Route based on severity
destinations = self.routing_rules.get(severity, [])
for dest in destinations:
self.send_notification(dest, alert)
# Create ticket for critical alerts
if severity == 'critical':
self.create_incident_ticket(alert)
4. Metrics & Dashboard
4.1 Key Metrics to Expose
prometheus
# Helpers
# Offset lag per projection
projection_offset_lag{projection="user_projection"} 150
# Time lag in seconds
projection_time_lag_seconds{projection="order_projection"} 45.2
# Processing rate (events/sec)
projection_processing_rate{projection="user_projection"} 125.5
# Error rate
projection_error_rate{projection="*"} 0.002
# Status (0=down, 1=degraded, 2=healthy)
projection_status{projection="*"} 2
# Throughput comparison (current vs baseline)
projection_throughput_ratio{projection="*",period="1h"} 1.15
4.2 Grafana Dashboard Panels
Lag Overview: Heatmap of all projections with offset/time lag
SLA Compliance: Percentage of time within SLA thresholds
Top Stale Projections: Table sorted by lag
Consistency Timeline: Time-series of lag for key projections
Event Throughput: Incoming events vs processed events
1. ACKNOWLEDGE alert in incident channel
2. CHECK dashboard for:
- Which projection is stale?
- Lag trend (increasing/decreasing/stable)?
- Error rates?
- Consumer group lag in Kafka?
3. IMMEDIATE ACTIONS:
a. Check consumer group offsets:
kafka-consumer-groups --bootstrap-server ... --describe --group read-model-group
b. Check projection logs for errors:
kubectl logs -l app=read-model -c projection-updater --tail=100
c. Verify event store health:
- Is Kafka topic healthy?
- Any broker failures?
4. TROUBLESHOOTING:
- If offset lag increasing but processing rate normal:
* Check for batch size too small
* Check for downstream DB slowness
- If processing rate dropped to zero:
* Check for exceptions in projection updater
* Check consumer group rebalancing
* Verify DB connectivity
- If time lag high but offset lag normal:
* Events might be old (check event timestamps)
* Clock skew between services
5. RECOVERY:
- Restart affected projection consumer
- Scale up consumer instances
- Increase batch size temporarily
- If corrupted state, rollback to last checkpoint
6. POST-MORTEM:
- Document root cause
- Update thresholds if needed
- Add missing metrics/logs
- Improve recovery automation
class PredictiveMonitor:
def predict_lag(self, projection, window='1h'):
# Use time series forecasting (ARIMA, Prophet)
historical_lag = self.get_historical_lag(projection, window)
# Predict next 30 minutes
forecast = self.forecaster.predict(historical_lag, steps=30)
if max(forecast) > self.thresholds['offset_lag']:
self.send_early_warning(
projection,
f"Predicted lag in 30min: {max(forecast)}"
)
Multi-tenancy: Isolate projection data per tenant if needed
This design provides:
Comprehensive monitoring with multi-dimensional staleness detection
Intelligent alerting with proper severity and routing
Automated recovery where possible
Operational visibility through dashboards
SLA tracking and compliance reporting
Production-ready patterns with HA and fault tolerance
The system can detect when projections are stale due to processing delays, consumer failures, downstream issues, or event store problems, and provide actionable alerts with context for quick resolution.