Skip to content
Commitwise
Menu
Java Backend

Database performance

Make PostgreSQL queries fast and keep them fast, with B-tree and composite indexes in the right column order, reading EXPLAIN ANALYZE plans, avoiding index-killing query patterns, keyset pagination instead of OFFSET, batched writes with JPA, and knowing what indexes cost.

advanced

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

The orders page was fast at launch. A year later, with 40 million rows, “My orders” takes four seconds, the nightly import runs for six hours, and the database CPU sits at 90% every evening. Nobody changed the code. The data grew, and queries that scanned whole tables, paginated with large offsets and inserted rows one by one stopped being acceptable.

Most backend performance problems end up in the database, and most of them are fixed with a few tools: the right index, a look at the query plan, pagination that doesn’t get slower with every page, and batched writes. This lesson uses PostgreSQL, and the ideas carry over to other relational databases.

New to some of these? Open what you need, or skip ahead.

Basics:What is SQL?

SQL is the language for asking a relational database for data: select id, total from orders where customer_id = 42 order by created_at desc. Tables have rows and columns; queries filter (where), sort (order by), join tables and limit the result. JPA and Spring Data generate SQL for you, but the database still runs SQL. See Spring Data JPA and Hibernate.

Basics:What is a database index?

An index is a separate, sorted structure that points to rows, like the index at the back of a book. Instead of reading every page (every row) to find “customer 42”, the database looks the value up in the index and jumps to the matching rows. See database indexDatabase indexA sorted structure on one or more columns that lets the database find rows without reading the whole table.Open in glossary →.

Part Not started

Indexes and query plans

Without an index, the database answers where customer_id = 42 by reading every row in the table: a sequential scan. With 40 million orders, that’s slow no matter how fast the server is.

A B-tree index keeps the values of a column sorted, with pointers to the rows. Finding customer 42 takes a few steps, like looking up a word in a dictionary.

Indexes can cover several columns. An index on (customer_id, created_at) is sorted by customer first, then by date within each customer, like a phone book sorted by last name, then first name. That makes it perfect for “customer 42’s orders, newest first”, and useless for “all orders from yesterday”: you can’t use a phone book to find everyone named Ana.

To see what the database actually does, put EXPLAIN ANALYZE in front of a query. It shows the planQuery planThe steps a database chooses to execute a query (scans, index lookups, joins, sorts), shown with EXPLAIN.Open in glossary →: which index (if any) was used, how many rows each step produced, and how long it took.

PostgreSQL’s default B-tree supports equality, ranges, ORDER BY and prefix LIKE 'abc%' (with the right collation or text_pattern_ops). For composite indexes, put equality predicates first, then the range or sort column (the “ESR” rule: equality, sort, range), and include the tiebreaker for stable ordering; a query can use the index only through its leftmost columns. INCLUDE columns make index-only scans possible (helped by an up-to-date visibility map, i.e. vacuum). Partial indexes (where status = 'OPEN') index only hot rows; expression indexes (lower(email)) match queries that use the same expression. Index killers: functions or casts on the indexed column, leading wildcards, OR across different columns (sometimes rescued by bitmap OR), implicit type conversions, and low selectivity, where a scan is genuinely cheaper. Read plans with EXPLAIN (ANALYZE, BUFFERS): compare estimated vs actual rows (bad estimates → stale statistics or correlated columns; ANALYZE, extended statistics), find the node with the most time, and watch for Sort spilling to disk, nested loops over many rows, and Rows Removed by Filter. Indexes cost writes, disk and cache: drop unused ones (pg_stat_user_indexes.idx_scan = 0) and create new ones with CREATE INDEX CONCURRENTLY in production.

-- "My orders": one customer's orders, newest first, 50 at a time
select id, total, status, created_at
from orders
where customer_id = 42
order by created_at desc, id desc
limit 50;

-- Equality column first, then the sort columns in the same order and direction
create index concurrently orders_customer_created_idx
    on orders (customer_id, created_at desc, id desc);

explain (analyze, buffers)
select id, total, status, created_at from orders
where customer_id = 42 order by created_at desc, id desc limit 50;
-- Before the index:
Limit  (actual time=3812.4..3812.4 rows=50 loops=1)
  ->  Sort  (actual time=3812.4..3812.4 rows=50 loops=1)
        Sort Key: created_at DESC, id DESC
        ->  Seq Scan on orders  (rows=1840 loops=1)
              Filter: (customer_id = 42)
              Rows Removed by Filter: 39998160
