Load balancing reads across PostgreSQL replicas

Read traffic can move to PostgreSQL standbys only when the application tolerates replica lag and the routing layer knows which servers are healthy. This page covers the routing options, their trade-offs and the checks to run before go-live.

On this page

Load balancing reads across PostgreSQL replicas: when it pays off

If your primary is under read pressure, or you built standbys for failover and now want to use them, PostgreSQL's built-in options can send reads to hot standbys, but only when the application accepts that a replica may return data slightly behind the primary. Hot standbys serve read-only queries, and nothing more. They accept SELECT statements and read-only transactions, but they cannot take writes, create temporary objects that persist, or run anything that modifies data. Replication also applies changes asynchronously by default, so a read on a standby reflects the primary as of some earlier point. Before routing traffic, confirm with your application owners which screens and jobs can tolerate that delay.

Hot standby is the right tool when read volume is the bottleneck, the queries are mostly reporting, search or lookups, and the cost of an occasional stale row is low. It is the wrong first move when the primary is saturated by writes, by a few expensive queries, or by lock contention. Adding replicas does nothing for write throughput, and a standby running long analytical queries can be cancelled by replay conflicts, which you must measure before depending on it. In those cases, examine the slow queries and indexes first, or consider a connection pooler such as PgBouncer to reduce connection overhead, or an application cache for data that changes rarely.

Reading from standbys also changes your failover and capacity plans. A replica that serves traffic must be sized for that load during a failover, and its lag must be monitored because an unnoticed lag spike silently changes what users see. Decide up front which requests need read-your-writes guarantees, such as a user checking a payment they just made, and send those to the primary. Record the routing rules as part of the design so the team can review them when the topology changes.

Which routing option fits your application

The PostgreSQL client library (libpq) accepts a multi-host connection string and can choose a host by role with target_session_attrs, and it can spread connections across candidate hosts with load_balance_hosts. The PostgreSQL high availability documentation describes this as a client-side feature, so no extra network component is needed. The application team controls the choice because the connection string lives in their configuration. Points to weigh:

  • Role selection: target_session_attrs=read-only makes a client skip servers that accept writes, which covers standbys but does not check how far behind they are.
  • Spreading load: load_balance_hosts=random picks among eligible hosts at connect time, so balance depends on how long connections live.
  • Failure mode: a client that connected to a standby keeps that session even if the standby falls behind or is promoted.
  • Driver support: each language driver must pass these options through to libpq, so confirm the behavior in your driver version.
  • Pooling interaction: pooled connections are opened once, so routing decisions made at connect time may not reflect later changes.

Before relying on this, test which hosts a sample client actually reaches during a failover and during a replica outage.

Configuration options and when each fits

This table compares the client, proxy and standby settings that decide where read traffic lands, and what each one gives up. Read it by first choosing where routing happens (client library, HAProxy or application code), then checking the standby settings that govern how stale or conflicting reads behave.

Setting or componentWhat it doesWhen it fitsWhat it trades away
target_session_attrs = read-writelibpq connects only to a host that accepts writesApplication connections that must always reach the primaryReads on the same string go to the primary, so no read offload
target_session_attrs = read-onlylibpq connects only to a host in read-only modeDedicated reporting or read-only connection stringsFails if no standby is reachable, so pair with a fallback host list
target_session_attrs = prefer-standbylibpq tries standbys first and falls back to the primaryRead-heavy services that can tolerate some replica lagReplica lag is invisible to the client, so recent writes may not show
load_balance_hosts = randomlibpq picks a random host from the list at connect timeSpreading new connections across several standbys without a proxyConnection counts per host can skew; no health awareness beyond connect failure
HAProxy backend with health checksRoutes traffic to hosts that pass a check for the required roleCentral routing for many clients and language stacksAdds a hop and a component to operate; check settings must match your Patroni version
Patroni REST API role endpointsHealth checks query the node role, such as primary or replicaTelling HAProxy which node is the leader and which are standbysEndpoint names and status codes vary by version; confirm them in your Patroni documentation
hot_standby (standby)Lets the standby accept read-only queries while replaying WALAny standby that serves readsOff means the standby cannot serve queries, so it cannot be a read target
max_standby_streaming_delay (standby)Sets how long replay may wait before cancelling conflicting queriesKeeping replay close to the primary while tolerating short query cancellationsLonger values delay replay and increase lag; shorter values cancel long reads
hot_standby_feedback (standby)Tells the primary about the oldest snapshot still needed on the standbyLong reports that must not be cancelled by vacuum cleanupPrimary table bloat can grow because vacuum waits for standby queries

How to set up read routing across standbys

