We are asked: "Design a read-replica lag-aware routing layer: staleness budgets, consistency hints, retry policies, and observability."
This is a typical system design interview question. The task is to design a read-replica lag-aware routing layer. This is about handling read traffic to a primary database and its replicas, taking into account the replication lag (staleness) of replicas, to provide a balance between load, performance, and data freshness.
We need to cover:
Staleness budgets: the maximum allowed staleness (replication lag) for a request, possibly based on user or application requirements.
Consistency hints: maybe ways for the client to indicate desired consistency level (e.g., read-after-write consistency, linearizability, eventual consistency, etc.)
Retry policies: how to handle failures, including when a replica is too stale, or errors.
Observability: metrics, logging, tracing, monitoring of replication lag and routing decisions.
We should produce a detailed design.
Let's structure:
Problem Statement: What is read-replica lag? Why routing layer? Need to direct reads to appropriate replicas based on staleness requirements, while balancing load and ensuring high availability.
System Overview:
Primary DB (writes only) and multiple read replicas (asynchronous replication).
Replication lag: time since last update on primary that the replica has applied. Varies per replica.
Routing layer sits between clients and DB replicas (or as part of a proxy/load balancer).
Goal: For each read request, route to a replica that satisfies the staleness budget (maximum allowed lag) if possible. If no replica meets the budget, either route to primary or fail based on policy. Also, handle failures and retries.
Components:
Replica Lag Monitor: collects replication lag metrics for each replica (e.g., using timestamps, LSN, or heartbeat).
Router: receives read requests with optional consistency hint/staleness budget; decides which replica (or primary) to send request to.
Client API / SDK: allows clients to specify staleness budget or consistency hint.
Configuration: global defaults, per-client/request overrides.
Retry Handler: deals with errors, including stale data (if detected) and replica failures.
Observability Stack: logging, metrics, tracing.
Staleness Budgets:
Definition: maximum acceptable replication lag (in time, e.g., seconds, or perhaps in terms of logical sequence numbers).
Granularity: per request, per user, per endpoint. Could be a default set at system level.
Budget units: time-based (e.g., 5 seconds) or txn-based (e.g., "read your writes"): may need to track write timestamps per user session; could be complex.
Simplify: time-based budgets are easier. For read-after-write, we may need to localize to primary for that user's writes, or use a token that indicates minimum LSN.
Option: Use "session consistency" where if a client performs a write, we note the replication position (e.g., last committed LSN on primary) and then for reads from that client we require the replica to have advanced beyond that LSN (or within time budget). That's typical for "read your writes".
Implementation: Router checks the current lag of each replica (lag = time since primary's last change that replica hasn't applied yet). If a replica's lag <= budget, it's eligible. Among eligible, choose one (maybe random or least loaded). If none eligible, fallback to primary (if write-after-read not needed) or error.
Could also support "strong consistency" (always read from primary) by setting budget=0.
Consistency Hints:
Types:
EVENTUAL: high staleness budget, any replica.
BOUNDED_STALENESS: specify max lag.
READ_YOUR_WRITES: per-session guarantee. Could be implemented by associating a "last write timestamp" with the client/session and requiring replica's last applied time >= that timestamp.
MONOTONIC_READS: ensure successive reads from same client see non-decreasing data. Could be handled by caching the LSN of last read and requiring next read from replica that has at least that LSN.
LINEARIZABLE/STRONG: always read from primary (budget=0 and maybe also use read locks? But for routing, just route to primary).
The routing layer may provide a way to set these hints on a request. The hints might be translated to a staleness budget (time or LSN) or to a specific routing rule.
Retry Policies:
Errors: replica down, network errors, replica too stale (if we check after getting response? Possibly we need to check pre-read).
Pre-read check: we can decide based on lag measurement. If we pick a replica and it's down, retry on another replica (maybe primary if budget not strict). If we pick a replica that is within lag but then on read we detect stale data (maybe not possible unless we have version vectors), we may need to retry.
Actually, we typically decide based on lag metrics. So we don't read from a replica that is considered too stale. But what if the replica lags increases after we selected but before request? That's a race. Could handle by adding a short timeout and if request fails due to error (like duplicate key? Not relevant) maybe retry with higher priority (primary). Or we could have the replica itself check staleness and reject if too stale (some DBs have read-only transactions that can check). But typical: use a load balancer that chooses based on metrics; if a replica becomes too slow or overloaded, we route away.
Retry strategy: For read errors (connection failures, timeouts), retry on other replicas, possibly exponential backoff. For staleness violations (i.e., client requires fresher than available), we might route to primary. If primary also fails, maybe error.
Circuit breaker: per replica, to avoid sending traffic to failing replicas.
Logging: each routing decision may log (at debug) the chosen replica, lag, budget. Errors.
Tracing: propagate trace IDs; mark spans for routing decision and DB query.
Monitoring dashboards: replication lag over time, replica health, request distribution.
Alerts: lag exceeds threshold, too many fallbacks to primary, high error rates.
Tools: Prometheus, Grafana, OpenTelemetry.
Implementation Details:
Lag measurement: Could be via database-specific commands (e.g., pg_stat_replication for Postgres, SHOW SLAVE STATUS for MySQL) or via monitoring agents that report to a central store (like a key-value store). The router needs up-to-date lag info; could push from replicas or pull periodically.
Router could be a separate service (like a load balancer) or integrated into application code (client-side load balancing). Probably design as a service that clients call (like a read proxy). Or as a library.
Routing algorithm: Given set of replicas with known lag and load (optional), and a budge B, filter replicas with lag <= B. If none, fallback to primary. Among filtered, pick one using a load balancing policy (random, round-robin, least connections). Optionally consider load and health.
Caching of lag: caution about staleness of lag metrics themselves; need reasonably fresh data (e.g., refreshed every second). Could use a distributed cache like Redis to store latest lag metrics.
Handling writes: writes go to primary directly. For read-after-write, we may need to cache the write timestamp or LSN in the client session (or in a token) and send with subsequent reads. Router uses that to determine required replica advancement.
Multi-region scenario: replicas in different regions; also consider network latency. Could incorporate latency into routing (e.g., choose nearest replica that meets budget). That could be an extension.
Edge Cases:
Replica lag spikes: if all replicas exceed budget, fallback to primary might overload it. Could have a "grace period" or allow slightly over budget with risk.
Partition tolerance: if a replica is unreachable, remove from pool.
Consistency budgets may change dynamically based on business logic.
Detailed Flow:
Client sends read request with optional consistency hint (or default).
Router extracts budget: if hint is READ_YOUR_WRITES, retrieve session's last write LSN from context (maybe stored in a cookie or passed). Convert to required min LSN (or time).
Router queries lag store for current lag of each replica. Also get health.
If none eligible, route to primary (if allowed) or return error (if strong consistency required but primary unavailable).
After response, record metrics.
Retry Policy Example:
On network error or timeout: retry up to N times, each time re-evaluating eligibility (maybe new lag measurements). If after retries still fails, return error.
On stale response detection? Not typical unless client includes a version and gets error. Could have DB return "transaction too old" if read-only snapshot is too old? Not common.
Observability in more depth:
Use structured logs with request ID, replica chosen, lag at decision time, outcome.
Trace spans: "router.decision", "db.query".
Export metrics: counters for routed_to_primary, routed_to_replica, fallback_due_to_lag, retry_attempts.
Security: not asked, but mention that the router may need auth to query DB replication status.
Extensibility: Could add support for causal consistency via vector clocks, but out of scope.
We need to present a comprehensive design. Since it's a text answer, we can write in paragraphs, or bullet points. Use clear headings.
We should include diagrams? Possibly not, but we can describe.
Let's produce a structured answer with sections:
Introduction
System Components
Staleness Budgets
Consistency Hints
Routing Algorithm
Retry Policies
Observability
Failure Handling
Scalability & Performance Considerations
Conclusion
Make it detailed.
We need to ensure we address all four: staleness budgets, consistency hints, retry policies, and observability. Not too heavy on code, but design-level.
We can also mention that the routing layer could be implemented as a sidecar (like Envoy) or a dedicated service.
Let's start.
Potential pitfalls: Overly simplistic. Should ensure we cover different consistency models. Also discuss that staleness budgets can be per-request or per-client.
Also, could discuss that the budget might be expressed as a time interval or as a specific replication position (e.g., LSN). The router needs to compare replica's applied LSN to required LSN. That requires the primary to expose its current LSN, and replicas to expose their applied LSN. The router then computes difference in time (if LSNs are timestamped) or uses heartbeat.
Simplify: Use timestamp: primary maintains current commit timestamp (e.g., logical clock). Replicas report their "replay timestamp" (the timestamp of the last applied change). Lag = primary_time - replica_time. Then budget is a max allowed lag. For read-your-write: client provides the write timestamp that it observed from primary after its write; then required replica time >= write timestamp.
Implementation: Primary could have a table or function to get current commit timestamp (like pg_xlog_location, but better: use a monotonically increasing commit timestamp, e.g., in PostgreSQL, use pg_current_xact_id()? Actually we could use a sequence). But we can just conceptualize.
Health monitoring: replicas send heartbeats to router or central store.
We'll go into details.
Let's write.
Also, talk about caching: the router may cache replica health and lag to avoid hitting DB each time; need to balance freshness.
We can define a "Replica Registry" that stores metadata: replica ID, endpoint, status, last_heartbeat, lag, load. Router consults this registry.
Now, produce the final answer.
Read‑Replica Lag‑Aware Routing Layer
1. Overview
In a horizontally‑scaled data store, writes go to a primary database while reads are served from asynchronous read replicas. Replication lag is the delay between a commit on the primary and its application on a replica. A lag‑aware routing layer directs read requests to a replica that satisfies the requester’s consistency needs while balancing load and ensuring high availability.
Key requirements:
Staleness budgets – maximum allowed replication lag per request.
Router/Proxy: Stateless service (or library) that receives read requests, consults replica metadata, applies policies, and forwards the query.
Replica Registry: Central store (e.g., Redis, ZooKeeper) holding up‑to‑date metadata for each replica: endpoint, health status, current lag, load metrics, supported consistency features.
Lag Monitor: Side‑car or agent running on each replica (or pulling from the DB) that periodically measures replication progress and writes it to the registry.
Primary DB: Accepts writes and exposes a monotonically increasing commit marker (e.g., LSN, timestamp).
Read Replicas: Serve reads; each reports its “apply position” (LSN or timestamp) to the lag monitor.
3. Staleness Budgets
Definition – A staleness budget is the maximum acceptable difference between the primary’s current state and a replica’s applied state. It can be expressed in:
Time (seconds) – simpler, works if replicas report a timestamp of last applied change.
Replication Position (LSN, offset) – more precise; requires translating a time budget to an LSN threshold or using LSN directly.
Sources of a budget:
Global default (e.g., 10 s).
Per‑client configuration (e.g., mobile app tolerates 5 s).
Per‑request override – passed in request headers or RPC metadata.
Session‑bound – for “read‑your‑writes”, the client includes the commit marker from its last write; the required replica LSN must be ≥ that marker.
The router evaluates each replica: replica_lag = primary_current_marker - replica_applied_marker. If replica_lag ≤ budget, the replica is eligible.
4. Consistency Hints
Beyond simple time budgets, hints express higher‑level consistency guarantees:
Hint
Translation to Routing
EVENTUAL
Very high budget (∞); any healthy replica.
BOUNDED_STALENESS
Convert supplied max‑lag (e.g., 2 s) to numeric budget.
READ_YOUR_WRITES
Client sends the commit marker (LSN/ts) of its last write. Router requires replica_applied_marker ≥ write_marker. May also enforce a small time buffer if the replica is slightly behind.
MONOTONIC_READS
For a given client session, remember the LSN of the last read (session_last_read). Next read must use a replica with replica_applied_marker ≥ session_last_read. Router stores session_last_read in a cookie or external session store.
STRONG / LINEARIZABLE
Budget = 0; always route to primary. Often combined with a “read lock” but that is outside routing layer scope.
Hints can be combined (e.g., “read‑your‑writes within 5 s”). The router builds a composite filter: eligible replicas must satisfy all constraints.
5. Routing Algorithm
Inputs:
Request: consistency_hint, optional session data (last write marker, last read LSN).
Replica metadata from registry: {endpoint, lag, load, health}.
Steps:
Determine required conditions:
Minimum required replica marker (min_marker) derived from any session‑bound write/read LSN.
Maximum allowed lag (max_lag) derived from time budget (converted using primary’s current marker).
Fetch latest replica data (cached with small TTL, e.g., 1 s) from the registry.
If empty: fallback to primary if primary is healthy and the hint permits (e.g., not strong linearizability without primary? Actually strong requires primary, so fallback to primary is okay; if primary unavailable → error).
If non‑empty: apply load‑balancing (round‑robin, random, least‑connections, or latency‑aware if cross‑region).
Forward request, attaching tracing IDs.
Record metrics for decision: chosen replica, eligibility count, fallback reason.
Caching: The router may keep a local snapshot of replica metadata, refreshing asynchronously. Staleness of metadata (few seconds) is acceptable because replication lag changes slowly relative to request rate.
6. Retry Policies
Failures can occur at multiple points: replica unreachable, request timeout, or the replica becomes ineligible after selection (rare). The router must decide whether and how to retry.
Retryable errors:
Network errors, connection failures, timeouts.
Replica returns an application error indicating it cannot serve the request (e.g., “snapshot too old”, though this is uncommon for simple reads).
Policy:
Immediate retry limit: max_retries (e.g., 2) per request.
Replica selection on retry: Re‑evaluate eligibility using fresh metadata; avoid retrying the same failing replica (circuit breaker per replica).
If primary was used in first attempt and fails, do not retry on primary again (unless all replicas fail) – consider returning error.
Circuit breaker: After a threshold of consecutive failures (e.g., 5 timeouts in 30 s), temporarily mark replica as unhealthy in the registry.
Fallback escalation: If after retries no replica meets the budget, but primary is healthy and the hint allows reading from primary (e.g., bounded staleness can be violated), route to primary as a last resort. If the hint forbids (e.g., strict read‑your‑writes and primary is the only source of fresh data), return an error to client.
Handling dynamic lag: If a replica’s lag increases after selection but before the query completes, the query may return slightly stale data. This is usually acceptable because the check was recent. To guarantee never exceeding the budget, the replica itself could reject reads that would exceed the client’s required freshness, but most DBs don’t provide this. Hence the router relies on fresh measurements.
7. Observability
Full visibility into routing decisions and replica health is essential.
Structured JSON logs for each request: trace_id, client_id, consistency_hint, budget, chosen_replica, replica_lag_at_decision, outcome (success/failure), retry_count.
Error logs with stack traces for unexpected exceptions.
Tracing:
Propagate traceparent (W3C) or B3 headers.
Router creates a span: routing.decision with tags for selected replica, lag, and eligibility.
Forwarded DB query inherits the same trace ID; DB instrumentation (if any) adds its own spans.
Dashboards & Alerts:
Grafana dashboards showing per‑replica lag over time, request distribution, fallback rates.
Alerts:
Lag > threshold for > X seconds.
Primary QPS spikes (due to many fallbacks).
High error/retry rates.
Replica health degradation.
Tooling: OpenTelemetry for tracing, Prometheus for metrics, Loki/Elastic for logs.
8. Failure Handling & High Availability
Replica outage: Monitor detects via missing heartbeats; marks replica unhealthy. Router excludes it from pool.
Primary outage: Write traffic stops; read‑only traffic may still use replicas with appropriate budgets (if reads can tolerate staleness). However, if primary is down, replication stops and lag grows. Router should detect increasing fallbacks and alert.
Network partition: Replica may be unreachable; health check fails. Partition between router and registry: router caches last known state and continues using it, but may mark replicas stale if heartbeats missing. Re‑establish connection and sync.
Stale metadata: The lag monitor pushes updates frequently (every second). If push fails, pull model can be used as backup. Router can also have a TTL on cached entries; after TTL, it may fetch fresh data or fall back to a safe default (e.g., route to primary).
9. Scalability & Performance
Router scaling: Stateless; can be horizontally scaled behind a load balancer. Use consistent hashing on client ID if session‑state (e.g., session_last_read) is stored in the router; better to store session state in an external store (Redis) so any router instance can access it.
Replica registry: Must handle high read QPS from routers. Use an in‑memory data store (Redis) with pub/sub for updates; routers subscribe to changes to invalidate caches instantly.
Lag monitor: Minimal overhead; reads DB system tables (e.g., pg_stat_replication, SHOW SLAVE STATUS). For many replicas, use a central collector to avoid load on primary.
Cross‑region latency: If replicas are geo‑distributed, the router can incorporate network RTT estimates into selection (prefer lower latency among eligible replicas). This is an optional enhancement.
10. Security & Multi‑Tenancy
The router authenticates to the replica registry and to replicas (service‑to‑service auth, mTLS).
Replication status endpoints on replicas should be restricted to trusted networks.
For multi‑tenant systems, budgets may be tenant‑specific; router could fetch tenant config from a policy service.
11. Example Request Flow
Client sends read request with header X-Consistency-Hint: bounded-staleness, max-lag=3s (or session token containing last write LSN).
Router extracts hint, queries local cache of replica metadata (refreshed <1 s ago).
Suppose Replica A lag = 2.1 s, Replica B lag = 3.5 s, Replica C lag = 1.8 s. Eligibility: only A and C.
If all replicas had lag > 3 s, router falls back to primary (if healthy). If primary also down → error 503.
12. Advanced Topics (Optional)
Causal consistency via vector clocks: router would need to track per‑client vector clock and compare against replica’s known dependencies. This greatly increases complexity and is out of scope for a basic lag‑aware router.
Hybrid logical clocks (HLC): Could be used to bound staleness without synchronized clocks.
Dynamic budget adaptation: Router could adjust budgets based on observed lag distribution to maintain high hit‑rate on replicas.
Read‑only transaction snapshots: Some DBs allow starting a snapshot with a required LSN; router could send the target LSN as a session variable (e.g., SET TRANSACTION SNAPSHOT TO ...). This ensures the replica only serves data as of that LSN, effectively enforcing consistency without false positives.
13. Conclusion
A lag‑aware routing layer offloads the complexity of consistency management from application code, providing a flexible, observable, and resilient way to serve reads from replicas. By combining real‑time replication metrics, user‑provided consistency hints, smart retry logic, and comprehensive observability, it enables applications to trade off freshness for performance while maintaining reliability.