How OpenAI scales PostgreSQL: one writer, nearly 50 replicas, and the work around them

A technical deep dive into OpenAI’s read-heavy PostgreSQL design: WAL fan-out, replica lag, connection pooling, cache coordination, overload control, and schema limits.


In January 2026, OpenAI’s PostgreSQL deployment had one unsharded Azure Database for PostgreSQL Flexible Server primary and nearly 50 read replicas. The deployment served millions of database queries per second within a system serving 800 million users. That user count is a product-scale number, not a count of simultaneous PostgreSQL clients. I keep coming back to the single writer. Every write competes for that primary, while most reads have to be removed from it before they become a problem.

Counting replicas misses most of the scaling work. The database is only one part of a chain that includes a cache, application routing, PgBouncer, Kubernetes Services, regional replicas, workload isolation, and rate limits. Each layer controls a different kind of pressure. None makes the primary’s write capacity unlimited.

One primary, several read paths

Application reads use a shared cache and regional PgBouncer pools before reaching read replicas. Writes and transactional reads go to one primary. Dashed WAL paths feed the read fleet and a separate failover standby.

The read fleet and failover standby serve different purposes. Query routing must also carry the consistency requirement; a replica count cannot guarantee read-your-writes behavior.

Open full size Scroll horizontally to read the diagram on a small screen.

The primary is the authority for writes. PostgreSQL remains unsharded, and every write goes through that single instance. Some reads also have to stay there because they are part of a write transaction. Other reads can be served from cache or sent to a regional replica.

That distinction matters when an application reads data immediately after changing it. A replica can only return transactions it has received and replayed. A request that needs read-your-writes behavior cannot be sent to an arbitrary replica and assumed to see the latest commit. The application needs an explicit consistency contract: route dependent reads to the primary, or fence a replica read on a WAL position known to include the write. A fixed delay or affinity to an arbitrary replica cannot guarantee freshness. The read also needs a new snapshot taken after that fence; an older Repeatable Read snapshot will stay old even after replay catches up. A generic “send reads to replicas” rule is not enough.

The read router has to decide:

  1. Can the cache answer this key within the feature’s freshness contract?
  2. If the cache misses, can this read tolerate replica lag?
  3. If it cannot, should the query use the primary, wait for a replica position, or fail within the request deadline?

Each answer changes load. A cache hit avoids a database query. A replica read protects primary CPU but accepts some staleness. A primary read with a fresh snapshot avoids asynchronous replica delay, but consumes the capacity needed for writes and transactional reads. These are product consistency choices as much as database-routing choices.

OpenAI has moved shardable, write-heavy workloads to systems such as Azure Cosmos DB and stopped adding new tables to this PostgreSQL deployment. That puts a boundary around the workload the primary can support. It also avoids a costly migration of existing application endpoints solely to shard a database that still has headroom for its read-heavy role.

WAL replication moves state, not query capacity

PostgreSQL records changes in its write-ahead log, or WAL. A physical replica receives the log stream and replays it to advance its own copy of the database. That makes it useful for reads, but the replica is downstream of the writer: it does not accept writes that independently modify the same database state.

The primary’s commit and a replica’s visibility of that commit are separate events. With asynchronous replication, the primary can acknowledge a transaction before a replica has received or replayed its WAL. The replica can then answer queries while being slightly behind. Near-zero average lag is not a consistency guarantee for an individual query.

WAL positions and rates explain recovery better than a single lag number. Let B be the replica’s outstanding WAL backlog, W the primary’s WAL generation rate, and R the replica’s replay rate. When R > W, the backlog shrinks at R - W; when R <= W, the replica cannot catch up while the workload continues.

For example, suppose a replica is 24 GiB behind, the primary generates 100 MiB/s, and the replica replays 300 MiB/s. At 1,024 MiB per GiB, the net catch-up rate is 200 MiB/s, so the idealized catch-up time is 24 × 1,024 / 200 = 123 seconds. This assumes stable rates and ignores network stalls, checkpoints, and workload interference. If replay falls to 100 MiB/s while generation stays at 100 MiB/s, the replica remains behind indefinitely.

Replication also has a write-side cost. OpenAI’s primary streams WAL directly to each read replica. More replicas mean more WAL consumers, more network transfer, and more work on the primary. Replica count is not free capacity added only on the read side.

The deployed direct topology sends WAL from the primary to each replica. The experimental cascade sends WAL through an intermediate relay to downstream replicas; forwarding does not require local replay first.

The cascade is a scaling direction under test in January 2026. It reduces direct primary streams while adding relay failure and freshness boundaries.

Open full size Scroll horizontally to read the diagram on a small screen.

Cascading replication changes the fan-out tree. The primary sends WAL to a smaller set of intermediate replicas; each intermediate forwards it to downstream replicas. This can reduce direct streams from the primary and could support a fleet above 100 replicas. It adds a forwarding hop, not a requirement to replay each record before forwarding it. A standby can stream received, flushed WAL onward while its own query-visible replay position is further behind. Network or WAL-flush delays at the relay can still hold back every child. If a relay fails, its downstream replicas need a new upstream and a safe recovery path.

