FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Read/Write Split Engine & Routing

Multi-host database routing in FastAPI, session routing to primary for writes and replicas for reads.

Freshness: current•15 min read•Data Engineering and Databases

Key Learning Outcomes

  • ✓Route read traffic dynamically to replica instances
  • ✓Ensure write consistency across multi-node databases
Full Technical Reference Document

Mental model

In typical OLTP and AI knowledge workloads, 80%–90% of database queries are read-only SELECT operations (feed listings, RAG metadata lookups, analytics dashboards, profile checks). Read/Write Split Routing directs every mutating workflow (INSERT, UPDATE, DELETE) and strongly consistent read strictly to the single PostgreSQL Primary, while spreading tolerant SELECT load horizontally across one or more streaming Read Replicas. Because PostgreSQL physical streaming replication is asynchronous by default, effective routing must classify read paths by consistency requirement rather than splitting blindly on HTTP verb alone—guarding critical "read-your-own-writes" transitions with explicit primary pinning or LSN causality tokens.

HTTP Request Route
Inspect Operation Consistency Need
Eventual Read -> Query Read Replica Engine Pool
Write or RYW Read -> Query Primary Database Engine
WAL Streaming Replication Synchronization
Conceptual teaching model synthesized from:postgresql-docs,sqlalchemy-docs

Theory

PostgreSQL replicates writes from the Primary to Standby Replicas by shipping Write-Ahead Log (WAL) records (pg_wal). Under asynchronous replication (synchronous_commit = on locally on primary, async WAL ship to standby), a primary COMMIT returns immediately before standby replicas finish replaying those WAL bytes, producing a transient replication lag window (typically 1–50 ms, spiking to seconds during heavy bulk backfills or replica vacuum conflicts).

Routing PolicySQLAlchemy Engine TargetConsistency GuaranteeWhen Safe vs. Unsafe
Explicit Dependency Injection Split (ReadDb vs WriteDb)Separate replica_engine vs primary_engine Depends hooksPer-endpoint explicit controlSafest default; prevents accidental replica routing inside mutation flows
Sticky Session / Primary-Pinning Window (RYW Cookie/Header)Primary for N seconds (~5 s) post-mutation per user/tenant, else ReplicaRead-your-own-writes (Session Consistency)Prevents "I created an item and page refresh showed 404" race bugs
WAL LSN Monotonic Wait (pg_last_wal_replay_lsn())Any Replica whose replay LSN >= write response LSN, fallback PrimaryLinearizable read-after-write without primary CPU loadIdeal for distributed APIs returning write-token LSNs across services
SQLAlchemy Routing Session (get_bind())Dynamic engine switch inspecting self._flushing or execution_optionsTransparent inside mixed services, risky if misusedMust override _flushing / explicit for_write hints to avoid mid-request drift

Separate ReadDb / WriteDb Dependencies and Read-Your-Own-Writes Protection

In FastAPI, injecting two explicit typed dependencies—WriteDb (bound to Primary) and ReadDb (bound to Replica Pool, with automatic fallback or explicit opt-out)—is far safer and easier to audit than magic middleware parsing SQL strings with regex. Crucially, whenever a POST/PATCH endpoint executes a write and the client immediately triggers a follow-up GET (redirect-after-POST, React Query cache invalidation), reading from a lagging replica will miss the newly inserted row! Mitigate this cleanly via either a short primary-pinning hint (X-Read-Primary-Until signed timestamp cookie / Redis key per tenant for 3–5 seconds after writes) or passing pg_current_wal_lsn() from the write endpoint so reads wait briefly (pg_wal_replay_pause check or conditional Primary fallback) if lag exceeds budget.

python
from collections.abc import AsyncIterator
from typing import Annotated
from fastapi import Depends, FastAPI, Header, HTTPException, status
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
​
PRIMARY_URL = "postgresql+asyncpg://app:secret@primary-pgbouncer:6432/app_db"
REPLICA_URL = "postgresql+asyncpg://app:secret@replica-pgbouncer:6432/app_db"
​
primary_engine = create_async_engine(PRIMARY_URL, pool_size=10, pool_pre_ping=True, connect_args={"statement_cache_size": 0})
replica_engine = create_async_engine(REPLICA_URL, pool_size=25, pool_pre_ping=True, connect_args={"statement_cache_size": 0})
​
PrimarySessionLocal = async_sessionmaker(primary_engine, expire_on_commit=False)
ReplicaSessionLocal = async_sessionmaker(replica_engine, expire_on_commit=False)
​
async def get_write_db() -> AsyncIterator[AsyncSession]:
async with PrimarySessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
​
async def get_read_db(
x_consistency: Annotated[str | None, Header()] = None,
) -> AsyncIterator[AsyncSession]:
# Route strongly consistent post-write reads to Primary; standard analytics/feeds to Replica
factory = PrimarySessionLocal if x_consistency == "strong" else ReplicaSessionLocal
async with factory() as session:
yield session
​
WriteDb = Annotated[AsyncSession, Depends(get_write_db)]
ReadDb = Annotated[AsyncSession, Depends(get_read_db)]
app = FastAPI()
​
@app.get("/v1/search/documents")
async def list_documents(db: ReadDb, org_id: int) -> dict[str, object]:
rows = (await db.execute(text("SELECT id, title FROM documents WHERE org_id = :org LIMIT 25"), {"org": org_id})).mappings().all()
return {"items": list(rows)}
​
@app.post("/v1/documents", status_code=status.HTTP_201_CREATED)
async def create_document(db: WriteDb, org_id: int, title: str) -> dict[str, str]:
row = await db.execute(text("INSERT INTO documents (org_id, title) VALUES (:org, :title) RETURNING pg_current_wal_lsn()::text"), {"org": org_id, "title": title})
wal_lsn = row.scalar_one()
return {"title": title, "wal_lsn": wal_lsn}

