Replication and Scaling

Updated · 14 min read
hardPostgreSQL 18sqlreplicationread-replicasfailoverconnection-poolingshardingscalinginterview

Replication keeps live copies of a database on other servers, and scaling means handling more work than one server can. A single PostgreSQL server can go a long way, but sooner or later one of three things happens: it receives more reads than it can answer, more connections than it can hold, or it fails and the app goes down with it. Replication answers the first and the last: copies called replicas take reads and stand ready to replace the main server. Connection pooling answers the second. Sharding, splitting data across several servers, answers the rare case where even writes outgrow one machine. In this lesson, we will see how replicas follow the main server, why a replica can show old data (replication lag), what happens in a failover, how a pool shares a few connections among many app requests, and why sharding is the last step, not the first.

In One Minute

  • Scale up (a bigger server) before you scale out (more servers). It is simpler and often enough.
  • A primary takes all writes; replicas replay its changes and can answer reads.
  • Most replicas are asynchronous, so they can be slightly behind: replication lag. A user may not see the change they just made.
  • Failover promotes a replica to primary when the primary fails; with asynchronous replication, the last few changes can be lost.
  • A connection pool lets many requests share a few database connections.
  • Sharding splits data across servers by a key. It scales writes but makes joins, transactions and changes much harder.

Scale Up or Scale Out

Scaling up means a bigger server; scaling out means more servers.

Scale up (vertical)Scale out (horizontal)
WhatMore CPU, memory and faster disks for one serverSeveral servers sharing the work
Changes to the appNoneReads routed to replicas, or data split by shard
LimitThe biggest machine you can buy or rentMuch higher, at the cost of complexity
Helps withReads, writes and connectionsReads (replicas) or writes too (sharding)

Before either, make the queries cheaper. A missing index or a query that reads a whole table can use more of the server than all other queries together (Writing Fast Queries). Fixing it is free, and the improvement carries over to every server you add later.

How Replication Works

Every change to an ordinary table is first written to PostgreSQL's transaction log, the WAL (write-ahead log). A replica receives that log from the primary and replays it, so it ends up with the same data. This is called streaming replication. The replica is read-only: it answers SELECT queries, and refuses any statement that would change data.

A server can tell you which role it has:

SQL▶ Try it
SELECT pg_is_in_recovery() AS is_replica;
 
SELECT name, setting
FROM pg_settings
WHERE name IN ('wal_level', 'max_wal_senders', 'hot_standby',
               'synchronous_commit', 'synchronous_standby_names')
ORDER BY name;
Output
 is_replica
------------
 f
(1 row)
 
           name            | setting
---------------------------+---------
 hot_standby               | on
 max_wal_senders           | 10
 synchronous_commit        | on
 synchronous_standby_names |
 wal_level                 | replica
(5 rows)

Explanation: pg_is_in_recovery() is f (false) on a primary and t on a replica, which is always "recovering" by replaying the primary's log. wal_level = replica means the log holds enough detail for replicas. max_wal_senders is how many replicas (and backup tools) may stream from this server at once. hot_standby = on lets a replica answer queries while it replays. synchronous_standby_names is empty, which means replication is asynchronous: a commit doesn't wait for any replica.

On a primary, pg_stat_replication lists each connected replica. The Try it database has none, so the view is empty here:

SQL▶ Try it
SELECT client_addr, state, sync_state, replay_lag
FROM pg_stat_replication;
Output
 client_addr | state | sync_state | replay_lag
-------------+-------+------------+------------
(0 rows)

Explanation: On a primary with replicas, you get one row per replica. state is streaming when it is keeping up, sync_state says async or sync, and replay_lag is how far behind the replica is in time. Watching replay_lag is how teams notice a replica falling behind (Troubleshooting a Database).

Writes go to the primary; its log streams to the replicas, which answer reads

Replication Lag

Replication lag is the delay between a commit on the primary and the moment a replica shows it. It is usually milliseconds, but it grows when the replica is busy, the network is slow, or the primary writes a lot at once. The classic bug is reading your own write from a replica. Here is that bug, simulated with a copy of the table standing in for a replica that hasn't caught up yet:

SQL▶ Try it
-- The replica's copy, as it was a moment ago
CREATE TABLE replica_payments AS SELECT * FROM payments;
 
