1. Understand the Goal: The user wants a design for a "read-replica lag-aware routing layer." This implies a system that sits between a client and a database cluster (primary + replicas) and intelligently routes read requests based on how much the replicas are lagging behind the primary.
code
Key components mentioned in the prompt:
* Staleness budgets (how old is too old?).
* Consistency hints (client requirements).
* Retry policies (what to do when things fail or lag is too high).
* Observability (how to see what's happening).
2. High-Level Architecture:
* Client: Sends queries.
* Routing Layer (The Proxy/Middleware): The core component. It needs to intercept queries, check state, and route.
* Database Cluster: Primary (Writes) + Replicas (Reads).
* State Store/Monitor: The routing layer needs to know the current lag. It can poll the DB or ingest metrics.
Component Deep Dive:
Staleness Budget (The "Why"):
Concept: Maximum time/transaction difference allowed for a read.
Implementation: Client specifies a header or query comment (e.g., max_staleness_ms=500). If replica lag > 500ms, go to Primary.
Consistency Hints (The "What"):
Concept: Clients sometimes need "read-your-writes" or strict linearizability.
Types:
PRIMARY_ONLY: Critical reads (e.g., verifying a password).
CAUSAL (Read-your-writes): Needs to track session tokens/scatter-gather logic (might be too complex for a general prompt, keep it simple: "High Consistency" vs "Eventual").
EVENTUAL (Default): Route to replicas.
Mechanism: "Sticky sessions" or passing timestamps (e.g., read_at_or_after_timestamp).
Refining the content (Self-Correction during drafting):
Initial thought: Just use Seconds_Behind_Master.
Correction: That's imprecise. For a robust design, mention LSN (Log Sequence Number) or GTID (Global Transaction ID) comparisons if using Postgres/MySQL. It's more accurate to say "Time-based budget" maps to "LSN distance."
Read-After-Write: This is tricky. How does the proxy know I just wrote? Ideally, the client sends back a token received from the write, or we track the session. Let's propose a "Session Causal Token" approach (e.g., passing the latest commit_timestamp).
Fallback Logic: If all replicas violate the budget, should we error or hit the Primary? Hitting the Primary protects availability but might overload the primary. Overloading the primary is usually better than user-facing errors, unless the primary is the bottleneck. Let's suggest "Route to Primary with Circuit Breaker" as the fallback.
Final Polish: Use clear headings, code-like blocks for configuration/pseudocode, and bullet points for readability. (Drafting the actual response structure now).
Title: Read-Replica Lag-Aware Routing Layer
Sections:
High-Level Architecture
Metadata & State Management (The "Brain")
Routing Logic (The "Decision")
Client Contract (Budgets & Hints)
Resilience & Retries
Observability
Executing the content generation: (This aligns with the detailed output provided previously). I will ensure I cover specific technologies like HAProxy/pgBouncer concepts but abstracted for a general design.
Specific Detail: Mention "Time Travel" queries (Snowflake/CRDB style) as an alternative, but stick to the standard Primary-Replica model for this prompt.
Specific Detail: Handling "Thundering Herd" on Primary fallback. If a replica lags, everyone hits primary. Solution: Probabilistic fallback or rate limiting fallbacks.
Final Review against prompt:
Staleness budgets? Yes.
Consistency hints? Yes.
Retry policies? Yes.
Observability? Yes.
This looks solid. Proceeding to generate output.
Designing a lag-aware routing layer requires moving beyond simple Round-Robin load balancing. We need a stateful proxy that understands the database topology, the replication timeline, and the client's tolerance for stale data.
Below is a comprehensive design for the "Chronos Proxy."
1. High-Level Architecture
The routing layer sits between the application (clients) and the database cluster. It consists of three logical sub-components:
The Health/Lag Aggregator: Periodically polls replicas to calculate replication lag.
The Policy Engine: Matches incoming queries against consistency requirements.
The Connection Pooler & Router: Routes traffic and manages retries.
Client sends subsequent SELECT with hint min_commit_time: T1.
Router Logic: The router selects a replica only if Replica_Last_Applied_Timestamp >= T1.
If the replica is behind T1, the router either waits (blocking wait) or falls back to the Primary.
B. Session Stickiness (Sticky Sessions)
Hint:session_id: xyz
Logic: Cache the route for this session ID for N seconds. This guarantees monotonic reads (you don't see time go backwards) within a user session, even if lag varies between replicas.
5. Retry Policies & Fallback Strategies
What happens when a replica is lagging beyond the budget?
The "Fail-Open" vs. "Fail-Closed" Policy
Strict (Fail-Closed): If Replica_Lag > Budget, return Error 503 Service Unavailable or Staleness Violation. Use this for financial data where stale data is worse than no data.
Relaxed (Fail-Open): If Replica_Lag > Budget, fall back to the Primary.
Risk: This can cause "thundering herd" on the Primary if all replicas lag simultaneously.
Mitigation: Use Probabilistic Fallback. If 3 replicas are lagging, only 30% of read requests hit the Primary; the rest return slightly stale data or error.
Adaptive Retries
If a replica is selected but the query times out or returns a replication error:
Retry 1: Immediately retry on a different replica (if available).
Retry 2: Retry on the Primary (if consistency hint allows).
6. Observability (The Dashboard)
You cannot route what you cannot measure. The routing layer must expose specific metrics.
Key Metrics (Prometheus/Datadog)
replication_lag_seconds (gauge): Per replica.
staleness_budget_violations_total (counter): How often a replica was rejected because it was too slow.
routing_target_count (counter): Splits by target="primary" vs target="replica".
SLO Alert: If routing_target_count{primary} / total > 20%, your read-scaling is failing.
routing_latency_approximation (histogram): The difference between Query_Issued_At and Commit_Time_of_Data_Returned (requires DB support).