This sequence takes a PostgreSQL primary and its standbys from a verified hot standby setup to a routing layer that sends writes to the primary and reads only to healthy standbys, proven under failover.

  1. Confirm hot standby and replica health

    Confirm that each standby is configured with hot_standby enabled, that it is streaming from the primary, and that replication lag is within the range your application can tolerate. The DBA or platform engineer runs the checks on every node. Run SELECT pg_is_in_recovery(); on the primary, which should return false, and on each standby, which should return true. On the primary, query pg_stat_replication to confirm every standby is streaming. The step is done when every standby reports in recovery and appears in pg_stat_replication with a lag value you have recorded as your baseline.

  2. Define the read and write endpoints

    Decide the two names your applications will use: one endpoint for writes that always resolves to the current primary, and one for reads that resolves only to standbys. Write down which connection strings or hostnames map to each, and which queries are allowed on the read path. Include the rule that any session needing read-your-writes consistency uses the write endpoint for a defined window after a write. The owner is the application architect with the DBA. The step is done when the endpoint table is approved and each application team has confirmed which of its queries belong on each path.

  3. Configure client or HAProxy routing

    Choose where the routing decision lives. The libpq route uses a multi-host connection string with target_session_attrs to select a writable primary or a standby, and load_balance_hosts to spread read connections across standbys. The HAProxy route runs separate listeners for the read and write endpoints and backends that select nodes by health check. Configure one approach, or confirm your Patroni setup supports the HAProxy design you planned. The engineer making the change records the exact connection strings or HAProxy configuration in version control. The step is done when a test client connected through the read endpoint reports pg_is_in_recovery() as true and a client on the write endpoint reports false.

  4. Set health checks so only standbys receive reads

    Configure the health check that decides which nodes can serve reads. For HAProxy with Patroni, the check should accept only nodes whose REST API reports a replica role, and it must exclude the leader from the read backend. Confirm the check behaves correctly if a standby falls too far behind or stops, since a stalled standby should drop out of the read pool. Ask your Patroni and HAProxy maintainers to confirm the exact endpoint and status codes for your versions. The step is done when a standby that is stopped or paused is removed from the read backend, and the primary never appears in it.

  5. Verify routing under normal load

    Run a controlled read workload through the read endpoint and a write workload through the write endpoint, then record which node serves each connection. Count sessions per node from pg_stat_activity or your load balancer statistics, and confirm the read workload spreads across standbys while no read connection lands on the primary. Test one read-your-writes path: write a row, then read it through the path your design assigns. The step is done when the distribution is recorded, no read session is on the primary, and the read-your-writes test returns the expected result every time.

  6. Test a switchover with reads in flight

    Run a planned switchover while the read workload is active. Watch the read backend and the write endpoint: the former primary should leave the write path, a standby should be promoted, and the former primary should rejoin as a standby and enter the read pool. Measure how long reads or writes fail during the change and whether clients reconnect without manual steps. Confirm that no session on the write endpoint is still attached to a standby after promotion. The step is done when routing has shifted to the new topology and the observed error window is documented for your runbook.

  7. Test an unplanned failure and record the results

    Stop the primary process or isolate its network in a test environment and observe what the routing layer does. Confirm that the write endpoint moves to the new primary only after promotion, and that stale read connections to the old primary are not served. Check that application retry logic handles dropped sessions, and record the reconnection behavior. Repeat the test for a standby failure, which should only remove that node from reads. The step is done when both failure tests produce the expected routing change, and the results are stored with the configuration as evidence for your operations team.

How replica lag breaks read-your-writes

Asynchronous standbys can trail the primary, so a user who writes a row and immediately reads it back through a replica may not see the change. The commit succeeded on the primary, but the standby that served the read had not yet replayed that WAL. For a load balancer that spreads reads across replicas, this is the central trade-off: every read that can land on a standby is a read that can return the previous state. Before you choose a pattern, measure how far your standbys actually trail under normal and peak write load, using the lag views on the primary and the replay position on each standby, and confirm with your own workload how often the gap matters.

Teams handle this with three patterns, and most production systems combine them. The first routes a session to the primary for a short window after it performs a write, so the user's own follow-up reads see their changes. The second pins specific critical reads, such as an account balance check before a payment or a status page after a submission, to the primary through a separate pool or a target_session_attrs=read-write connection string. The third accepts staleness for queries where a few seconds of old data is harmless, such as dashboards, search results or reports, and sends only those to replicas. The application or its data access layer should make this choice explicit per query, because a load balancer on its own cannot know which read depends on a prior write.