-- Advitha pays on the primary
INSERT INTO payments (student_id, course_id, amount_usd, due_on, paid_on, method)
VALUES (102, 4, 200.00, '2026-01-05', '2026-01-05', 'card');
 
-- Her payments page reads from the replica
SELECT count(*) AS advitha_payments_on_replica
FROM replica_payments
WHERE student_id = 102;
 
SELECT count(*) AS advitha_payments_on_primary
FROM payments
WHERE student_id = 102;
Output
SELECT 7
 
INSERT 0 1
 
 advitha_payments_on_replica
-----------------------------
                           0
(1 row)
 
 advitha_payments_on_primary
-----------------------------
                           1
(1 row)

Explanation: The INSERT committed on the primary, so the primary shows Advitha's payment. The replica's copy doesn't have it yet, so her payments page says she has paid nothing, and she might pay again. A real replica would catch up a moment later, but by then the page has already shown the wrong answer.

An example timeline: a read that reaches the replica before it catches up shows old data

Synchronous Replication and Failover

With synchronous replication, a commit waits until a replica confirms it has the change, so a failover loses nothing, but every commit is slower.

Asynchronous (default)Synchronous
Commit waits forThe primary's own diskThe primary and at least one replica
SpeedFastest commitsEach commit adds a network round trip
If the primary diesChanges not yet sent can be lostNo committed change is lost
Settingsynchronous_standby_names emptysynchronous_standby_names lists replicas

Failover makes a replica the new primary when the old one fails. Managed services do it automatically, usually within a minute or two. On your own servers, tools such as Patroni watch the primary and promote a replica. Either way, the app must reconnect: it connects through a name or address that moves to the new primary, and it must retry the transactions that failed during the switch.

Logical replication is a second kind, which copies changes to chosen tables as rows rather than copying the whole server's log. It is used to upgrade to a new major version with little downtime, or to feed another system. It needs wal_level = logical, which the Try it server doesn't have, and PostgreSQL warns you:

SQL▶ Try it
CREATE PUBLICATION fee_pub FOR TABLE payments, students;
 
SELECT pubname, tablename
FROM pg_publication_tables
ORDER BY tablename;
Output
WARNING:  "wal_level" is insufficient to publish logical changes
CREATE PUBLICATION
 
 pubname | tablename
---------+-----------
 fee_pub | payments
 fee_pub | students
(2 rows)

Explanation: The publication is created and lists its two tables, but the WARNING says no changes can actually be sent until the server runs with wal_level = logical. On another server, CREATE SUBSCRIPTION ... PUBLICATION fee_pub would receive the rows.

Connection Pooling

A connection pool keeps a small set of open database connections and lends them to requests, one at a time. In PostgreSQL every connection is a separate server process with its own memory, and max_connections (100 by default) caps how many can exist. A web app with 50 copies, each opening 20 connections, would need 1,000. Most of those would sit idle, but each still uses memory, and new ones are refused once the limit is reached:

text
FATAL:  sorry, too many clients already
Where the pool livesExamplesNotes
In the appHikariCP in Java, the pg pool in Node.js, psycopg's pool in PythonEach app copy has its own pool; their sizes add up
Between app and databasePgBouncer, Pgpool-II, the proxies cloud providers offerMany app copies share one pool

PgBouncer's transaction mode gives a connection to a client only for the length of one transaction, so a few dozen server connections can serve thousands of clients. The trade-off is that anything that lasts longer than a transaction, such as a SET without LOCAL, an advisory lock or a temporary table, may end up on another client's connection. Since version 1.21, PgBouncer can also keep track of named prepared statements in this mode, through its max_prepared_statements setting. A minimal setup looks like this:

text
[databases]
feetracker = host=10.0.1.5 port=5432 dbname=feetracker
 
[pgbouncer]
pool_mode = transaction
max_client_conn = 2000
default_pool_size = 20

A bigger pool is not always faster. A server with 8 CPU cores can only run about 8 queries at the same moment; hundreds of active connections just wait for each other. Start with a small pool per app, watch for requests waiting for a connection, and grow it slowly.

A pool lets many app connections share a few database connections

Sharding

Sharding splits the rows of a table across several database servers, called shards, using a shard key. Each shard holds only some of the students, and the app (or a layer such as Citus for PostgreSQL or Vitess for MySQL) sends each query to the right shard. A simple rule hashes the key and takes the remainder:

SQL▶ Try it
SELECT student_id, first_name,
       abs(hashint4(student_id)) % 4 AS shard