That is why the difficult part of a cascade is not drawing another arrow. It is coordinating promotion, reconnects, timelines, and freshness after a failure. A topology with fewer primary connections can still have worse end-to-end freshness if the relay tier is undersized or unstable. In January 2026, the cascading design was still under test. The deployed read path used direct streams.

The hot standby has a different purpose from the regional read fleet. It is maintained as the primary’s failover target. If the primary fails, critical reads can continue through the read replicas, while writes remain unavailable until the standby is promoted and clients can use the new primary. That is partial availability, not write continuity. Failover also needs safe fencing of the old primary; otherwise two writable primaries could accept conflicting histories.

PgBouncer controls connections, not work

Each Azure PostgreSQL instance has a 5,000-connection limit. PgBouncer sits between clients and database instances, with multiple PgBouncer pods behind Kubernetes Services associated with each read replica. Average connection time fell from 50 ms to 5 ms.

Pooling helps because opening a database connection is not free. A service with many application processes can create far more client connections than the database should run concurrently. PgBouncer lets many clients share a smaller set of PostgreSQL server connections, reducing connection churn and the number of active backends.

But a pool does not make SQL faster. It bounds server sessions and turns excess demand into a queue. That queue needs limits too. If all server connections are busy, new work waits; if too many requests wait, latency grows until callers time out. A pool with an unbounded queue can hide overload for a while and then release a large backlog onto the database.

The useful sizing questions are therefore: how many server connections can the instance sustain, how many requests can wait, how long may each wait, and what is shed when those limits are reached? Raising the client limit without increasing database throughput only moves the bottleneck. The total has to include server-connection limits across every pooler pod and every database/user pool targeting an instance, including reserve pools and administrative connections. A per-pod limit of 100 across 20 pods can permit 2,000 backends; it is not an instance-wide limit of 100. Kubernetes Service balancing also assigns TCP connections, not individual SQL statements, so long-lived clients can leave pod loads uneven.

Pooling mode also changes what an application may assume. With transaction pooling, a client is assigned a server connection for the duration of a transaction and can receive a different backend later. Session state that the application expects to persist across transactions can fail: a later transaction may use a different backend. SQL-level session SET commands, session advisory locks, and temporary tables with session lifetimes need explicit compatibility checks. Protocol-level prepared statements depend on PgBouncer version and configuration. Statement pooling disallows transactions that span multiple statements. The deployment uses statement or transaction pooling, so application behavior has to be compatible with a backend connection changing between transactions.

Co-locating clients, poolers, and replicas in a region reduces network round trips and the time a backend connection stays occupied by remote work. That matters at scale because a connection held during network waits is unavailable to another transaction. Pooling and regional placement reduce connection pressure; neither replaces admission control for expensive queries.

Cache misses need coordination

Most reads are served from a cache. That lowers database work, but it creates a burst risk: when a popular key expires or becomes unavailable, many concurrent requests can miss together and issue the same database query.

The cache uses a lock or lease per key. One request wins the lease, reads PostgreSQL, and repopulates the cache. The other requests wait for that fill instead of duplicating the query. The lock narrows redundant work for a hot key; it does not increase database capacity, and it does not help when misses are spread across unrelated keys.

The lease has tricky edges. If the holder pauses past expiry, a second holder may start while the first is still running. If both write the cache, an older result could overwrite a newer one. The design needs ownership that can be checked at publication time, such as a monotonically increasing fencing value, or another mechanism that rejects stale holders. Ownership validation and the cache write must be atomic at the cache authority; a check followed by a separate write has its own expiry race. A cache lease implementation has to enforce that ownership at publication. Waiting requests also need a bounded policy: wait, serve stale data, go to the database, or fail. The feature’s freshness and latency contract determines those choices. Lease expiry, duplicate fills, wait time, and stale writes reveal whether the policy works.

An aggregate hit rate can conceal a dangerous miss pattern. A 99% hit rate sounds healthy, but the remaining one percent might concentrate on a few expensive keys during a launch. Breaking hit rate, miss rate, query cost, and wait time down by key family and workload exposes that concentration. Cache freshness should follow the data’s correctness requirements; shortening a TTL alone does not define what stale reads are acceptable.

Overload feeds on retries

Admission control limits requests before a bounded queue and aggregate PgBouncer server connection budgets. An illustrative 1200 transactions per second needs 18 active slots at 15 milliseconds but 36 at 30 milliseconds.

The connection budget spans every pool instance and database/user pool. Queue bounds and recovery reserve belong in the same budget as foreground queries.

Open full size Scroll horizontally to read the diagram on a small screen.

The failure loop is straightforward and nasty. A cache outage, expensive multi-table join, or write storm raises CPU, I/O, or connection use. Queries slow down. Requests time out. If callers retry immediately, PostgreSQL may still be executing the original query while a duplicate arrives. The database now has more work precisely when it has less spare capacity.

Rate limits at the application, pooler, proxy, and query layers shed load before all of it becomes database work. Blocking a costly query shape can protect unrelated traffic. Separating high-priority and low-priority workloads onto dedicated instances reduces noisy-neighbor effects across features and products. These mechanisms are complementary: a cache lease prevents duplicate fills for one key, while rate limits cap demand and workload isolation protects reserved capacity.