Synchronous replication changes the trade-off from read freshness to commit latency. With synchronous_commit set so that commits wait for a standby, a committed transaction is already applied on that standby, which removes most of the window in which a replica read can miss a write. The cost is that every write waits for the acknowledgment, and if the synchronous standby is slow or unavailable, writes stall or degrade depending on your configuration. Confirm the exact behavior for your PostgreSQL version and settings in the PostgreSQL high availability documentation before relying on it, and test write latency and failure handling with your real network before deciding whether synchronous commit or routing critical reads to the primary fits your recovery and latency targets.

Query conflicts on hot standby and how to reduce them

Read traffic on a standby competes with replay of changes from the primary. When replay needs rows or locks that a running query still uses, PostgreSQL either delays replay or cancels the query, so the routing design has to account for both outcomes.

Vacuum cleanup removes rows still in use

The primary vacuums dead row versions that the standby may still need for an open query. Replay of the cleanup record can force cancellation of that query with a conflict error. Check how often cancellations appear in standby logs under your real read mix, and confirm that short interactive reads are not the ones being cancelled most often.

HA and replication docs

Locks held by the primary

Operations such as ACCESS EXCLUSIVE locks taken on the primary are replayed on standbys. A standby query holding a conflicting lock on the same relation can be cancelled when replay needs that lock. Long reads on tables that get frequent DDL or table rewrites are the most exposed, so map which tables fall into that group before choosing replicas.

Replay of DDL and table changes

Some schema changes replayed from the primary conflict with active standby queries, including drops and rewrites of tables a reader is using. Review your migration process for DDL timing and confirm with your team which deployment windows can coincide with analytical reads on the standby. This is a process control as much as a configuration setting.

Settings that control conflict handling

The parameters max_standby_streaming_delay and max_standby_archive_delay set how long replay may wait before cancelling conflicting queries, and hot_standby_feedback changes which side absorbs the cost. Decide per replica whether lag or cancellation is the acceptable failure, then document the values and confirm them against your PostgreSQL version's current reference.

Hot standby feedback and primary bloat

Setting hot_standby_feedback to on tells the primary which row versions the standby still needs, which prevents conflicts but can cause table and index bloat on the primary during long queries. Measure bloat on the primary after enabling it, and watch for replication slot or xmin effects in your monitoring before changing the setting on production clusters.

Dedicated standbys for long analytical reads

Routing long reports to a standby configured with delay and feedback settings separate from the interactive pool keeps cancellations away from user-facing queries. The trade-off is an extra server to run and monitor. Define the query classes first, then decide whether a dedicated replica, a separate HAProxy backend, or a different connection string serves them.

How read and write requests reach primary and standbys

The application connects through two endpoints: a write endpoint that must reach the primary, and a read endpoint that can reach any healthy standby. HAProxy checks each Patroni REST API to decide which node is the leader and which are replicas, and streaming replication carries WAL from the primary to every standby. Check that the write route never lands on a standby, and that replicas drop out of the read pool when their lag or health fails.

Write and read traffic routed by health checks over streaming replication.

Questions teams ask before routing reads to replicas

What drives the cost of routing reads to PostgreSQL replicas?

The cost depends mostly on how much of the application has to change and how much testing the team needs before trusting the routing. Three components matter: application changes to send reads and writes to different endpoints, the routing layer itself (libpq settings, HAProxy or another proxy with health checks), and testing of replica lag and hot standby query conflicts. Application work is often the largest component when the code does not already separate read and write paths. Routing configuration is comparatively small. Testing scales with the number of read paths that must tolerate stale data. Ask any quote to break these three components out, state which are one-time and which recur (health check tuning, lag alerting and replica capacity reviews continue after go-live), and name who owns each piece: your developers, your database team, or DeployOpen under a written scope.

How long does a read replica routing project take?

Duration depends on the environment more than on the routing technology. The main variables are how many services issue reads, whether those services already support a second connection string, how many replicas exist and how far they lag under peak load, and how quickly the team can run representative test traffic. A single application with clean read and write separation moves much faster than a monolith with reads scattered through shared data-access code. Environments without a staging database that resembles production usually add time, because lag and conflict behavior cannot be measured without realistic load. Ask for a timeline that lists the test environment dependency explicitly, since it is the item most often delayed.

What does our team need to provide for a replica routing project?

The team needs to provide four things before work starts. First, a test environment with at least one primary and standby that resembles production in size and configuration, plus a way to generate read and write load. Second, administrative access to the database, the proxy or load balancer, and the application's deployment pipeline, with enough rights to change connection settings and reload configuration. Third, named application owners for each service that issues reads, who can confirm which queries tolerate stale results and which must see their own writes. Fourth, agreement on replica lag thresholds and who responds when they are breached. Missing application owners is the most common reason routing decisions get delayed, because the staleness rules cannot be set without them.

