We are going to design a system that periodically checks the consistency between a read model (denormalized view) and the source of truth (e.g., a transactional database) by sampling.
Steps:
- We have a source of truth (SOT) and one or more read models (RM).
- We want to sample a subset of data (by some criteria, e.g., random, recent, etc.) from the SOT and then compare the corresponding data in the RM.
- The comparison can be done by:
a. Querying the SOT for the sampled keys and the expected values (or the entire state for those keys).
b. Querying the RM for the same keys and comparing the values.
- We need to define what "consistency" means. For example, for each sampled key, the RM should have the same value as in the SOT at the time of the SOT query.
- We must account for the fact that the RM might be eventually consistent and might have a delay. Therefore, we might want to sample only data that is old enough to have been propagated (e.g., only data older than the maximum expected delay).
- We can run this validator periodically and report any inconsistencies.
Design Considerations:
- How to sample? We can use random sampling, or stratified sampling if we have different categories.
- How to handle large datasets? We might need to sample a fixed number or a percentage.
- What if the RM is down? We need to handle errors.
- We might want to record the results (inconsistencies) for monitoring and alerting.
Implementation Plan:
Let's assume we have:
SOT: a database (SQL, NoSQL) that is the source of truth.
RM: another database (or same but different table) that holds the denormalized read model.
We will create a validator that:
Step 1: Determine the sample set.
We can have a configuration for:
- sampling strategy (random, recent, etc.)
- sample size (n) or sample fraction (p)
- filter (only consider records that are older than X to avoid lag)
For example, for random sampling:
We can get a list of primary keys from the SOT that meet the filter (e.g., updated_at < now - max_delay) and then randomly select n of them.
Step 2: For each key in the sample, get the current state from SOT and from RM.
Step 3: Compare the two states. We need a way to compare. This could be:
- Simple field-by-field comparison (if the RM is a direct copy of some fields from SOT)
- Or if the RM is a projection, we might need to compute the expected value from the SOT (which might require joining multiple tables or running a function).
We might define a comparator function that takes (sot_data, rm_data) and returns whether they are consistent.
Step 4: Collect all inconsistencies and report.
Step 5: Log the results and possibly send alerts.
We can run this as a scheduled job (e.g., every hour).
Example Implementation:
Let's assume we are validating a user profile read model that is built from a transactional user table and an address table.
SOT:
Table: users (id, name, email, updated_at)
Table: addresses (id, user_id, street, city, updated_at)
RM:
Table: user_profiles (user_id, name, email, address, updated_at)
The RM might be built by joining users and addresses and denormalizing the address.
We can define a comparator for a given user_id:
SOT:
Get the user by id and the primary address (or the one marked as primary) from addresses.
Then construct the expected profile: { user_id: id, name: name, email: email, address: street + ', ' + city }
RM:
Get the user_profiles record for user_id.
Then compare.
However, note that the RM might not have an address for a user without an address. So we have to handle that.
Alternatively, we can have a stored procedure or a query that computes the expected RM data from the SOT for a set of user_ids.
We can do:
For a set of user_ids, we can run a query that returns the expected RM data for each user_id.
Then we can run a query on the RM for the same user_ids.
Then compare in the application code.
But if we have a large sample, we might want to do set-based comparison in the database if possible.
However, because the RM might be in a different database, we might have to do it in the application.
Let's assume we are in an application that can connect to both databases.
Pseudocode:
class ConsistencyValidator:
def init(self, sot_connection, rm_connection, sample_size, max_delay_seconds):
self.sot_conn = sot_connection
self.rm_conn = rm_connection
self.sample_size = sample_size
self.max_delay = max_delay_seconds
def get_sample_user_ids(self):
# We get user_ids from the SOT that are old enough (updated_at < now - max_delay)
# Then we randomly select sample_size of them.
query = """
SELECT id FROM users
WHERE updated_at < NOW() - INTERVAL '{} seconds'
ORDER BY RANDOM()
LIMIT {}
""".format(self.max_delay, self.sample_size)
# Execute on SOT and return list of ids.
def get_expected_profile_from_sot(self, user_ids):
# We can write a query that joins users and addresses (assuming one address per user for simplicity) and returns the expected profile.
# But note: we might have multiple addresses? Then we have to decide which one to use.
# Let's assume we have a primary address flag in addresses.
query = """
SELECT
u.id as user_id,
u.name,
u.email,
a.street || ', ' || a.city as address
FROM users u
LEFT JOIN addresses a ON u.id = a.user_id AND a.is_primary = true
WHERE u.id IN ({})
""".format(','.join(map(str, user_ids)))
# This returns a list of expected profiles for the given user_ids.
def get_actual_profiles_from_rm(self, user_ids):
query = """
SELECT user_id, name, email, address
FROM user_profiles
WHERE user_id IN ({})
""".format(','.join(map(str, user_ids)))
def compare(self, expected_profiles, actual_profiles):
# We can convert actual_profiles to a dict by user_id for easy lookup.
actual_dict = {profile['user_id']: profile for profile in actual_profiles}
inconsistencies = []
for expected in expected_profiles:
user_id = expected['user_id']
actual = actual_dict.get(user_id)
if actual is None:
inconsistencies.append({
'user_id': user_id,
'error': 'missing in RM',
'expected': expected,
'actual': None
})
else:
# Compare fields. We might have to normalize (e.g., address formatting) or use a custom comparator.
if (expected['name'] != actual['name'] or
expected['email'] != actual['email'] or
expected['address'] != actual['address']):
inconsistencies.append({
'user_id': user_id,
'error': 'mismatch',
'expected': expected,
'actual': actual
})
return inconsistencies
def run(self):
sample_ids = self.get_sample_user_ids()
if not sample_ids:
print("No sample ids found. Skipping.")
return
expected = self.get_expected_profile_from_sot(sample_ids)
actual = self.get_actual_profiles_from_rm(sample_ids)
inconsistencies = self.compare(expected, actual)
self.report(inconsistencies)
def report(self, inconsistencies):
# Log and maybe send alert if there are any inconsistencies.
if inconsistencies:
for inc in inconsistencies:
print(inc)
# Send alert, etc.
else:
print("No inconsistencies found.")
However, note that the above example assumes:
- One address per user (primary). Adjust as needed.
- The RM table has the same fields as the expected projection.
In a real system, we might have to handle:
- Different ways of projecting (e.g., concatenation, aggregation, etc.)
- The RM might be built from multiple events and we might need to replay events? But that's heavy. Instead, we might have a way to compute the expected state from the current SOT state.
Alternatively, if the RM is built by an event processor, we might want to compare the event stream? But that's more complex.
This validator is for the current state.
Another approach: if the RM is built by a materialized view that is updated by triggers, we might be able to use the same logic as the view to compute the expected from SOT.
We must be cautious: the comparator must be exactly the same as the logic that builds the RM, otherwise we might flag false positives.
We can also consider:
-
Sampling by time: only sample records that were updated at a time when we know the RM should have caught up (e.g., 24 hours ago).
-
We might want to sample different types of records (stratified) to ensure we cover all cases.
-
We might want to run multiple validators for different read models.
-
We might want to run the validator in a way that doesn't overload the SOT or RM.
-
We might want to run the validator in a read-only replica of the SOT to avoid impacting the primary.
-
We might want to run the validator on a subset of the data that is known to be critical.
-
We might want to have a way to automatically correct inconsistencies? That's more advanced and might be risky.
-
We might want to track the consistency rate over time.
Let's extend the design:
We can have:
class ConsistencyValidator:
def __init__(self, config):
self.config = config
# config might have:
# sot_connection, rm_connection, sample_size, max_delay,
# sampling_strategy,
# comparator (a function or a class that knows how to compare for a given entity type)
def sample(self):
#根据配置的采样策略返回一组keys
def fetch_expected(self, keys):
# 从SOT获取预期状态
def fetch_actual(self, keys):
# 从RM获取实际状态
def compare(self, expected, actual):
# 使用配置的比较器比较
def run(self):
keys = self.sample()
expected = self.fetch_expected(keys)
actual = self.fetch_actual(keys)
return self.compare(expected, actual)
Then we can have a Scheduler that runs the validator periodically.
We can also have multiple validators for different entity types.
We can have a way to persist the results (in a database or log) and then have a dashboard.
We can set up alerts if the inconsistency rate exceeds a threshold.
We can also have a way to manually trigger a validation for a specific set of keys (e.g., when we suspect a problem).
We must be cautious about the performance of the validator. We don't want to run heavy queries on the SOT during peak hours.
We might run the validator on a read replica of the SOT and on a read-only replica of the RM (if available).
We might also want to limit the validator to a fixed percentage of the data if the sample size is too large.
We might want to use a fixed random seed for reproducibility? But then we might always sample the same set. Maybe we want to sample randomly each time.
Alternatively, we can use a hash of the key and then take a sample by hash range (like reservoir sampling) so that we can sample consistently over time? Not necessary.
Let's keep it simple: random sample.
But note: if we have a very large table, getting a random sample by ORDER BY RAND() is expensive. We can use a different approach:
We can get the min and max id and then generate random ids in that range and then check if they exist? But that might not be uniform.
Alternatively, we can use TABLESAMPLE if the database supports it (PostgreSQL, SQL Server). But it's not available in all.
Or we can use a random offset? But that's also expensive.
We might have to accept that for very large tables, we might need a different sampling strategy.
Another idea: if we have a timestamp column, we can sample by time (e.g., pick a random day in the last month and then take all records from that day? but that might be too many). Then we can randomly select from that day.
Given the complexity, we might just use a random sample by id if the id distribution is uniform and we have an index on id.
Steps for random sample by id:
1. Get the min and max id from the table (with the filter).
2. Generate random numbers between min and max and then select the records with id >= random_id order by id limit 1? That doesn't give exactly n.
Alternatively, we can do:
SELECT id FROM users
WHERE updated_at < ...
AND id >= (SELECT FLOOR( RAND() * (SELECT MAX(id) FROM users) ) FROM users)
ORDER BY id
LIMIT n
But that might not be random if there are gaps.
We can use:
SELECT id FROM users
WHERE updated_at < ...
AND id >= (SELECT (RAND() * (SELECT MAX(id) FROM users))::integer FROM users)
ORDER BY id
LIMIT n
However, if there are gaps, we might get less than n. We can run multiple queries? Or we can use a different method.
Alternatively, we can use a temporary table with all the ids that meet the filter and then sample from that? But that might be too big.
Given the trade-offs, we might just use the simple ORDER BY RAND() if the table is not too large, or if we are sampling from a filtered set that is small.
If the filtered set is large, we might use:
SELECT id FROM users
WHERE updated_at < ...
AND id IN (SELECT id FROM users WHERE updated_at < ... ORDER BY RAND() LIMIT n)
But that's the same.
We might need to adjust based on the database.
Let's assume we are using PostgreSQL and we have an index on updated_at and id.
We can do:
SELECT id FROM users
WHERE updated_at < NOW() - INTERVAL '{} seconds'
ORDER BY RANDOM()
LIMIT {}
But if the table is huge and the filter is not selective, this will be slow.
We can try to use a two-step:
Step 1: get a random set of ids from the index on updated_at? Not sure.
Alternatively, we can use a different sampling strategy: by time.
We pick a random timestamp in the allowed range (e.g., between min(updated_at) and max(updated_at) of the filtered set) and then take the first n records we find after that timestamp? But that might not be uniform.
Given the complexity, we might just accept that for large tables we need a more sophisticated sampling or we sample from a precomputed table of ids (like a materialized view that holds the ids of old records).
But let's not overcomplicate. We assume the table is not too large or we have a way to sample efficiently.
We'll leave the sampling strategy as pluggable.
So we can have:
class RandomSampler:
def __init__(self, filter_condition, sample_size):
self.filter = filter_condition
self.sample_size = sample_size
def sample(self, connection):
query = f"""
SELECT id FROM users
WHERE {self.filter}
ORDER BY RANDOM()
LIMIT {self.sample_size}
"""
# execute and return ids
class TimeWindowSampler:
def __init__(self, filter_condition, sample_size, time_column='updated_at'):
...
We can also have a composite sampler that does stratified sampling.
But for now, let's stick with random.
We'll design the validator to be flexible.
We can also consider:
- We might want to sample by a hash of the id to get a consistent sample over time? Not necessary.
Let's code a simple version with random sampling and then we can extend.
We'll assume the SOT and RM are in the same database for simplicity? But they might not be.
We'll assume we have two connections.
We'll write the validator in Python.
Let's code:
Note: We are going to use a simple example with users and addresses.
We'll assume the following schema:
SOT:
users: id (int), name (varchar), email (varchar), updated_at (timestamp)
addresses: id (int), user_id (int), street (varchar), city (varchar), is_primary (boolean), updated_at (timestamp)
RM:
user_profiles: user_id (int), name (varchar), email (varchar), address (varchar), updated_at (timestamp)
We'll create a validator for user_profiles.
Steps:
1. Sample user_ids from users table (with filter: updated_at < now - max_delay).
2. For each user_id, get the expected profile by joining users and addresses (primary address).
3. Get the actual profile from user_profiles.
4. Compare.
But note: the RM might have a different updated_at? We are comparing the content, but we might also want to check the updated_at?
We can decide: we are comparing the state, so we might not care about the updated_at in the RM? Or we might want to check that the RM was updated after the SOT?
We are sampling old records to avoid lag, so we don't expect the updated_at to be exactly the same, but we might want to check that the RM updated_at is not too old?
We can leave that for another validator.
For now, we compare the business data: name, email, address.
Let's code accordingly.
We'll create:
class UserProfileValidator(ConsistencyValidator):
def get_expected_profile_from_sot(self, user_ids):
# We'll do a single query for all user_ids.
query = """
SELECT
u.id as user_id,
u.name,
u.email,
a.street || ', ' || a.city as address
FROM users u
LEFT JOIN addresses a ON u.id = a.user_id AND a.is_primary = true
WHERE u.id IN ({})
""".format(','.join(map(str, user_ids)))
# Execute on SOT and return list of dicts.
def get_actual_profiles_from_rm(self, user_ids):
query = """
SELECT user_id, name, email, address
FROM user_profiles
WHERE user_id IN ({})
""".format(','.join(map(str, user_ids)))
def compare(self, expected_profiles, actual_profiles):
# ... as above
But note: the RM might have a different representation for address (e.g., without concatenation). We are using the same concatenation as in the projection.
How is the RM built? We must know the projection logic.
We can make the comparator configurable.
Alternatively, we can have a function that, given a SOT record (and possibly related records), returns the expected RM record.
We can define:
def build_expected_profile(user_record, address_record):
if address_record:
address = address_record['street'] + ', ' + address_record['city']
else:
address = None
return {
'user_id': user_record['id'],
'name': user_record['name'],
'email': user_record['email'],
'address': address
}
Then in get_expected_profile_from_sot, we can do:
users = query_users(user_ids) # returns dict by user_id
addresses = query_addresses(user_ids) # returns dict by user_id (only primary)
expected = []
for user_id in user_ids:
user = users.get(user_id)
if not user:
# This user might have been deleted? But we sampled from users, so should exist.
continue
address = addresses.get(user_id)
expected.append(build_expected_profile(user, address))
But note: the user_profiles might have been built at a different time and the user might have been updated since then?
We are sampling old records, so we are comparing the SOT state at the time of the query with the RM state (which might be older or newer?).
Actually, we are comparing the current SOT state with the current RM state. But we are sampling only old records to avoid lag.
So we assume that for records that were updated more than max_delay ago, the RM should have caught up.
But what if the RM is built from events and there is a gap in event processing? Then the RM might be missing or outdated.
We are comparing the current SOT (which is the source of truth) with the current RM. If the RM is behind, we might see inconsistencies.
We are sampling old records to avoid that, but if the RM is consistently behind by more than max_delay, then we will see inconsistencies for all old records?
We might want to adjust the max_delay based on the typical lag.
Alternatively, we can compare the SOT state at a time in the past (e.g., 24 hours ago) with the RM state now?
But that would require storing historical state in the SOT? Not necessarily, we can use a point-in-time query if we have versioning?
Without versioning, we only have the current state.
So we are comparing the current SOT with the current RM, but we are only sampling records that are old enough to have been processed.
This is a reasonable approach.
Let's code accordingly.
We'll create a base class:
class ConsistencyValidator:
def __init__(self, sot_conn, rm_conn, sample_size, max_delay_seconds, sampling_strategy='random'):
self.sot_conn = sot_conn
self.rm_conn = rm_conn
self.sample_size = sample_size
self.max_delay = max_delay_seconds
self.sampling_strategy = sampling_strategy
def sample_keys(self):
# returns list of keys (user_ids in this example)
pass
def get_expected(self, keys):
# returns list of expected records (dicts) for the given keys from SOT
pass
def get_actual(self, keys):
# returns list of actual records (dicts) for the given keys from RM
pass
def compare_records(self, expected, actual):
# returns list of inconsistencies
pass
def run(self):
keys = self.sample_keys()
if not keys:
return []
expected = self.get_expected(keys)
actual = self.get_actual(keys)
return self.compare_records(expected, actual)
Then we implement a specific validator for user_profiles.
We'll also handle the case when the RM doesn't have a record for a key (missing).
We'll assume that the keys are user_ids.
Let's code the UserProfileValidator:
class UserProfileValidator(ConsistencyValidator):
def sample_keys(self):
query = """
SELECT id FROM users
WHERE updated_at < NOW() - INTERVAL '{} seconds'
ORDER BY RANDOM()
LIMIT {}
""".format(self.max_delay, self.sample_size)
# execute on self.sot_conn and return list of ids.
def get_expected(self, user_ids):
# We'll do two queries: one for users and one for addresses (primary only)
# Then build the expected profiles.
user_query = """
SELECT id, name, email
FROM users
WHERE id IN ({})
""".format(','.join(map(str, user_ids)))
users = self.sot_conn.execute(user_query).fetchall()
users_by_id = {user['id']: user for user in users}
address_query = """
SELECT user_id, street, city
FROM addresses
WHERE user_id IN ({}) AND is_primary = true
""".format(','.join(map(str, user_ids)))
addresses = self.sot_conn.execute(address_query).fetchall()
addresses_by_user_id = {addr['user_id']: addr for addr in addresses}
expected = []
for user_id in user_ids:
user = users_by_id.get(user_id)
if user is None:
# This user might have been deleted? But we just sampled, so skip.
continue
address = addresses_by_user_id.get(user_id)
address_str = None
if address:
address_str = address['street'] + ', ' + address['city']
expected.append({
'user_id': user_id,
'name': user['name'],
'email': user['email'],
'address': address_str
})
return expected
def get_actual(self, user_ids):
query = """
SELECT user_id, name, email, address
FROM user_profiles
WHERE user_id IN ({})
""".format(','.join(map(str, user_ids)))
return self.rm_conn.execute(query).fetchall()
def compare_records(self, expected, actual):
actual_by_id = {rec['user_id']: rec for rec in actual}
inconsistencies = []
for exp in expected:
user_id = exp['user_id']
act = actual_by_id.get(user_id)
if act is None:
inconsistencies.append({
'user_id': user_id,
'error': 'missing',
'expected': exp,
'actual': None
})
else:
# Compare fields
if (exp['name'] != act['name'] or
exp['email'] != act['email'] or
exp['address'] != act['address']):
inconsistencies.append({
'user_id': user_id,
'error': 'mismatch',
'expected': exp,
'actual': act
})
return inconsistencies
This is a simple implementation.
We can improve:
- We might want to compare only the fields that are in the RM? But the RM might have extra fields? We are only comparing the ones we expect.
- We might want to ignore certain fields (like updated_at) if they are not part of the business state.
- We might want to have a configurable list of fields to compare.
- We might want to handle NULLs properly (e.g., address can be NULL).
Let's adjust the comparison to handle NULLs:
def fields_equal(expected_val, actual_val):
if expected_val is None and actual_val is None:
return True
if expected_val is None or actual_val is None:
return False
return expected_val == actual_val
Then in compare:
if not fields_equal(exp['name'], act['name']) or ...
But note: the RM might have an empty string vs NULL? We have to know the business rule.
We can leave that to the specific validator.
Alternatively, we can have a comparer function that is passed in the config.
Given the complexity of different projections, we might want to make the comparison logic pluggable.
We can change the base class to accept a comparator function.
class ConsistencyValidator:
def __init__(self, ..., comparator=None):
self.comparator = comparator or self.default_comparator
def default_comparator(self, expected, actual):
# compare all keys in expected that are also in actual?
# But we know the expected and actual are for the same entity type.
# We can require that the expected and actual have the same keys? Not necessarily.
# Let's assume we have a list of fields to compare.
fields = ['name', 'email', 'address']
for field in fields:
if expected.get(field) != actual.get(field):
return False
return True
But then we have to handle missing fields?
We can do:
for field in fields:
if expected.get(field) != actual.get(field):
return False
This will treat missing field as None? But if the field is missing in expected, we might not care? We only compare the fields we expect.
Alternatively, we can have a set of fields that must be present in both?
We can design the expected and actual to have the same fields? In our example, we build the expected with user_id, name, email, address. The actual has the same.
So we can just compare all fields except the key? But the key is the same.
We can do:
for key in expected:
if key == 'user_id':
continue
if expected[key] != actual.get(key):
return False
But note: the actual might have extra fields. We ignore them.
So:
def default_comparator(self, expected, actual):
for key, value in expected.items():
if key == 'user_id':
continue
if value != actual.get(key):
return False
return True
Then in compare_records:
if not self.comparator(exp, act):
# record inconsistency
This way, we can override the comparator for different validators.
Let's adjust the base class:
class ConsistencyValidator:
def __init__(self, sot_conn, rm_conn, sample_size, max_delay_seconds, sampling_strategy='random', comparator=None):
self.sot_conn = sot_conn
self.rm_conn = rm_conn
self.sample_size = sample_size
self.max_delay = max_delay_seconds
self.sampling_strategy = sampling_strategy
self.comparator = comparator or self.default_comparator
def default_comparator(self, expected, actual):
# Compare all fields except the key (which we assume is 'user_id' in this example, but it could be different)
# We don't know the key field name? We can let the subclass define it? Or we can have a key_field attribute.
# Alternatively, we can require that the expected and actual have the same structure and we skip the key field.
# But we don't know the key field name. We can have an attribute self.key_field.
# Let's assume the key field is the first field? Not safe.
# We can have the validator define the key field.
# Alternatively, we can have the sample_keys return a list of tuples (key, ...) but we are returning just keys.
# Let's change: the sample_keys returns a list of keys (simple). Then get_expected and get_actual return a list of records (dicts) that have a key field.
# We can have the validator define the key field name.
# We'll add in __init__: key_field='user_id'
pass
We'll leave that for the specific validator to handle.
In UserProfileValidator, we know the key is 'user_id'. We can override the comparator if needed.
But the default_comparator in the base class doesn't know the key field. We can make it an abstract method? Or we can have the base class comparator expect that the expected and actual are for the same key and we don't compare the key.
We can change the base class to:
def default_comparator(self, expected, actual):
# We assume that the key field is the same and we skip it.
# But we don't know the key field. We can require that the expected and actual have the same set of keys except the key field?
# Alternatively, we can have the validator pass the key field.
# Let's change the design: the validator will have a list of fields to compare (excluding the key).
# We can have an attribute self.compare_fields.
pass
Alternatively, we can have the validator define the comparator.
Given the time, let's keep it simple: the UserProfileValidator will have its own compare_records that uses a fixed list of fields.
We'll remove the comparator from the base class and let each validator implement compare_records.
So the base class:
class ConsistencyValidator:
def sample_keys(self):
raise NotImplementedError
def get_expected(self, keys):
raise NotImplementedError
def get_actual(self, keys):
raise NotImplementedError
def compare_records(self, expected, actual):
raise NotImplementedError
def run(self):
keys = self.sample_keys()
if not keys:
return []
expected = self.get_expected(keys)
actual = self.get_actual(keys)
return self.compare_records(expected, actual)
Then UserProfileValidator implements these.
We can also have a helper in the base class for the random sampling.
class RandomSampleMixin:
def sample_keys_random(self, table, filter_condition, sample_size):
query = f"""
SELECT id FROM {table}
WHERE {filter_condition}
ORDER BY RANDOM()
LIMIT {sample_size}
"""
# execute on self.sot_conn? But we might sample from a table in the SOT.
# We'll assume the table is in the SOT.
# We can have the validator specify the table and filter.
# But the filter might be complex and use the max_delay.
# We can have the validator define:
# def get_sample_filter(self):
# return f"updated_at < NOW() - INTERVAL '{self.max_delay} seconds'"
# Then in sample_keys:
# filter_condition = self.get_sample_filter()
# table = self.get_sample_table()
# then use RandomSampleMixin.sample_keys_random(table, filter_condition, self.sample_size)
We can create a mixin for random sampling.
But let's not over-engineer.
We'll implement the UserProfileValidator with the random sampling as above.
We'll assume the SOT connection and RM connection are passed and have a method execute that returns a list of dicts.
We'll also handle the case when the sample_keys returns an empty list.
We'll also handle errors in the queries and log them.
We'll run the validator and return the list of inconsistencies.
We can then have a scheduler that runs the validator and sends alerts.
This is a basic design.
We can extend:
- Add more sampling strategies.
- Add more validators for different read models.
- Add a way to store the results and track over time.
- Add a way to automatically correct? (e.g., by republishing events? or by rebuilding the read model for that entity? That's risky.)
For now, we have a validator that can be extended.
Let's write the code accordingly.
We'll also consider that the SOT and RM might be in different databases, so we use two connections.
We'll assume the connections are DB-API 2.0 compliant (like psycopg2 for PostgreSQL).
We'll write the validator in a way that it can be used with any database that supports SQL.
But note: the query for random sampling uses RANDOM() which is PostgreSQL. For MySQL we use RAND(). We can make the random function configurable.
We can have:
class ConsistencyValidator:
def __init__(self, ..., random_function='RANDOM'):
self.random_function = random_function
def get_random_sample_query(self, table, filter_condition, sample_size):
return f"""
SELECT id FROM {table}
WHERE {filter_condition}
ORDER BY {self.random_function}()
LIMIT {sample_size}
"""
Then in UserProfileValidator:
def sample_keys(self):
filter_condition = f"updated_at < NOW() - INTERVAL '{self.max_delay} seconds'"
query = self.get_random_sample_query('users', filter_condition, self.sample_size)
# execute on self.sot_conn
But note: the table name and filter are specific to the validator.
We can have the validator define:
def get_sample_table(self):
return 'users'
def get_sample_filter(self):
return f"updated_at < NOW() - INTERVAL '{self.max_delay} seconds'"
Then the base class can have a default implementation of sample_keys using these.
Let's adjust:
class ConsistencyValidator:
def __init__(self, sot_conn, rm_conn, sample_size, max_delay_seconds, random_function='RANDOM'):
self.sot_conn = sot_conn
self.rm_conn = rm_conn
self.sample_size = sample_size
self.max_delay = max_delay_seconds
self.random_function = random_function
def get_sample_table(self):
raise NotImplementedError
def get_sample_filter(self):
# default filter by updated_at
return f"updated_at < NOW() - INTERVAL '{self.max_delay} seconds'"
def get_sample_keys_query(self):
table = self.get_sample_table()
filter_condition = self.get_sample_filter()
return f"""
SELECT id FROM {table}
WHERE {filter_condition}
ORDER BY {self.random_function}()
LIMIT {self.sample_size}
"""
def sample_keys(self):
query = self.get_sample_keys_query()
result = self.sot_conn.execute(query)
return [row['id'] for row in result]
# ... other methods as abstract
Then UserProfileValidator:
class UserProfileValidator(ConsistencyValidator):
def get_sample_table(self):
return 'users'
# we can override get_sample_filter if needed, but we use the default.
def get_expected(self, user_ids):
# ... as above
def get_actual(self, user_ids):
# ... as above
def compare_records(self, expected, actual):
# ... as above
This way, we have a reusable base class for random sampling by id.
But note: what if the table doesn't have an 'id' column? We can make the key column configurable.
We can have:
def __init__(..., key_column='id'):
self.key_column = key_column
Then in get_sample_keys_query:
return f"""
SELECT {self.key_column} FROM {table}
...
"""
And then in sample_keys, we return the key_column values.
We can also make the key column configurable per validator.
Let's adjust:
class ConsistencyValidator:
def __init__(self, ..., key_column='id'):
self.key_column = key_column
def get_sample_keys_query(self):
table = self.get_sample_table()
filter_condition = self.get_sample_filter()
return f"""
SELECT {self.key_column} FROM {table}
WHERE {filter_condition}
ORDER BY {self.random_function}()
LIMIT {self.sample_size}
"""
Then in UserProfileValidator, we don't need to change because we are using 'id' and the base class uses self.key_column which defaults to 'id'.
But if we have a table with a different primary key, we can set key_column in the init of the subclass.
We can also have the validator define the key column:
class UserProfileValidator(ConsistencyValidator):
def __init__(self, ...):
super().__init__(..., key_column='user_id') # but the sample table is 'users' and the primary key is 'id'?
# We have to be careful: the sample table's primary key might be named 'id', but in the RM the key is 'user_id'.
Actually, the sample_keys returns the keys from the sample table (which are the user_ids in the users table). Then we use these keys to query the SOT and RM.
In the SOT, the users table has id as primary key, and the RM user_profiles has user_id.
So in the sample, we are getting the user ids (from users.id). Then in get_expected and get_actual, we use the same list of user_ids.
So the key column for the sample table is 'id'. For the RM table, the key column is 'user_id'. That's handled in the get_expected and get_actual by building the queries with the appropriate column.
So the base class's key_column is only for the sample table.
We are good.
Now, we have a base class that can do random sampling from a table in the SOT.
We can extend the base class to support other sampling strategies (like time window) by overriding get_sample_keys_query or get_sample_filter.
We can also have a different mixin for time window sampling.
But let's keep it at that.
We'll now write the complete code for the base class and the UserProfileValidator.
We'll also add error handling and logging.
We'll assume the connections have a method execute that returns a list of dicts (like psycopg2.extras.DictCursor).
If not, we can adjust.
Let's code accordingly.
We'll also consider that the sample might be large and we might want to chunk the queries? But we are sampling a fixed size (e.g., 1000) so it's okay.
We'll write:
import logging
logging.basicConfig(level=logging.INFO)
class ConsistencyValidator:
def __init__(self, sot_conn, rm_conn, sample_size, max_delay_seconds, key_column='id', random_function='RANDOM'):
self.sot_conn = sot_conn
self.rm_conn = rm_conn
self.sample_size = sample_size
self.max_delay = max_delay_seconds
self.key_column = key_column
self.random_function = random_function
def get_sample_table(self):
raise NotImplementedError("Subclasses must implement get_sample_table")
def get_sample_filter(self):
return f"updated_at < NOW() - INTERVAL '{self.max_delay} seconds'"
def get_sample_keys_query(self):
table = self.get_sample_table()
filter_condition = self.get_sample_filter()
return f"""
SELECT {self.key_column} FROM {table}
WHERE {filter_condition}
ORDER BY {self.random_function}()
LIMIT {self.sample_size}
"""
def sample_keys(self):
try:
query = self.get_sample_keys_query()
logging.info(f"Sampling keys with query: {query}")
cursor = self.sot_conn.execute(query)
rows = cursor.fetchall()
keys = [row[self.key_column] for row in rows]
logging.info(f"Sampled {len(keys)} keys")
return keys
except Exception as e:
logging.error(f"Error sampling keys: {e}")
return []
def get_expected(self, keys):
raise NotImplementedError
def get_actual(self, keys):
raise NotImplementedError
def compare_records(self, expected, actual):
raise NotImplementedError
def run(self):
keys = self.sample_keys()
if not keys:
logging.warning("No keys sampled. Skipping validation.")
return []
try:
expected = self.get_expected(keys)
actual = self.get_actual(keys)
inconsistencies = self.compare_records(expected, actual)
return inconsistencies
except Exception as e:
logging.error(f"Error during validation: {e}")
return []
class UserProfileValidator(ConsistencyValidator):
def get_sample_table(self):
return 'users'
def get_expected(self, user_ids):
if not user_ids:
return []
# Query users
user_query = f"""
SELECT id, name, email
FROM users
WHERE id IN ({','.join(map(str, user_ids))})
"""
users = self.sot_conn.execute(user_query).fetchall()
users_by_id = {user['id']: user for user in users}
# Query primary addresses
address_query = f"""
SELECT user_id, street, city
FROM addresses
WHERE user_id IN ({','.join(map(str, user_ids))}) AND is_primary = true
"""
addresses = self.sot_conn.execute(address_query).fetchall()
addresses_by_user_id = {addr['user_id']: addr for addr in addresses}
expected = []
for user_id in user_ids:
user = users_by_id.get(user_id)
if user is None:
continue
address = addresses_by_user_id.get(user_id)
address_str = None
if address:
address_str = f"{address['street']}, {address['city']}"
expected.append({
'user_id': user_id,
'name': user['name'],
'email': user['email'],
'address': address_str
})
return expected
def get_actual(self, user_ids):
if not user_ids:
return []
query = f"""
SELECT user_id, name, email, address
FROM user_profiles
WHERE user_id IN ({','.join(map(str, user_ids))})
"""
return self.rm_conn.execute(query).fetchall()
def compare_records(self, expected, actual):
actual_by_id = {rec['user_id']: rec for rec in actual}
inconsistencies = []
for exp in expected:
user_id = exp['user_id']
act = actual_by_id.get(user_id)
if act is None:
inconsistencies.append({
'user_id': user_id,
'error': 'missing',
'expected': exp,
'actual': None
})
else:
# Compare fields: name, email, address
if (exp['name'] != act['name'] or
exp['email'] != act['email'] or
exp['address'] != act['address']):
inconsistencies.append({
'user_id': user_id,
'error': 'mismatch',
'expected': exp,
'actual': act
})
return inconsistencies
This is a working example.
We can run:
validator = UserProfileValidator(sot_conn, rm_conn, sample_size=100, max_delay_seconds=3600)
result = validator.run()
if result:
for inc in result:
print(inc)
We can also create a Scheduler that runs this periodically.
We can also extend the base class to have a method that runs and reports.
We might want to store the results in a table:
validation_runs:
id, run_at, validator_name, sample_size, inconsistencies_count, etc.
validation_errors:
id, run_id, user_id, error_type, expected, actual
Then we can have a dashboard.
But that's beyond the scope.
This is a basic design for an eventual consistency validator.
We can improve by:
- Using parameterized queries to avoid SQL injection (if the user_ids come from an untrusted source? but we are generating them internally).
- Using a more efficient sampling for large tables (e.g., using TABLESAMPLE or a random id based on min/max).
- Adding more sampling strategies.
- Adding more validators.
- Adding a way to automatically correct (e.g., by rebuilding the read model for the inconsistent entities).
- Adding a way to run the validator on a read replica to avoid load on the primary.
- Adding a way to run the validator in parallel for multiple validators.
- Adding a way to track the history and alert on spikes.
But the above code is a starting point.
I'll design an Eventual Consistency Validator that samples data from read models and compares against the source of truth (SOT). This is crucial for systems with asynchronous replication, CDC pipelines, or materialized views.
Architecture Overview
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Source of │────▶│ Read Model │────▶│ Application │
│ Truth (SOT) │ │ (Denorm/View) │ │ Queries │
└─────────────────┘ └──────────────────┘ └─────────────────┘
▲ │
│ │ Periodic Sampling
│ ▼
┌─────────────────────────────────────────────────────────────┐
│ Consistency Validator │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ 1. Sample from SOT (time-based/random) │ │
│ │ 2. Fetch corresponding from Read Model │ │
│ │ 3. Deep comparison (field-level, structural) │ │
│ │ 4. Metrics & Alerting │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Core Implementation
import time
import random
import logging
from datetime import datetime, timedelta
from typing import List, Dict, Any, Optional, Tuple, Set
from dataclasses import dataclass
from abc import ABC, abstractmethod
import psycopg2 # or your DB driver
from metrics import MetricsCollector # hypothetical metrics library
@dataclass
class ValidationResult:
"""Results of validation for a single entity"""
entity_id: str
entity_type: str
is_consistent: bool
differences: List[Dict[str, Any]]
sot_timestamp: datetime
rm_timestamp: Optional[datetime]
validation_duration_ms: float
@dataclass
class ValidationRunStats:
"""Aggregate statistics for a validation run"""
total_sampled: int
consistent_count: int
inconsistent_count: int
avg_validation_time_ms: float
run_timestamp: datetime
sampling_strategy: str
class Sampler(ABC):
"""Abstract sampling strategy"""
@abstractmethod
def sample_ids(self, cursor, sample_size: int,
min_age_seconds: int = 300) -> List[Tuple[str, str]]:
"""Return list of (entity_type, entity_id) to validate"""
pass
class RandomSampler(Sampler):
"""Random sampling across all entity types"""
def __init__(self, entity_weights: Dict[str, float] = None):
self.entity_weights = entity_weights or {}
def sample_ids(self, cursor, sample_size: int,
min_age_seconds: int = 300) -> List[Tuple[str, str]]:
"""Sample random IDs from SOT tables modified at least X seconds ago"""
cursor.execute("""
SELECT 'user' as entity_type, id::text as entity_id, updated_at
FROM users
WHERE updated_at < NOW() - INTERVAL '%s seconds'
UNION ALL
SELECT 'order' as entity_type, id::text, updated_at
FROM orders
WHERE updated_at < NOW() - INTERVAL '%s seconds'
-- Add other tables
""", (min_age_seconds, min_age_seconds))
candidates = cursor.fetchall()
if not candidates:
return []
# Weighted random sampling if weights provided
if self.entity_weights:
weights = [self.entity_weights.get(row[0], 1.0) for row in candidates]
sampled = random.choices(candidates, weights=weights, k=min(sample_size, len(candidates)))
else:
sampled = random.sample(candidates, min(sample_size, len(candidates)))
return [(row[0], row[1]) for row in sampled]
class TimeWindowSampler(Sampler):
"""Sample from specific time windows (good for catching batch issues)"""
def sample_ids(self, cursor, sample_size: int,
min_age_seconds: int = 300) -> List[Tuple[str, str]]:
# Sample from last hour, 6 hours ago, 24 hours ago
time_windows = [
timedelta(hours=1),
timedelta(hours=6),
timedelta(hours=24)
]
results = []
per_window = max(1, sample_size // len(time_windows))
for window in time_windows:
cursor.execute("""
SELECT 'user' as entity_type, id::text
FROM users
WHERE updated_at BETWEEN NOW() - %s - INTERVAL '1 hour'
AND NOW() - %s
ORDER BY RANDOM()
LIMIT %s
""", (window, window, per_window))
results.extend([(row[0], row[1]) for row in cursor.fetchall()])
return results[:sample_size]
class ConsistencyValidator:
def __init__(
self,
sot_conn_string: str,
rm_conn_string: str,
sampler: Sampler,
sample_size: int = 1000,
min_age_seconds: int = 300, # Minimum age to avoid lag
max_validation_time_ms: int = 5000,
metrics_collector: Optional[MetricsCollector] = None
):
self.sot_conn_string = sot_conn_string
self.rm_conn_string = rm_conn_string
self.sampler = sampler
self.sample_size = sample_size
self.min_age_seconds = min_age_seconds
self.max_validation_time_ms = max_validation_time_ms
self.metrics = metrics_collector or MetricsCollector()
self.logger = logging.getLogger(__name__)
def _get_connections(self):
"""Get database connections (implement for your DB)"""
sot_conn = psycopg2.connect(self.sot_conn_string)
rm_conn = psycopg2.connect(self.rm_conn_string)
return sot_conn, rm_conn
def _fetch_sot_entity(self, cursor, entity_type: str, entity_id: str) -> Optional[Dict]:
"""Fetch complete entity from SOT"""
queries = {
'user': """
SELECT u.*,
a.street, a.city, a.zip as address_zip,
p.phone_number
FROM users u
LEFT JOIN addresses a ON u.id = a.user_id AND a.is_primary = true
LEFT JOIN phones p ON u.id = p.user_id AND p.is_primary = true
WHERE u.id = %s
""",
'order': """
SELECT o.*,
c.name as customer_name,
array_agg(oi.product_id) as product_ids
FROM orders o
LEFT JOIN customers c ON o.customer_id = c.id
LEFT JOIN order_items oi ON o.id = oi.order_id
WHERE o.id = %s
GROUP BY o.id, c.name
"""
}
query = queries.get(entity_type)
if not query:
self.logger.warning(f"No query defined for entity type: {entity_type}")
return None
try:
cursor.execute(query, (entity_id,))
row = cursor.fetchone()
if row:
return dict(row)
except Exception as e:
self.logger.error(f"Error fetching SOT {entity_type} {entity_id}: {e}")
return None
def _fetch_rm_entity(self, cursor, entity_type: str, entity_id: str) -> Optional[Dict]:
"""Fetch entity from read model/denormalized view"""
queries = {
'user': """
SELECT user_id, name, email,
full_address as address,
primary_phone as phone,
updated_at
FROM user_profiles
WHERE user_id = %s
""",
'order': """
SELECT order_id, order_number, total_amount,
customer_name,
product_list,
updated_at
FROM order_summaries
WHERE order_id = %s
"""
}
query = queries.get(entity_type)
if not query:
return None
try:
cursor.execute(query, (entity_id,))
row = cursor.fetchone()
if row:
return dict(row)
except Exception as e:
self.logger.error(f"Error fetching RM {entity_type} {entity_id}: {e}")
return None
def _compare_entities(self, sot: Dict, rm: Dict, entity_type: str) -> List[Dict]:
"""Deep comparison between SOT and RM entities"""
differences = []
# Define comparison rules per entity type
comparison_rules = {
'user': {
'fields': ['name', 'email', 'address', 'phone'],
'normalizers': {
'address': lambda x: x.strip().lower() if x else x,
'email': lambda x: x.strip().lower() if x else x
}
},
'order': {
'fields': ['order_number', 'total_amount', 'customer_name', 'product_ids'],
'normalizers': {
'customer_name': lambda x: x.strip().lower() if x else x,
'product_ids': lambda x: sorted(x) if isinstance(x, list) else x
}
}
}
rules = comparison_rules.get(entity_type, {'fields': []})
for field in rules['fields']:
sot_val = sot.get(field)
rm_val = rm.get(field)
# Apply normalizer if exists
normalizer = rules.get('normalizers', {}).get(field, lambda x: x)
sot_norm = normalizer(sot_val)
rm_norm = normalizer(rm_val)
if sot_norm != rm_norm:
differences.append({
'field': field,
'sot_value': sot_val,
'rm_value': rm_val,
'sot_normalized': sot_norm,
'rm_normalized': rm_norm
})
# Check timestamp consistency (RM shouldn't be newer than SOT)
if 'updated_at' in sot and 'updated_at' in rm:
if rm['updated_at'] > sot['updated_at'] + timedelta(seconds=30):
differences.append({
'field': 'updated_at',
'sot_value': sot['updated_at'],
'rm_value': rm['updated_at'],
'issue': 'RM timestamp ahead of SOT'
})
return differences
def run_validation(self) -> ValidationRunStats:
"""Main validation orchestration"""
start_time = time.time()
sot_conn, rm_conn = self._get_connections()
inconsistencies = []
validation_times = []
try:
# 1. Sample entities to validate
sample_start = time.time()
sample = self.sampler.sample_ids(
sot_conn.cursor(),
self.sample_size,
self.min_age_seconds
)
sample_time = (time.time() - sample_start) * 1000
self.logger.info(f"Sampled {len(sample)} entities in {sample_time:.2f}ms")
# 2. Validate each entity
for entity_type, entity_id in sample:
entity_start = time.time()
try:
# Fetch from both sources
sot_entity = self._fetch_sot_entity(sot_conn.cursor(), entity_type, entity_id)
rm_entity = self._fetch_rm_entity(rm_conn.cursor(), entity_type, entity_id)
if not sot_entity:
self.logger.warning(f"SOT entity missing: {entity_type}/{entity_id}")
continue
# Compare
differences = self._compare_entities(sot_entity, rm_entity or {}, entity_type)
result = ValidationResult(
entity_id=entity_id,
entity_type=entity_type,
is_consistent=len(differences) == 0,
differences=differences,
sot_timestamp=sot_entity.get('updated_at'),
rm_timestamp=rm_entity.get('updated_at') if rm_entity else None,
validation_duration_ms=(time.time() - entity_start) * 1000
)
if not result.is_consistent:
inconsistencies.append(result)
validation_times.append(result.validation_duration_ms)
except Exception as e:
self.logger.error(f"Error validating {entity_type}/{entity_id}: {e}")
validation_times.append(time.time() - entity_start)
# 3. Calculate statistics
total_time = time.time() - start_time
avg_time = sum(validation_times) / len(validation_times) if validation_times else 0
stats = ValidationRunStats(
total_sampled=len(sample),
consistent_count=len(sample) - len(inconsistencies),
inconsistent_count=len(inconsistencies),
avg_validation_time_ms=avg_time,
run_timestamp=datetime.utcnow(),
sampling_strategy=type(self.sampler).__name__
)
# 4. Emit metrics
self._emit_metrics(stats, inconsistencies, sample_time)
# 5. Log summary
self.logger.info(
f"Validation complete: {stats.consistent_count}/{stats.total_sampled} consistent "
f"({stats.inconsistent_count} inconsistent). "
f"Avg time: {avg_time:.2f}ms"
)
# 6. Persist results (optional)
self._persist_results(stats, inconsistencies)
return stats
finally:
sot_conn.close()
rm_conn.close()
def _emit_metrics(self, stats: ValidationRunStats,
inconsistencies: List[ValidationResult], sample_time: float):
"""Emit metrics to monitoring system"""
tags = {'sampler': stats.sampling_strategy}
self.metrics.gauge('consistency_validator.sample_time_ms', sample_time, tags)
self.metrics.gauge('consistency_validator.avg_validation_time_ms',
stats.avg_validation_time_ms, tags)
self.metrics.gauge('consistency_validator.inconsistency_rate',
stats.inconsistent_count / max(1, stats.total_sampled), tags)
self.metrics.gauge('consistency_validator.sample_size', stats.total_sampled, tags)
# Track specific error patterns
error_patterns = {}
for inc in inconsistencies:
for diff in inc.differences:
pattern = f"{inc.entity_type}.{diff['field']}"
error_patterns[pattern] = error_patterns.get(pattern, 0) + 1
for pattern, count in error_patterns.items():
self.metrics.gauge(f'consistency_validator.error.{pattern}', count, tags)
def _persist_results(self, stats: ValidationRunStats,
inconsistencies: List[ValidationResult]):
"""Store validation results for audit/trend analysis"""
# Implementation depends on your storage (PostgreSQL, S3, etc.)
pass
class AlertingRule:
"""Define conditions for alerts"""
def __init__(self,
inconsistency_rate_threshold: float = 0.01,
consecutive_failures: int = 3,
specific_errors: List[str] = None):
self.inconsistency_rate_threshold = inconsistency_rate_threshold
self.consecutive_failures = consecutive_failures
self.specific_errors = specific_errors or []
self.failure_counter = 0
def should_alert(self, stats: ValidationRunStats,
inconsistencies: List[ValidationResult]) -> bool:
# Check inconsistency rate
rate = stats.inconsistent_count / max(1, stats.total_sampled)
if rate >= self.inconsistency_rate_threshold:
return True
# Check for specific critical errors
for inc in inconsistencies:
for diff in inc.differences:
field_path = f"{inc.entity_type}.{diff['field']}"
if field_path in self.specific_errors:
return True
# Check consecutive failures
if stats.inconsistent_count > 0:
self.failure_counter += 1
if self.failure_counter >= self.consecutive_failures:
return True
else:
self.failure_counter = 0
return False
# Usage Example
def main():
# Configure logging
logging.basicConfig(level=logging.INFO)
# Initialize validator
validator = ConsistencyValidator(
sot_conn_string="postgresql://sot_user:pass@sot-db:5432/main",
rm_conn_string="postgresql://rm_user:pass@rm-db:5432/main",
sampler=RandomSampler(entity_weights={'user': 0.7, 'order': 0.3}),
sample_size=500,
min_age_seconds=600 # Only validate data >10min old to avoid lag
)
# Run validation
stats = validator.run_validation()
# Check if we should alert
alert_rule = AlertingRule(
inconsistency_rate_threshold=0.02, # 2% inconsistency rate
specific_errors=['user.email', 'order.total_amount'],
consecutive_failures=2
)
if alert_rule.should_alert(stats, []): # Pass inconsistencies if needed for specific errors
send_alert(f"Consistency validation failed: {stats.inconsistent_count}/{stats.total_sampled} inconsistent")
Advanced Features to Add
1. Delta Encoding for Efficient Comparison
class DeltaEncoder:
"""Store only changed fields to reduce payload size"""
def encode_entity(self, entity: Dict, previous_version: Dict) -> Dict:
delta = {}
for key, value in entity.items():
if key not in previous_version or previous_version[key] != value:
delta[key] = value
return delta
2. Statistical Sampling Strategies
class StratifiedSampler(Sampler):
"""Stratified sampling across entity states"""
def sample_ids(self, cursor, sample_size: int, **kwargs) -> List[Tuple[str, str]]:
# Sample proportionally from:
# - Recently created (0-1 hour)
# - Modified (1-24 hours)
# - Stable (>24 hours)
pass
3. Lag Detection
def detect_lag(sot_timestamp: datetime, rm_timestamp: datetime) -> timedelta:
"""Calculate replication lag between SOT and RM"""
if not rm_timestamp:
return timedelta.max
return sot_timestamp - rm_timestamp
4. Batch Processing for Large Datasets
def validate_in_batches(self, batch_size: int = 1000):
"""Validate large datasets in batches to avoid memory issues"""
offset = 0
while True:
batch = self._get_batch(offset, batch_size)
if not batch:
break
self._validate_batch(batch)
offset += batch_size
5. Self-Healing (Optional, Risky)
def auto_repair(self, inconsistencies: List[ValidationResult]):
"""Attempt to self-heal by re-publishing events or rebuilding"""
for inc in inconsistencies:
if self._can_auto_repair(inc):
self._replay_events(inc.entity_type, inc.entity_id)
Deployment Considerations
Scheduling
# Kubernetes CronJob
apiVersion: batch/v1
kind: CronJob
spec:
schedule: "0 */6 * * *" # Every 6 hours
jobTemplate:
spec:
template:
spec:
containers:
- name: consistency-validator
image: validator:latest
resources:
limits:
memory: "512Mi"
cpu: "500m"
Configuration via Environment
import os
class Config:
SAMPLE_SIZE = int(os.getenv('VALIDATION_SAMPLE_SIZE', '1000'))
MIN_AGE_SECONDS = int(os.getenv('VALIDATION_MIN_AGE', '300'))
DB_TIMEOUT = int(os.getenv('DB_TIMEOUT', '30'))
ALERT_WEBHOOK = os.getenv('ALERT_WEBHOOK')
Observability
-
Metrics to Track:
consistency.validation.duration
consistency.inconsistency.count
consistency.sample.lag.seconds
consistency.entity.validation.time.{entity_type}
-
Logging:
- Log each inconsistency with context
- Create audit trail of validation runs
-
Dashboards:
- Inconsistency rate over time
- Lag distribution
- Top inconsistent fields/entities
Best Practices
-
Start Conservative:
- Begin with small sample sizes (100-1000)
- Validate only critical entities first
- Use higher
min_age_seconds initially
-
Sample Wisely:
- Focus on high-traffic/high-value entities
- Include edge cases (NULLs, special characters)
- Seasonally adjust sampling (holiday traffic patterns)
-
Comparison Strategy:
- Normalize data (trim whitespace, case sensitivity)
- Handle NULL semantics correctly
- Consider numerical precision (floating point, decimals)
- Ignore non-deterministic fields (timestamps within delta)
-
Error Handling:
- Always validate validator itself (sanity checks)
- Timebox individual entity validation
- Continue validation on individual failures
- Retry transient failures
-
Alert Fatigue Prevention:
- Use incremental alerts (only new issues)
- Auto-close resolved issues after N successful runs
- Differentiate between transient vs persistent issues
When to Run
- Scheduled: During low-traffic periods
- Post-Deployment: After read model changes
- On-Demand: When anomalies detected
- Canary Validation: Validate new deployment against old SOT
Limitations & Trade-offs
| Aspect | Trade-off |
|---|
| Sample Size | Larger = more accurate but more load |
| Min Age | Higher = less lag-sensitive but misses recent issues |
| Validation Depth | Deep comparison = thorough but slower |
| Frequency | More frequent = faster detection but more DB load |
This validator provides statistical confidence rather than 100% verification. For critical data, you might need:
- 100% validation for recently modified records
- Cryptographic hashing for bulk comparison
- Change Data Capture (CDC) comparison instead of point-in-time
Would you like me to elaborate on any specific aspect, such as:
- Implementing for a specific data model (e.g., e-commerce, social network)?
- Integrating with specific monitoring systems (Prometheus, Datadog)?
- Handling specific edge cases (deleted records, soft deletes, temporal data)?