FROM students
ORDER BY student_id;
Output
 student_id | first_name | shard
------------+------------+-------
        101 | Srihitha   |     2
        102 | Advitha    |     0
        103 | Navika     |     1
(3 rows)

Explanation: hashint4 is PostgreSQL's built-in hash for integers. With four shards, each student goes to shard 0, 1, 2 or 3, and all of that student's enrollments and payments would live on the same shard, so their own pages need only one server. This is the same idea as hash partitioning (Partitioning), but across servers instead of inside one.

Sharding has real costs, which is why it comes last:

CostWhy
Queries across shards"Total fees by course" must ask every shard and add the answers
Transactions across shardsA change on two shards needs two-phase commit or careful app logic
JoinsOnly cheap when both rows share the shard key
Uneven shardsOne busy student or tenant can overload one shard (a "hot shard")
Adding shardsChanging % 4 to % 8 moves about half the rows; real systems plan for this
OperationsBackups, migrations and monitoring on every shard
Scale in this order; each step adds complexity

Common Mistakes

Reading your own write from a replica. The user doesn't see the change they just made. Read from the primary right after a write.

Treating a replica as a backup. Mistakes replicate in milliseconds. Keep backups with point-in-time recovery.

Giving every app copy a big pool. The pools add up past max_connections. Size pools for the total, or use PgBouncer.

Sharding too early. It makes every cross-customer report and every migration harder. Exhaust the simpler steps first.

Not planning for failover. The app must reconnect and retry. Test a failover before a real one happens.

Ignoring lag. Monitor replay_lag; a replica hours behind still answers queries, with old data.

Interview Corner

What is the difference between scaling up and scaling out?

Scaling up gives one server more CPU, memory and faster disks. Scaling out adds servers: replicas for reads, or shards for writes. Scaling up is simpler; scaling out goes further but adds complexity.

What is replication lag, and how do you handle it?

The delay before a replica shows a change committed on the primary. Send reads that must see the latest data, such as a user's own just-made change, to the primary; send reads that can be slightly old to replicas; and monitor lag.

Synchronous or asynchronous replication: what is the trade-off?

Synchronous replication waits for a replica to confirm each commit, so failover loses nothing, but commits are slower. Asynchronous is faster but can lose the last changes if the primary fails.

Why use a connection pool with PostgreSQL?

Each connection is a server process with its own memory, and max_connections limits how many can exist. A pool reuses a few connections for many requests, avoiding the cost of connecting and the limit.

What are the downsides of sharding?

Queries, joins and transactions across shards become hard or slow, shards can be uneven, adding shards means moving data, and every operation runs on every shard.

Practice

Challenge: The team is considering four shards, chosen by abs(hashint4(student_id)) % 4. Count how many payments would land on each shard. Is the data spread evenly?

Show solution
SQL▶ Try it
SELECT abs(hashint4(student_id)) % 4 AS shard,
       count(*)                      AS payments,
       sum(amount_usd)               AS total_usd
FROM payments
GROUP BY shard
ORDER BY shard;
Output
 shard | payments | total_usd
-------+----------+-----------
     1 |        2 |    450.00
     2 |        5 |   1700.00
(2 rows)

No. Five payments go to shard 2 (Srihitha's) and two to shard 1 (Navika's); Advitha has no payments yet, and shard 3 gets no one at all. With three students, hashing can't spread evenly. With thousands of students it evens out, but one very active student or customer can still make a hot shard. That's one more reason to wait until the data really needs sharding.

Quick check: Replication and scaling

4 questions
1Where should the query behind "Your payment was received" run, right after the payment is saved?
2What does pg_is_in_recovery() return on a streaming replica?
3Someone runs DELETE FROM payments with no WHERE on the primary. What happens on the replicas?
4Which step is usually tried last?

Key Takeaways

You want toUse
Know if a server is a replicaSELECT pg_is_in_recovery();
See replicas and their lagSELECT client_addr, state, replay_lag FROM pg_stat_replication; (on the primary)
Make commits wait for a replicasynchronous_standby_names
Copy chosen tables to another serverCREATE PUBLICATION and CREATE SUBSCRIPTION
Share connections among many clientsAn app pool, or PgBouncer in transaction mode
Spread rows across serversSharding by a key (Citus, Vitess, or app logic)

Was this tutorial helpful?

Lesson 100 of 115