Can our in-house database team route reads to replicas by itself?

Often yes, if the team already runs streaming replication, understands hot standby behavior and can change application data-access code. The routing configuration itself is standard. The harder parts are judgment calls: deciding which reads can tolerate lag, handling read-your-writes requirements after a user saves data, and recognizing query conflicts that cancel long reads on a standby. A team that lacks application-side ownership or has not load-tested a standby will usually spend more time on those decisions than on configuration. An external partner can take on the build, the lag and conflict tests, and the runbook, or review an in-house design. Whichever route you choose, write the scope down before work starts so the handover is clear.

Does load balancing reads work without Patroni?

Read routing can work without Patroni, but the failover side needs its own mechanism. Libpq offers target_session_attrs and load_balance_hosts in the client connection string, which let applications pick standbys without an extra proxy. PostgreSQL does not detect a failed primary or promote a standby by itself, so a cluster without Patroni, repmgr, pg_auto_failover or another external tool needs a documented manual or scripted failover procedure. Without automated failover, the routing layer has no reliable way to know which node is the current primary after a crash. Check the PostgreSQL high availability documentation for the supported options and confirm which tool your design uses before you finalize the routing approach.

What breaks when reads go to standbys?

Three problems appear most often. Replica lag makes reads return older data, so a user who saves a change and reloads the page may not see it. Hot standby query conflicts occur when the primary removes row versions or applies changes that a long-running read on the standby still needs, which cancels that query, and the frequency depends on workload and settings such as max_standby_streaming_delay. Connection routing can also send traffic to a node that is healthy but overloaded or lagging, which needs a health check that considers lag, not only whether the port answers. Test each of these with production-like load and agree on handling for each class of query before go-live.

When should we choose a different scaling approach instead of read replicas?

Choose a different approach when the main constraint is not read volume or when replicas cannot meet the freshness the application needs. If the bottleneck is slow queries, missing indexes or lock contention, tuning or query changes will usually help more than another node. If writes are the limit, read replicas do not help, and the options shift toward partitioning, workload separation or a different architecture. If nearly every read must reflect the latest write, a routing layer adds complexity without much benefit. Caching in the application, a dedicated analytics store for heavy reporting, or connection pooling with PgBouncer may fit better. Measure where time is spent before committing to replicas.

Where to read the PostgreSQL documentation

Before you choose a routing design, read the official high availability, load balancing and replication chapter of the PostgreSQL documentation. It covers hot standby servers that answer read-only queries, the difference between synchronous and asynchronous replication, and the point that PostgreSQL does not balance load across standbys by itself. That last fact is the reason your routing layer, whether it is libpq connection parameters, HAProxy or a custom service, has to be designed and owned as a separate component. Pay particular attention to the sections on replication lag and query conflicts on hot standby, because those determine which queries are safe to send to a replica and which must always reach the primary.

Then read the failover chapter, which explains that PostgreSQL does not detect a failed primary or notify standbys on its own. Your read routing depends on that behavior: after a promotion, the host that used to serve reads may be the new primary, and a client that caches a host list can keep sending writes to a server that is now read-only. Confirm the exact PostgreSQL version you will run against the supported release list before you rely on any parameter behavior, and check the documentation for that version, since client-side options such as target_session_attrs and load_balance_hosts depend on the libpq version your applications link against. Write down the answers to these questions before you draw the routing diagram.

How DeployOpen scopes and delivers read routing

DeployOpen plans read routing as part of the cluster design, not as an afterthought bolted onto an application. The written scope fixes which replicas take reads, how clients find the primary, and how lag and conflicts are handled before any build starts.

How we scope

  • Inventory which queries can tolerate replica lag and which need read-your-writes guarantees
  • Agree the routing layer, whether libpq settings, HAProxy through Patroni, or application-side logic
  • Set written acceptance criteria for lag, failover behavior and query conflict handling

How we build

  • Configure target_session_attrs and load_balance_hosts in client connection strings and test them
  • Build HAProxy health checks against Patroni endpoints so only healthy standbys receive reads
  • Tune hot standby settings for conflict behavior and document the trade-offs with the application team

How we hand over

  • Document each routing rule, the replica lag threshold and the fallback to the primary
  • Provide test scripts that prove writes reach the primary and reads reach standbys after failover
  • Walk operators through lag monitoring and the runbook for removing a misbehaving replica

How we support

  • Engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts
  • Ongoing support, upgrades and continuous testing of the routing setup are available as retainers
  • Confirm with DeployOpen how routing changes are reviewed when application query patterns change

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.