I have tuned PostgreSQL databases behind Java services for energy grid operators, e-commerce platforms, a health insurer and a VoIP monitoring product. The stack changed a lot over the years. The way slow queries show up did not: a page that used to load instantly now takes seconds, the connection pool runs dry under load, and someone suggests "just add more CPU".
More hardware rarely fixes it. A repeatable process does. This is the one I use, from finding the guilty query to making sure it never comes back.
1. Find the queries that actually hurt
Do not start with the query you think is slow. Start with data.
pg_stat_statements
pg_stat_statements aggregates execution statistics for every normalized query. It needs to be preloaded (on managed services like RDS or Azure you set this in the parameter group):
# postgresql.conf shared_preload_libraries = 'pg_stat_statements' After a restart:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements; SELECT query, calls, round(total_exec_time::numeric, 1) AS total_ms, round(mean_exec_time::numeric, 1) AS mean_ms, rows FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10; Sort by total_exec_time, not by mean_exec_time. A query that takes 15 ms but runs 2 million times a day costs you far more than a 3 second report that runs twice. In my experience the biggest wins almost always hide in that first group.
auto_explain
Knowing which query is slow is half the story. auto_explain logs the execution plan of slow statements as they happen in production, with the real parameters:
shared_preload_libraries = 'pg_stat_statements,auto_explain' auto_explain.log_min_duration = '500ms' auto_explain.log_analyze = on auto_explain.log_buffers = on auto_explain.log_timing = off # keeps the overhead low 2. Read the plan, not the SQL
Run the query with real parameter values:
EXPLAIN (ANALYZE, BUFFERS) SELECT ...; Careful: ANALYZE really executes the statement. For UPDATE or DELETE, wrap it in BEGIN; ... ROLLBACK;.
These are the patterns I look for first:
| What you see in the plan | What it usually means |
|---|---|
Seq Scan on a large table with a big Rows Removed by Filter | Missing or unusable index |
Estimated rows=12, actual rows=48210 | Stale statistics, the planner picks the wrong strategy |
Nested Loop with loops=50000 on the inner side | Bad estimate or missing index on the join column |
Sort Method: external merge Disk: ... | Sort spills to disk, no index supports the ORDER BY |
High shared read in Buffers | Data comes from disk, not from cache |
explain.dalibo.com is a great free tool to visualize larger plans.
3. Fix the usual suspects
Foreign keys without an index
PostgreSQL creates an index for primary keys and unique constraints, but not for foreign key columns. Every join or WHERE order_id = ? on such a column is a candidate for a sequential scan, and so is every DELETE on the parent table.
CREATE INDEX CONCURRENTLY idx_order_item_order_id ON order_item (order_id); CONCURRENTLY avoids locking the table for writes, but it cannot run inside a transaction. In Liquibase, set runInTransaction="false" on the changeset. In Flyway, add a script config file with executeInTransaction=false.
Composite indexes in the wrong order
For a query like this:
SELECT * FROM orders WHERE customer_id = ? AND status = 'OPEN' ORDER BY created_at DESC LIMIT 20; put the equality columns first and the sort column last:
CREATE INDEX CONCURRENTLY idx_orders_customer_open ON orders (customer_id, created_at) WHERE status = 'OPEN'; The partial index (WHERE status = 'OPEN') keeps it small if most orders are closed. PostgreSQL can read it backwards, so the DESC sort comes for free and the Sort node disappears from the plan.
Functions on indexed columns
WHERE lower(email) = lower(?) cannot use a plain index on email. Either index the expression:
CREATE INDEX CONCURRENTLY idx_users_email_lower ON users (lower(email)); or store the normalized value. The same applies to casts and to date functions such as date_trunc('day', created_at) = ?. Rewrite those as a range: created_at >= ? AND created_at < ?.
N+1 queries from JPA
The database looks fast, every single query takes 1 ms, and the endpoint still needs 3 seconds. That is the classic N+1 problem. Make it visible first:
logging.level.org.hibernate.SQL=debug For @ManyToOne associations an entity graph usually solves it:
@EntityGraph(attributePaths = "customer") List<Order> findByStatus(OrderStatus status); For collections combined with pagination, be careful: fetching a collection together with LIMIT makes Hibernate paginate in memory (warning HHH90003004). Batch fetching is the safer default here:
spring.jpa.properties.hibernate.default_batch_fetch_size=50 This turns N queries into roughly N/50 queries with an IN clause, without changing a single repository method.
Deep pagination with OFFSET
OFFSET 100000 LIMIT 50 means PostgreSQL reads and throws away 100,000 rows. Keyset pagination stays fast no matter how deep you go:
SELECT id, created_at, total FROM orders WHERE customer_id = :customerId AND (created_at, id) < (:lastCreatedAt, :lastId) ORDER BY created_at DESC, id DESC LIMIT 50; backed by an index on (customer_id, created_at, id). The client sends the last seen created_at and id instead of a page number.
Stale statistics after bulk loads
After large imports or migrations, autovacuum may not have analyzed the table yet, and the planner works with numbers from yesterday. A simple ANALYZE orders; at the end of the import job often fixes plans that looked "random".
4. Make sure it stays fixed
Tuning is worthless if the next feature brings the problem back. Two things have worked well for me.
Test against a real PostgreSQL, not H2. With Testcontainers and Spring Boot's @ServiceConnection this is a few lines, and you can even assert the number of statements to catch N+1 regressions in CI:
@SpringBootTest(properties = "spring.jpa.properties.hibernate.generate_statistics=true") @Testcontainers class OrderQueryCountTest { @Container @ServiceConnection static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:17"); @Autowired EntityManagerFactory entityManagerFactory; @Autowired OrderService orderService; @Test void loadsRecentOrdersWithoutNPlusOne() { Statistics stats = entityManagerFactory.unwrap(SessionFactory.class).getStatistics(); stats.clear(); orderService.findRecentOrders(42L); assertThat(stats.getPrepareStatementCount()).isLessThanOrEqualTo(2); } } Watch it in production. Spring Boot already exposes HikariCP pool metrics through Micrometer. Alerts on hikaricp_connections_pending and on the request latency of your critical endpoints, plus a weekly look at pg_stat_statements, catch most regressions before users do.
The short checklist
- Find the expensive queries with
pg_stat_statements, sorted by total time. - Capture real plans with
auto_explainandEXPLAIN (ANALYZE, BUFFERS). - Check foreign key indexes, index column order, functions on columns, N+1 and OFFSET pagination.
- Run
ANALYZEafter bulk loads. - Lock the fix in with Testcontainers tests and pool metrics.
None of this is exotic. That is exactly the point: most performance problems I have seen in Java backends were solved with these basics, not with a bigger database server.
What is the worst query plan you have ever found in production? I would love to read your stories in the comments.
I am a freelance Senior Java Backend and Platform Engineer based in Berlin, working with Spring Boot, PostgreSQL, Kafka and Kubernetes. If your team is fighting with a slow backend, feel free to reach out via daniel-heid.de.