Alternatives and trade-offs

  • Explicit Dual Engines (WriteDb + ReadDb in FastAPI): Crystal-clear auditability during code review, separate PgBouncer pools per role, zero brittle SQL parsing; requires engineers to choose WriteDb explicitly for strongly consistent reads (SELECT ... FOR UPDATE, authentication token checks, billing balance checks).
  • Proxy-Layer Read/Write Splitting (Pgpool-II / AWS RDS Proxy): Inspects SQL at the proxy layer to route reads vs. writes without app code changes; struggles with stored functions (SELECT mutate_user()), multi-statement transactions, and application-aware Read-Your-Own-Writes pins.
  • PostgreSQL synchronous_commit = remote_apply: Forces primary transactions to wait until a standby applies WAL before confirming COMMIT, guaranteeing zero replication lag on that standby at the expense of adding cross-AZ network RTT (1–5 ms) to every write and risking write stalls if the standby goes unreachable without synchronous_standby_names quorum failover.

Failure modes and misconceptions

  1. Read-Your-Own-Writes Anomaly After POST -> GET: Creating an order on Primary and letting the immediate UI redirect GET /orders/{id} hit an async Replica during a 40 ms lag burst returns HTTP 404 Not Found to the user. Enforce strong consistency (Primary routing) for immediate post-write fetches, auth checks, and billing validations.
  2. Issuing Writes Inside a Replica Transaction (Including Temp Tables or Sequence nextval): PostgreSQL standbys are strictly read-only (cannot execute INSERT in a read-only transaction). Any endpoint routed to ReadDb that silently runs an audit log insert, session update, or SET mutation will fail immediately at runtime.
  3. Long Analytical Replica Queries Cancelled by max_standby_streaming_delay: When Primary runs VACUUM or DDL cleanup affecting rows currently being scanned by a 60-second BI query on a Replica, PostgreSQL cancels the replica query (ERROR: canceling statement due to conflict with recovery) unless hot_standby_feedback = on or max_standby_streaming_delay is tuned—and enabling hot_standby_feedback causes bloat retention on the Primary if replica queries run forever.
  4. Auto-Routing GET Queries to Replicas Blindly: Not every GET endpoint tolerates eventual consistency—GET /oauth/token/introspect, GET /billing/credits, or GET /webhooks/idempotency must read Primary truth so revoked tokens or spent credits cannot be double-spent within a lag window.
Reflect before revealing the guide

Decision scenario

Your SaaS platform runs 90% read queries (RAG citation lookups, dashboard aggregations, public catalog reads) against a saturated 8-core Primary alongside 2 streaming Read Replicas across Availability Zones. Split SQLAlchemy engines cleanly into WriteDb and ReadDb FastAPI dependencies backed by dedicated primary and replica PgBouncer pools, keep auth/billing/read-after-write flows pinned to WriteDb (guided by a 5-second X-Read-Primary-Until session cookie after mutations), configure replica endpoints with aggressive statement_timeout = 10s and monitored WAL replay lag alerts (> 500 ms trips automated circuit fallback to healthy replicas), and offload heavy batch analytics to a dedicated delayed replica with hot_standby_feedback = off.

Learning outcomes

  • Separate primary write pools and replica read pools cleanly using typed FastAPI dependencies (WriteDb vs ReadDb).
  • Diagnose and prevent read-your-own-writes anomalies caused by asynchronous WAL streaming lag.
  • Contrast explicit app routing, proxy SQL parsing, and remote_apply synchronous commit trade-offs.
  • Protect replica queries against recovery conflicts (max_standby_streaming_delay) and prevent accidental write operations on read-only standbys.

Trade-offs

Read/write replica splitting unlocks near-linear read scaling and isolates heavy dashboard queries from OLTP primary CPU, yet introduces eventual-consistency race windows and operational lag monitoring that demand explicit consistency classification per endpoint.

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next