A PostgreSQL Read Replica in Spring Boot: Route readOnly Transactions, Size the Pool, Find the Index, Read Your Own Writes
Read-only transactions go to a streaming PostgreSQL replica through one LazyConnectionDataSourceProxy. Pool sizes 2, 4 and 32 give p95 1,247, 623 and 782 ms; one index on the primary takes the search from 46.4 ms to 0.23 ms and the load test to 46,902 requests. And 499 of 500 reads right after a write miss on the replica, 0 on the primary.
What you will learn
- Route @Transactional(readOnly = true) to a replica with LazyConnectionDataSourceProxy and two Hikari pools
- Prove which server answered with pg_is_in_recovery()
- Measure the replica pool size and find the missing index instead
- Handle replica lag with read-your-own-writes on the primary for a few seconds
Before you start
- Replication and replica lag
- Spring @Transactional and JdbcClient
A replica is always a little behind, so the real decision is which reads can live with that. This article puts a Relay-style desk on PostgreSQL with one streaming replica, routes read-only transactions to it, measures what the pool size buys, and handles the lag. The concept itself, and which reads must go to the primary, is in replication and replica lag.
A primary and a streaming replica
The replica was copied once with pg_basebackup, and -R made it a standby that follows the primary's WAL. Both run in Docker with 4 CPUs each, and the table holds 300,000 tickets from 30,000 customers.
primary: select application_name, state from pg_stat_replication
application_name | state
------------------+-----------
walreceiver | streaming
replica: select pg_is_in_recovery()
pg_is_in_recovery
-------------------
t
The primary sees one replica, streaming. The replica says it is in recovery: it only applies what the primary sends.
One routing DataSource
@Configuration
public class ReadRoutingConfig {
@Value("${desk.db.password}")
private String password;
// one pool per server; the routing DataSource picks one per transaction
@Bean
DataSource dataSource(@Value("${desk.primary.url}") String primaryUrl,
@Value("${desk.replica.url}") String replicaUrl,
@Value("${desk.replica.pool-size}") int replicaPool) {
var primary = pool("primary", primaryUrl, 10);
var replica = pool("replica", replicaUrl, replicaPool);
replica.setReadOnly(true);
// lazy: the connection is taken at the first SQL, when readOnly is already known
var routing = new LazyConnectionDataSourceProxy(primary);
routing.setReadOnlyDataSource(replica);
return routing;
}
private HikariDataSource pool(String name, String url, int size) {
var pool = new HikariDataSource();
pool.setPoolName(name);
pool.setJdbcUrl(url);
pool.setUsername("desk");
pool.setPassword(password);
pool.setMaximumPoolSize(size);
return pool;
}
}
Two Hikari pools, one per server, and the replica pool is read-only. The trick is "lazy": the proxy takes a real connection at the first SQL statement, when Spring already knows whether the transaction is readOnly. The password comes from configuration, not from code.
// every row says which server answered
private static final String COLUMNS = "id, customer_email, subject, status, "
+ "case when pg_is_in_recovery() then 'replica' else 'primary' end as served_by";
// a write: no readOnly, so the primary
@Transactional
public Ticket create(String email, String subject) { ... }
// readOnly = true: the routing DataSource sends it to the replica
@Transactional(readOnly = true)
public Optional<Ticket> find(long id) { ... }
$ curl -s localhost:18570/api/tickets/42 | jq -c '{id, servedBy}'
{"id":42,"servedBy":"replica"}
$ curl -s -X POST -H "Content-Type: text/plain" -d "Cannot log in" "localhost:18570/api/[email protected]" | jq -c '{id, servedBy}'
{"id":300001,"servedBy":"primary"}
Measure the pool, then find the index
A k6 test runs a customer search with 64 agents, at three replica pool sizes:
| Replica pool | p95 | Requests |
|---|---|---|
| 2 | 1,247 ms | 713 |
| 4 | 623 ms | 1,256 |
| 32 | 782 ms | 1,556 |
Going from 2 to 4 connections almost doubled the requests. Eight times that, 32, gave about a quarter more and a worse p95. Past the replica's four cores, more connections mostly wait for each other. The pool is not what makes this search slow, so look at the query:
-> Seq Scan on tickets (actual time=0.023..46.239 rows=10.00 loops=1)
Rows Removed by Filter: 299991
Execution Time: 46.401 ms
-- CREATE INDEX on the primary, then the same EXPLAIN on the replica:
-> Bitmap Index Scan on tickets_customer_idx (actual time=0.052..0.052 rows=10.00 loops=1)
Execution Time: 0.230 ms
The index is created on the primary and reaches the replica through the WAL stream. 46.4 ms became 0.23 ms. With the same 4 connections, k6 then showed p95 40 ms and 46,902 requests. More connections bought a quarter more; one index bought 37 times the requests. (Reading query plans is covered in database index for an AI app.)
Living with lag
A probe creates a ticket and reads it straight back, 500 times:
$ curl -s -X POST "localhost:18570/api/lag-probe?n=500"
499 of 500 reads missed the new ticket
$ curl -s -X POST "localhost:18570/api/lag-probe?n=500&ownWrites=true"
0 of 500 reads missed the new ticket
With no delay added, the replica had not yet applied the write 499 times out of 500. That is the bug a user sees as "I just created a ticket and it says not found". The fix is read-your-own-writes: for a few seconds after a write, that user's reads go to the primary.
@PostMapping("/api/tickets")
public Ticket create(@RequestParam String customer, @RequestBody String subject,
HttpServletResponse response) {
var ticket = tickets.create(customer, subject);
// for the next 5 seconds, this user's reads go to the primary
var recentWrite = new Cookie("recent-write", "1");
recentWrite.setMaxAge(5);
response.addCookie(recentWrite);
return ticket;
}
@GetMapping("/api/tickets/{id}")
public ResponseEntity<Ticket> one(@PathVariable long id,
@CookieValue(name = "recent-write", required = false) String recentWrite) {
// a recent writer reads the primary; everyone else, the replica
var ticket = recentWrite != null
? tickets.findOnPrimary(id)
: tickets.find(id);
return ResponseEntity.of(ticket);
}
findOnPrimary is the same query with plain @Transactional, so it routes to the primary.
Emma creates ticket 301002 and reads it at once: {"id":301002,"servedBy":"primary"}. After sleep 6 the cookie has expired and the same read says "servedBy":"replica".
Recap
| Before | After | |
|---|---|---|
| Search, 64 agents | 1,256 requests, p95 623 ms | 46,902 requests, p95 40 ms |
| One search, EXPLAIN | Seq Scan, 46.4 ms | Bitmap Index Scan, 0.23 ms |
| Read straight after a write | 499 of 500 missed (replica) | 0 of 500 missed (primary) |
| Reads on the primary | All of them | Only your own, for 5 seconds |
Try it yourself: change one() to always call tickets.find(id), create a ticket and read it back at once. You will see the "not found" a user would.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Spring Boot Repository and Service Layer: Save and Read Data Without Writing SQL
A one-line JpaRepository interface and a small @Service class save and read blog posts with no SQL. Follow one save and one read through every layer, then prove it with a test.
Entities and H2 in Spring Boot: a Post Class Becomes a Table
The blog's cards are typed into HTML. A Post class with @Entity and @Id becomes the POST table in an in-memory H2 database: three pom lines, a few YAML settings, and Hibernate writes the create table SQL at startup.
Seed Data and Posts on the Homepage: CommandLineRunner, the Model and th:each
SeedData, a CommandLineRunner, saves three posts when the POST table is empty. HomeController puts postService.getAll() into the Model, and one postCard inside th:each becomes three cards. Three inserts at startup, one select per visit.
Pagination and Sorting on a Spring Boot Homepage: PageRequest In, Page Out
Eight posts, three to a page, newest first. HomeController turns ?page=1&sort=oldest into a PageRequest, PostService passes it to findAll(Pageable), H2 runs one select with an offset and one count, and the Page that comes back knows it is page 2 of 3.
