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.
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 Policy | SQLAlchemy Engine Target | Consistency Guarantee | When Safe vs. Unsafe |
|---|---|---|---|
Explicit Dependency Injection Split (ReadDb vs WriteDb) | Separate replica_engine vs primary_engine Depends hooks | Per-endpoint explicit control | Safest 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 Replica | Read-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 Primary | Linearizable read-after-write without primary CPU load | Ideal for distributed APIs returning write-token LSNs across services |
SQLAlchemy Routing Session (get_bind()) | Dynamic engine switch inspecting self._flushing or execution_options | Transparent inside mixed services, risky if misused | Must 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.
pythonfrom collections.abc import AsyncIteratorfrom typing import Annotatedfrom fastapi import Depends, FastAPI, Header, HTTPException, statusfrom sqlalchemy import textfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_enginePRIMARY_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 sessionawait session.commit()except Exception:await session.rollback()raiseasync 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 Replicafactory = PrimarySessionLocal if x_consistency == "strong" else ReplicaSessionLocalasync with factory() as session:yield sessionWriteDb = 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+ReadDbin FastAPI): Crystal-clear auditability during code review, separate PgBouncer pools per role, zero brittle SQL parsing; requires engineers to chooseWriteDbexplicitly 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 confirmingCOMMIT, 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 withoutsynchronous_standby_namesquorum failover.
Failure modes and misconceptions
- Read-Your-Own-Writes Anomaly After
POST->GET: Creating an order on Primary and letting the immediate UI redirectGET /orders/{id}hit an async Replica during a40 mslag burst returns HTTP404 Not Foundto the user. Enforcestrongconsistency (Primary routing) for immediate post-write fetches, auth checks, and billing validations. - 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 toReadDbthat silently runs an audit log insert, session update, orSETmutation will fail immediately at runtime. - Long Analytical Replica Queries Cancelled by
max_standby_streaming_delay: When Primary runsVACUUMor 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) unlesshot_standby_feedback = onormax_standby_streaming_delayis tuned—and enablinghot_standby_feedbackcauses bloat retention on the Primary if replica queries run forever. - Auto-Routing
GETQueries to Replicas Blindly: Not everyGETendpoint tolerates eventual consistency—GET /oauth/token/introspect,GET /billing/credits, orGET /webhooks/idempotencymust read Primary truth so revoked tokens or spent credits cannot be double-spent within a lag window.
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 (
WriteDbvsReadDb). - Diagnose and prevent read-your-own-writes anomalies caused by asynchronous WAL streaming lag.
- Contrast explicit app routing, proxy SQL parsing, and
remote_applysynchronous 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.