-- After:
Limit  (actual time=0.041..0.118 rows=50 loops=1)
  ->  Index Scan using orders_customer_created_idx on orders  (rows=50 loops=1)
        Index Cond: (customer_id = 42)
        Buffers: shared hit=53
  • Before: a Seq Scan read all 40 million rows, threw away 39,998,160 of them (Rows Removed by Filter), then sorted the rest: 3.8 seconds.
  • After: an Index Scan jumps to customer 42’s entries, which are already sorted newest first, and stops after 50 rows: about 0.1 ms. No sort step at all.
  • concurrently builds the index without blocking writes to the table, which matters on a live system.

Predict the output

With only the index (customer_id, created_at desc, id desc), a report runs: select count(*) from orders where created_at >= now() - interval '1 day'. Can it use the index efficiently?

Spot the bugYesterday's orders are slow even with an index on created_at

Tap the line with the bug.

// index: create index orders_created_idx on orders (created_at);
@Query(
    value = """
        select * from orders
        where date(created_at) = :day
        """,
    nativeQuery = true,
)
fun ordersOn(day: LocalDate): List<Order>
// index: create index orders_created_idx on orders (created_at);
@Query(value = """
    select * from orders
    where date(created_at) = :day
    """, nativeQuery = true)
List<Order> ordersOn(LocalDate day);

Reading plans quickly

Plan nodeMeansLook at
Seq ScanReads the whole tableFine for small tables or large fractions; bad with a selective filter
Index Scan / Index Only ScanSeeks via an index (only-scan avoids the table)Heap Fetches on index-only scans (vacuum)
Bitmap Heap ScanCollects matches from one or more indexes, then reads pagesGood for medium selectivity and ORs
Nested LoopFor each outer row, look up inner rowsFine with few outer rows and an index on the inner side
Hash Join / Merge JoinJoin large setswork_mem spills (Batches > 1)
SortExplicit sortSort Method: external merge means it spilled to disk

Estimated vs actual rows that differ by orders of magnitude are the root of most bad plans: refresh statistics (ANALYZE), raise the statistics target for skewed columns, or add extended statistics for correlated columns. Use pg_stat_statements to find which queries consume the most total time; optimize those, not the slowest single query you happen to notice.

Exercisemedium

Choose the index

A support tool searches tickets: select * from tickets where status = 'OPEN' and assignee_id = ? order by priority desc, created_at limit 20. 95% of tickets are closed. Which index would you create?

›

Which columns are compared with =, and which decide the order? Do you need closed tickets in the index at all?

SolutionTry it yourself first

A partial composite index that matches the query:

create index concurrently tickets_open_assignee_idx
    on tickets (assignee_id, priority desc, created_at)
    where status = 'OPEN';
  • assignee_id first (equality), then priority desc, created_at in the query’s sort order, so no sort step is needed and the limit stops early.
  • where status = 'OPEN' keeps only 5% of tickets in the index: it’s small, stays in memory, and costs nothing when closed tickets are written.
  • The query must include status = 'OPEN' for the database to use a partial index, which it does.
  • B-tree: equality, range, sort, prefix LIKE. Composite: equality → sort → range (ESR); only leftmost-prefix queries seek.
  • INCLUDE for index-only scans; partial indexes for hot subsets; expression indexes must match the query expression.
  • Killers: functions/casts on indexed columns (date(col)), leading wildcards, type mismatches, low selectivity.
  • EXPLAIN (ANALYZE, BUFFERS): estimated vs actual rows, the costliest node, sorts spilling, rows removed by filter. pg_stat_statements for total time.
  • Indexes cost writes and memory: drop unused ones; CREATE INDEX CONCURRENTLY in production.

Check this part

  1. What does a Seq Scan in a query plan mean?

  2. An index exists on email. Why can't where lower(email) = ? use it?

  3. For where tenant_id = ? and status = ? order by created_at desc, which column order is best?

  4. Estimated rows: 10, actual rows: 2,000,000 on a join. Likely cause?

A B-tree index makes equality and range lookups and sorts fast. In a composite index, column order matters: equality columns first, then the range or sort column; a query must use the leftmost columns to benefit. Functions on indexed columns, leading-wildcard LIKE and mismatched types prevent index use. EXPLAIN (ANALYZE, BUFFERS) shows the plan the database actually ran: look for sequential scans on big tables, wrong row estimates and sorts. Every index slows writes.