Retries need a budget. Exponential backoff with jitter spreads retries over time; a bounded number of attempts and an overall deadline prevent one request from occupying resources indefinitely. A retry should also account for whether the first attempt could still be running. Otherwise a client that times out can multiply the work it is trying to recover from.

Writes add a correctness problem: a connection can drop after COMMIT succeeded but before the acknowledgement arrives. Retrying that operation blindly can apply it twice. An illustrative payment-like operation can store a scoped idempotency key under a unique constraint and the operation’s result in the same transaction as the mutation. A retry with that key reads the recorded result. This requires a defined key scope and retention window; merely generating a fresh request ID on each attempt provides no protection. Serialization failures require retrying the whole transaction, including the reads that informed its decisions.

Query shape and writes set the ceiling

One costly query joined 12 tables, and spikes in that query contributed to high-severity incidents. The important operational point is that a single query shape can consume enough CPU to affect unrelated requests. An ORM does not make the generated SQL harmless. The actual query plan and parameter distributions show where to start: is the join necessary, can it be decomposed, and is application-side assembly cheaper at the required data volume?

PostgreSQL’s MVCC model keeps multiple row versions so concurrent transactions can see a consistent snapshot. An update creates a new tuple version; vacuum later reclaims versions that no active transaction can see. The retention boundary depends on isolation and transaction state. Repeatable Read and Serializable transactions retain a transaction snapshot after their first ordinary query. Read Committed normally takes a new snapshot per statement; an idle transaction does not necessarily retain its last statement snapshot. An open transaction with an assigned transaction ID can still hold back the cleanup horizon, and locks survive until transaction end. backend_xmin, backend_xid, transaction age, and wait events distinguish an idle connection from one holding back cleanup. idle_in_transaction_session_timeout bounds abandoned open transactions; it is different from terminating ordinary pooled connections that are idle outside a transaction.

Write-heavy workloads stress the primary through WAL generation, row-version churn, index maintenance, and vacuum. Read replicas distribute query work, but they do not remove those costs from the writer. Fixing redundant application writes, delaying noncritical writes where correctness permits, and rate-limiting backfills reduce work at the point where it is created. Sharding write-heavy domains moves that write load to a different capacity boundary.

Schema changes have a lock budget

Some DDL operations are metadata changes; others rewrite a table or need locks that block production queries. This design limits schema changes to lightweight operations, applies a five-second timeout, allows concurrent index creation and removal, and puts new tables in alternative sharded systems.

A five-second schema timeout does not identify a specific PostgreSQL setting. lock_timeout bounds each lock-acquisition wait, while statement_timeout covers the whole statement, including waits and execution. A deliberate migration needs a short lock-wait budget separate from its execution budget. A queued ACCESS EXCLUSIVE request can block later conflicting queries behind it even before it obtains the lock. Concurrent index operations allow ordinary reads and writes to continue through the build, but still wait on transactions in some phases, consume I/O and CPU, and can leave an invalid index after failure. CREATE INDEX CONCURRENTLY cannot run inside a transaction block. Its execution budget must accommodate its scans; treating every concurrent build as a five-second operation would be a separate, much stronger restriction. A long backfill competes for the same resources as foreground writes and produces WAL that replicas must replay. Some of these migrations take more than a week, so progress, pause, resume, and rate control are part of the design.

The safest migration is a sequence with explicit compatibility windows: add a nullable field, deploy compatible readers and dual writers, retire old writers, then backfill at a bounded rate. Backfill updates need a predicate or version check so an old value cannot overwrite a concurrent new write. Reconcile remaining gaps before switching reads to the new field; remove old writes and storage in later deployments. Each step should have a small lock and load footprint and be able to stop without leaving application versions unable to read the schema.

Where the latency and availability budgets go

The January 2026 operating snapshot described nearly 50 read replicas, near-zero replication lag, low double-digit millisecond p99 client-side latency, and five-nines PostgreSQL availability. Those database-level figures do not establish an end-to-end ChatGPT SLO; the measurement window and method would have to be defined for that. Overall PostgreSQL load grew more than tenfold over the preceding year. Separately, the ImageGen launch drove a write-traffic surge of more than tenfold and added over 100 million users in a week; the deployment had one PostgreSQL SEV-0 in the preceding 12 months, during that launch.

Most of the protective work happens before a request reaches the primary. A cache hit avoids a database round trip. A cache miss waits for a pool slot, then for a replica to execute the query. A write waits on the primary, generates WAL, and adds replay work to every replica. Under load, the queues matter as much as the database’s raw execution speed: once pool wait or replay delay rises, adding retries can turn a slow request into more database work.

An operational dashboard needs pool wait separate from query execution time, and rejected requests beside completed ones. Compare the primary’s WAL generation rate with each replica’s receive and replay positions. Retained WAL storage needs an alarm alongside freshness. Replication slots can keep a disconnected consumer recoverable by retaining WAL, but unbounded retention can exhaust the upstream disk. A fleet can have healthy average query latency while one replica falls behind and another consumer quietly fills the volume. Those need separate alarms.