The user wants an "Eventual Consistency Validator" (ECV).
This system needs to:
- Compare "domain read models" (likely projections in a CQRS or Event Sourcing architecture) against a "source of truth" (likely the event store or a canonical state derived from events).
- Use "sampling" (meaning it shouldn't re-compute everything, just a subset to check consistency).
- Support "eventual consistency" (acknowledging that there is a lag between a write and the read model update).
Core Components:
- Source of Truth (SoT): The canonical data. In an ES/CQRS system, this is usually the Event Store or a snapshot + events. For the validator, I need a way to fetch the current state of an entity based on the latest events.
- Read Model (RM): The denormalized view used for queries. This could be a SQL table, a Redis hash, a document in Mongo, etc.
- Sampler: Logic to select which entities to check.
- Random Sampling: Good for general health.
- Hot Spot Sampling: Check frequently accessed items.
- Recent Writes Sampling: Check items that just changed (this is tricky with eventual consistency, need a grace period).
- Comparator: Logic to compare the SoT state with the RM state. Needs to handle semantic equivalence (e.g., date formats, null vs missing).
- Scheduler/Runner: Triggers the validation runs.
- Reporter/Alarmer: What happens when they don't match? Logging, metrics, alerts.
Technical Challenges & Considerations:
- Lag (The "Eventual" part): If I write an event at T=0, the read model might update at T=0.5s. If the validator checks at T=0.1s, it will report a false positive.
- Solution: The validator needs to know the "last updated" timestamp or a version number. If the RM is "older" than the SoT but within the acceptable lag window (e.g., 5 seconds), ignore it. If it's older than the window or the data is different despite having the same version, it's a corruption.
- Performance: Reconstructing state from events (SoT) is expensive.
- Solution: Maybe the SoT isn't the event stream itself, but a "Ledger" or "Master Table" that is strictly consistent, while the Read Models are derived. Let's assume a standard CQRS setup where we replay events or query a strict-consistency DB.
- Sampling Strategy: Naive random sampling might miss specific bugs in edge cases. Stratified sampling is better.
Architecture Design:
I will propose a modular architecture.
- Input: A stream of IDs to validate.
- Process:
- Select ID: From the pool.
- Fetch SoT: Calculate state from events or fetch from Master DB.
- Fetch RM: Fetch from the specific Read Model DB.
- Compare:
- Check version/timestamp alignment (Lag vs Corruption).
- Check field equality.
- Act: Metric emission / Repair trigger.
Code Structure (Python or TypeScript/Go):
Let's go with Python for readability and generic data structure manipulation, or Go for system engineering. Python is often easier for "scripts" but Go is better for services. Let's stick to a generic Python structure that looks like production-grade code.
Refining the "Lag" Problem:
This is the most critical part.
- Scenario A: SoT has version 100. RM has version 100. Data matches. -> OK.
- Scenario B: SoT has version 101. RM has version 100. -> Lag (Ignore if within threshold, Alert if stale).
- Scenario C: SoT has version 100. RM has version 100. Data mismatch. -> CORRUPTION (Critical Alert).
- Scenario D: SoT has version 100. RM has version 101. -> Ghost Write/Phantom (Critical Alert).
Repair Mechanism:
The validator shouldn't just complain; it should ideally trigger a re-projection for that specific ID.
Drafting the implementation details:
-
Interfaces:
Sampler: get_sample_ids(batch_size)
SourceOfTruth: get_canonical_state(id)
ReadModel: get_projection_state(id)
Validator: compare(canonical, projection)
-
Implementation details:
- I'll use
asyncio because DB calls are IO bound.
- I'll simulate the "Source of Truth" as a function that aggregates events.
- I'll simulate the "Read Model" as a dictionary/DB lookup.
-
Metrics:
consistency_check_total
consistency_check_lag_seconds
consistency_check_corruption_total
Step-by-Step Output Generation:
- High-Level Architecture: Explain the flow.
- The "Grace Period" Strategy: Explain how to distinguish between "slow" and "broken".
- Code Implementation: Python classes.
- Define Data Classes (State).
- Define the strategy for Lag vs. Error.
- The main loop.
- Self-Healing: How to hook in a repair mechanism.
- Operational concerns: Sampling methods (Random vs. Weighted).
Self-Correction during drafting:
Initial thought: Just query the DBs.
Correction: The "Source of Truth" in CQRS is often the Event Store. Replaying events for every sample is too heavy.
Pivot: The validator often works best if there is a "Current State Table" (Strict Consistency) alongside the Event Store, or if the validator only checks a small % of traffic. Or, simpler: The user asks for a "validator", not a re-builder. I will implement an abstract SourceOfTruthProvider and mention that in reality, this might need Snapshots to be performant.
Let's refine the "Lag" logic.
We need a max_lag_tolerance config.
If so_t.timestamp - rm.timestamp > max_lag, it's an error.
If rm.timestamp > so_t.timestamp, it's an error (ghost write).
If abs(diff) < max_lag AND data differs -> Error.
If abs(diff) < max_lag AND data same -> OK.
Wait, if abs(diff) < max_lag, we expect them to be different if SoT is newer.
So:
- If timestamps match (within small delta) and data differs -> Data Corruption.
- If SoT is newer than RM by more than
max_lag -> Stale/Timeout Error.
- If SoT is newer than RM by less than
max_lag -> Skip (Acceptable Lag).
Let's write the code.
- Language: Python (Type hinted).
- Libraries:
asyncio, pydantic (optional but good for structure), dataclasses. I'll stick to standard library + dataclasses to be self-contained.
Sampling Strategy:
I'll implement a WeightedRandomSampler that prioritizes recent writes (higher chance of race conditions) but also samples old data (bit rot).
Final Polish: Add a "Repair Queue" concept.
Let's structure the answer:
- Architecture Overview (The "Why" and "How").
- The Core Logic (Lag vs. Corruption).
- Python Implementation.
- Deployment & Integration Guide.
(Self-Correction on Code): Make sure to handle the case where the ID doesn't exist in Read Model but exists in SoT (Missing Projection) and vice versa (Phantom Projection).
Let's proceed.
This solution designs an Eventual Consistency Validator (ECV), a critical component in Distributed Systems (specifically CQRS/Event Sourcing architectures).
The core challenge is verifying that a Read Model (Projection) matches the Source of Truth (Event Store) without incurring the performance cost of recalculating the entire state for every check.
Architecture Overview
- The Strategy (Sampling): We cannot check every entity. We use a Weighted Random Sampler. It prioritizes:
- Recency: Entities changed recently (higher chance of temporary inconsistency).
- Risk: Entities with a history of failed validations.
- Random: A baseline to detect systematic drift.
- The Comparison Logic:
- Reconstruct the expected state from the Event Store (Source of Truth).
- Fetch the current state from the Read Database.
- Compare Version & Hash/Payload.
- The Tolerance Window: Since the system is "Eventual," a mismatch is only an error if the Read Model remains stale beyond a configured threshold (e.g., 5 seconds).
Python Implementation
This implementation uses asyncio to simulate concurrent validation and standard Python libraries.
1. Data Structures & Interfaces
First, we define the shape of our data and the abstract interfaces for our databases.
import asyncio
import random
import time
import hashlib
import json
from dataclasses import dataclass, field
from typing import List, Dict, Any, Optional
from datetime import datetime, timedelta
# --- Domain Objects ---
@dataclass
class DomainEvent:
type: str
payload: Dict[str, Any]
timestamp: float
@dataclass
class EntityState:
"""
The calculated state of an entity.
In a real app, this might be an Order, User, or InventoryItem.
"""
id: str
version: int
data_hash: str # A hash of the business logic state
last_updated: float
# --- Interfaces ---
class SourceOfTruth:
"""
Abstracts the Event Store.
Responsibility: Replaying events to build current state.
"""
async def get_current_state(self, entity_id: str) -> Optional[EntityState]:
# 1. Fetch all events for entity_id
# 2. Replay them to calculate state
# 3. Return state
raise NotImplementedError
class ReadModel:
"""
Abstracts the Query Database (e.g., Postgres, Elastic, Redis).
Responsibility: Fetching the projected view.
"""
async def get_projected_state(self, entity_id: str) -> Optional[EntityState]:
raise NotImplementedError
class MetricsService:
"""
Handles reporting of failures.
"""
def report_consistency_failure(self, entity_id: str, details: Dict):
print(f"[ALERT] Consistency Failure for {entity_id}: {details}")
def report_consistency_success(self, entity_id: str):
pass # Optionally log success
2. The Sampling Strategy
We don't just pick random IDs. We want to prioritize "hot" items (recently updated) because that is where eventual consistency latency is most likely to be confused with actual data corruption.
class WeightedSampler:
"""
Selects IDs for validation.
Favors IDs that have been updated recently to catch sync issues.
"""
def __init__(self, recent_update_stream: List[str], historical_pool: List[str]):
self.recent = recent_update_stream
self.pool = historical_pool
def get_batch(self, batch_size: int) -> List[str]:
selected = []
# Strategy:
# 70% chance to pick from 'recent' (last hour updates)
# 30% chance to pick from 'historical' (cold data)
for _ in range(batch_size):
if random.random() < 0.7 and self.recent:
selected.append(random.choice(self.recent))
elif self.pool:
selected.append(random.choice(self.pool))
elif self.recent: # Fallback if pool empty
selected.append(random.choice(self.recent))
return list(set(selected)) # Remove duplicates
3. The Validator Core
This is the engine that performs the actual comparison. It handles the "Grace Period" logic—allowing the Read Model a few seconds to catch up before flagging an error.
class ConsistencyValidator:
def __init__(
self,
source_of_truth: SourceOfTruth,
read_model: ReadModel,
metrics: MetricsService,
consistency_lag_threshold_sec: float = 5.0
):
self.sot = source_of_truth
self.rm = read_model
self.metrics = metrics
self.lag_threshold = consistency_lag_threshold_sec
async def validate_entity(self, entity_id: str):
"""
Core validation logic for a single entity.
"""
# 1. Fetch Source of Truth (Synchronous view)
# In a real scenario, this involves replaying events.
true_state = await self.sot.get_current_state(entity_id)
# 2. Fetch Read Model (Asynchronous view)
projected_state = await self.rm.get_projected_state(entity_id)
# Case A: Missing Data
if true_state is None and projected_state is not None:
# Tombstone issue: SOT deleted, RM still has data
self.metrics.report_consistency_failure(entity_id, {
"error": "Ghost Projection (Exists in RM but not SOT)"
})
return
if true_state is not None and projected_state is None:
# Projection lag or failure
# We only alert if the entity was created "long ago"
age = time.time() - true_state.last_updated
if age > self.lag_threshold:
self.metrics.report_consistency_failure(entity_id, {
"error": "Missing Projection (Exists in SOT but not RM)",
"age_sec": age
})
return
# Case B: Version Mismatch (Expected in Eventual Consistency)
if true_state.version != projected_state.version:
# Calculate time delta
time_lag = true_state.last_updated - projected_state.last_updated
# If the True State is significantly newer than the Projected State,
# and the gap exceeds our threshold, it's a failure.
if time_lag > self.lag_threshold:
self.metrics.report_consistency_failure(entity_id, {
"error": "Stale Version",
"sot_version": true_state.version,
"rm_version": projected_state.version,
"lag_sec": time_lag
})
# Else: This is just natural latency, ignore.
return
# Case C: Version Match but Content Mismatch (Corruption)
# This is the most dangerous case: The counter says "5", but the data
# in the Read Model is actually for "4" or is malformed.
if true_state.data_hash != projected_state.data_hash:
self.metrics.report_consistency_failure(entity_id, {
"error": "Data Corruption",
"message": "Versions match but content hashes differ!"
})
return
self.metrics.report_consistency_success(entity_id)
4. Simulation / Mock Implementation
Here we wire it all together with a mock implementation to demonstrate how the system runs.
# --- Mock Implementations for Demonstration ---
class MockEventStore(SourceOfTruth):
def __init__(self):
# Simulating a DB of events
self.db = {
"order-1": [
{"type": "Created", "payload": {"val": 10}, "ts": 1.0},
{"type": "Updated", "payload": {"val": 20}, "ts": 2.0}
],
"order-2": [
{"type": "Created", "payload": {"val": 5}, "ts": 1.5}
],
# order-3 is a "Ghost" in the Read Model (deleted in SOT)
"order-3": []
}
async def get_current_state(self, entity_id: str) -> Optional[EntityState]:
events = self.db.get(entity_id, [])
if not events:
return None
# Simple "Replay" logic
final_val = 0
for e in events:
if e['type'] == 'Created': final_val = e['payload']['val']
if e['type'] == 'Updated': final_val = e['payload']['val']
last_ts = events[-1]['ts']
# Generate deterministic hash based on final value
state_hash = hashlib.md5(json.dumps({"val": final_val}).encode()).hexdigest()
return EntityState(
id=entity_id,
version=len(events),
data_hash=state_hash,
last_updated=last_ts
)
class MockReadDB(ReadModel):
def __init__(self):
# Simulating a Read Table
self.projections = {
"order-1": {"version": 2, "hash": hashlib.md5(json.dumps({"val": 20}).encode()).hexdigest(), "ts": 2.0}, # Consistent
"order-2": {"version": 1, "hash": hashlib.md5(json.dumps({"val": 5}).encode()).hexdigest(), "ts": 1.5}, # Consistent
"order-3": {"version": 1, "hash": "some_hash", "ts": 1.0} # Ghost (Deleted in SOT)
}
async def get_projected_state(self, entity_id: str) -> Optional[EntityState]:
proj = self.projections.get(entity_id)
if not proj:
return None
return EntityState(
id=entity_id,
version=proj['version'],
data_hash=proj['hash'],
last_updated=proj['ts']
)
# --- Main Execution ---
async def main():
# Setup
event_store = MockEventStore()
read_db = MockReadDB()
metrics = MetricsService()
validator = ConsistencyValidator(event_store, read_db, metrics)
# Create a sampler with some "Hot" IDs and some "Cold" IDs
sampler = WeightedSampler(
recent_update_stream=["order-1", "order-2"], # These changed recently
historical_pool=["order-3", "order-4"] # order-4 doesn't exist anywhere
)
print("--- Starting Validation Run ---")
# Run 5 validation checks
ids_to_check = sampler.get_batch(5)
tasks = [validator.validate_entity(id) for id in ids_to_check]
await asyncio.gather(*tasks)
print("--- Run Complete ---")
if __name__ == "__main__":
asyncio.run(main())
Engineering Considerations for Production
-
Replay Cost Optimization:
Replaying events for every sample is expensive. In a high-throughput system, do not query the raw Event Store for every validation.
- Optimization: Use a Snapshot Store. If your system takes snapshots (e.g., every 100 events), load the snapshot and only replay the delta.
-
Handling High Latency:
If your system naturally has 10 seconds of lag, setting the threshold to 10s might mask actual bugs.
- Solution: Use a Dynamic Threshold. If
current_time - event_commit_time < avg_lag * 3, mark as "Pending" and re-check later. Only alert if it remains "Pending" for multiple cycles.
-
Self-Healing:
When the validator detects a permanent mismatch, it shouldn't just alert. It should publish a Reconciliation Event (e.g., InconsistencyDetected { entity_id }) which triggers a background worker to re-project that specific entity.
-
Sampling Bias:
Ensure your sampler isn't just picking IDs that are easy to find. It should sample across different shards or partitions of your database to detect partition-specific failures.