Part Not started

Pagination, batching and reads at scale

Pagination: limit 50 offset 100000 looks cheap, but the database still has to find and skip 100,000 rows to return the next 50. Page 2,000 is much slower than page 1, and if new orders arrive between requests, users see duplicates or miss rows.

Keyset paginationKeyset paginationPaging by continuing after the last row's sort key instead of skipping a number of rows with OFFSET.Open in glossary → (also called cursor or seek pagination) remembers where the last page ended: “give me 50 orders older than this one”. With an index on the sort columns, every page costs the same, and new rows don’t shift anything. The trade-off: you can go to “next” and “previous”, but not jump to page 2,000, which users rarely do anyway.

Batching writes: inserting 100,000 rows one at a time means 100,000 round trips to the database. Sending them in batches of, say, 500 does the same work in a few hundred round trips.

OFFSET cost grows linearly with the offset (rows are produced and discarded) and is unstable under concurrent inserts. Keyset pagination filters on the last seen sort key, (created_at, id) < (:createdAt, :id), with an index matching the order, giving constant cost per page and stable results; encode the key as an opaque cursor for clients (see mobile pagination). Spring Data supports it with ScrollPosition.keyset() and Window<T>. Write batching with Hibernate needs hibernate.jdbc.batch_size (20–100), order_inserts/order_updates, and sequence-based ids (GenerationType.SEQUENCE with an allocationSize that matches the sequence increment): IDENTITY forces an insert per entity to learn its id, silently disabling batching. With PostgreSQL, reWriteBatchedInserts=true turns batches into multi-row inserts; for bulk loads, COPY beats everything. Also: avoid N+1 queries (fetch joins, entity graphs, projections), keep transactions short (long ones hold locks and block vacuum), use read replicas for reads that tolerate replication lag (reports, search), and remember that read-your-writes paths must go to the primary.

interface OrderRepository : JpaRepository<Order, Long> {

    @Query(
        """
        select o from Order o
        where o.customerId = :customerId
          and (o.createdAt < :createdAt or (o.createdAt = :createdAt and o.id < :id))
        order by o.createdAt desc, o.id desc
        """
    )
    fun pageAfter(customerId: Long, createdAt: Instant, id: Long, limit: Limit): List<Order>

    fun findByCustomerIdOrderByCreatedAtDescIdDesc(customerId: Long, limit: Limit): List<Order>   // first page
}

// Service: the cursor is the last order's (createdAt, id), sent to the client as an opaque string
val page = if (cursor == null) {
    orders.findByCustomerIdOrderByCreatedAtDescIdDesc(customerId, Limit.of(50))
} else {
    orders.pageAfter(customerId, cursor.createdAt, cursor.id, Limit.of(50))
}
public interface OrderRepository extends JpaRepository<Order, Long> {

    @Query("""
        select o from Order o
        where o.customerId = :customerId
          and (o.createdAt < :createdAt or (o.createdAt = :createdAt and o.id < :id))
        order by o.createdAt desc, o.id desc
        """)
    List<Order> pageAfter(Long customerId, Instant createdAt, Long id, Limit limit);

    List<Order> findByCustomerIdOrderByCreatedAtDescIdDesc(Long customerId, Limit limit);   // first page
}

// Service: the cursor is the last order's (createdAt, id), sent to the client as an opaque string
List<Order> page = cursor == null
    ? orders.findByCustomerIdOrderByCreatedAtDescIdDesc(customerId, Limit.of(50))
    : orders.pageAfter(customerId, cursor.createdAt(), cursor.id(), Limit.of(50));
  • The first page is simply the newest 50 orders.
  • Every next page asks for orders that come after the last one the client saw, in the same order: older createdAt, or the same createdAt with a smaller id (the id breaks ties between orders created at the same moment).
  • With the index (customer_id, created_at desc, id desc) from the previous part, each page is an index seek plus 50 rows, whether it’s page 2 or page 2,000.

Predict the output

A customer has 200,000 orders. With limit 50 offset N, roughly how many rows does the database have to read to return page 4,000 (offset 199,950)?

Production puzzles

Spot the bugAn import that never batches

Tap the line with the bug.

@Entity
class Product(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    var id: Long? = null,
    var sku: String = "",
    var name: String = "",
)

