DEV Community

Daniel Heid
Daniel Heid

Posted on

Slow PostgreSQL Queries in Spring Boot: A Field Guide from Real Projects

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'
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

2. Read the plan, not the SQL

Run the query with real parameter values:

EXPLAIN (ANALYZE, BUFFERS)
SELECT ...;
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

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));
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

For @ManyToOne associations an entity graph usually solves it:

@EntityGraph(attributePaths = "customer")
List<Order> findByStatus(OrderStatus status);
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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

  1. Find the expensive queries with pg_stat_statements, sorted by total time.
  2. Capture real plans with auto_explain and EXPLAIN (ANALYZE, BUFFERS).
  3. Check foreign key indexes, index column order, functions on columns, N+1 and OFFSET pagination.
  4. Run ANALYZE after bulk loads.
  5. 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.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The sort-by-total-time rule is the one most teams get backwards, and it is the cheapest win in the whole guide — a 15 ms query at 2M calls a day is an 8-hour CPU bill nobody notices.

One detail I would add to the foreign-key section: on a busy parent table, the missing FK index does not just slow the join — it turns every DELETE on the parent into a full scan that holds locks longer, so the fix is also a lock-contention fix, not just a read fix.

Worst plan I have seen in production: a nested loop with loops=48000 on the inner side, estimated rows 8, actual 31000 — stale stats after a bulk import, exactly your section 3.6. ANALYZE fixed it in seconds after a week of people blaming the ORM. When the planner is right and the data really is skewed, do you reach for extended statistics (CREATE STATISTICS) or push the skew handling into the application?