// spring.jpa.properties.hibernate.jdbc.batch_size=500
@Transactional
fun importAll(rows: List<ProductRow>) {
    productRepository.saveAll(rows.map(Product::from))
}
@Entity
class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;
    String sku;
    String name;
}

// spring.jpa.properties.hibernate.jdbc.batch_size=500
@Transactional
void importAll(List<ProductRow> rows) {
    productRepository.saveAll(rows.stream().map(Product::from).toList());
}

Exercisehard

Fix the evening slowdown

Every evening the database CPU reaches 90% and the orders API’s p99 climbs from 80 ms to 2 s. pg_stat_statements shows the top three queries by total time: an order list with offset, a dashboard count(*) over the last 30 days run every 10 seconds by each open admin tab, and an N+1 loading order items. Plan the fixes in order.

›

Rank by total time and by how cheap each fix is. Which of these queries need to hit the primary at all?

SolutionTry it yourself first
  1. The N+1 (often the largest total): replace per-order item queries with a fetch join or a batch fetch (@BatchSize, default_batch_fetch_size) or a projection query. Cheap, big win.
  2. The order list: keyset pagination with a matching composite index; API returns an opaque cursor. Mobile and web clients switch to “load more”.
  3. The dashboard count: it doesn’t need to be exact to the second. Cache it for a minute (or maintain a counter table updated by events), and run it on a read replica. Ten tabs no longer mean ten scans every ten seconds.
  4. Verify with pg_stat_statements deltas, p99 on the API, and database CPU; add an alert on top query total time; keep EXPLAIN (ANALYZE, BUFFERS) output for the new plans in the PR.
Exercisemedium

Turn offset paging into keyset

An endpoint GET /products?page=N runs select * from products order by name limit 20 offset N*20. Names aren’t unique. Rewrite the query for keyset pagination and say what the client sends instead of page.

›

Names aren’t unique, so you need a second column to break ties.

SolutionTry it yourself first
-- first page
select * from products order by name, id limit 20;

-- next pages: continue after the last row the client received
select * from products
where (name, id) > (:lastName, :lastId)
order by name, id
limit 20;

create index concurrently products_name_id_idx on products (name, id);

The client sends a cursor instead of a page number: the last product’s name and id, usually encoded as one opaque string (?after=eyJuYW1lIjoi...). PostgreSQL’s row comparison (name, id) > (…) matches the order by name, id exactly, and id breaks ties between equal names.

  • OFFSET reads and discards skipped rows and shifts under inserts; keyset (sortKey, id) < (:last…) with a matching index is constant per page. Spring Data: ScrollPosition.keyset(), Window<T>, Limit.
  • Batching: hibernate.jdbc.batch_size, order_inserts, SEQUENCE ids with matching allocationSize (IDENTITY disables batching), reWriteBatchedInserts=true, flush/clear; COPY for bulk.
  • N+1: fetch joins, entity graphs, batch fetching, projections.
  • Short transactions; replicas for lag-tolerant reads, primary for read-your-writes. pg_stat_statements to rank work by total time.

Check this part

  1. Why does page 2,000 with OFFSET get slow?

  2. In keyset pagination, why add id to the sort and the cursor?

  3. Why does GenerationType.IDENTITY prevent Hibernate insert batching?

  4. Which reads can safely go to a replica?

OFFSET pagination reads and discards every skipped row, so deep pages get slower; keyset pagination continues from the last row's sort key and stays constant. Batch writes: Hibernate batches inserts only with sequence-based ids (IDENTITY disables batching) and hibernate.jdbc.batch_size; PostgreSQL's driver can rewrite batches into multi-row inserts. Avoid N+1 queries, keep transactions short, and send reads that tolerate lag to replicas.

Key takeaways

  • An index lets the database find rows without reading the whole table.
  • In multi-column indexes, order matters: equality columns first, then the sort column.
  • Don’t wrap indexed columns in functions; compare ranges instead.
  • Use keyset pagination instead of large offsets, and batch large writes.
  • Read EXPLAIN (ANALYZE, BUFFERS) and fix the costliest node; rank work with pg_stat_statements.
  • Design indexes for real queries (ESR, partial, covering) and drop the unused ones.
  • Keyset pagination, sequence ids for batching, short transactions, replicas for lag-tolerant reads.
  • Treat performance as ongoing: data grows, plans change, statistics drift.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.