Skip to content

Database bottlenecks: how to find them before production

B2Bnetwork team · · 6 min

System performance

In brief

You find database bottlenecks by combining a load test with measurements on the database side: a list of the queries with the greatest total time, their execution plans, lock waits, and the state of the connection pool. The key condition is production-scale data, because a query plan on a small table can be completely different from the plan on a large one. Most problems come down to a few queries without a proper index, the N+1 pattern from object-relational mapping, hot rows, and a connection pool that is too small or too large.

What a database bottleneck looks like during a test

A database bottleneck has a characteristic picture: response times rise while the application servers have idle CPU, because their threads are waiting for the database. Typical symptoms:

  • the wait time for a connection from the pool grows, and the logs show timeouts when acquiring a connection,
  • the database CPU or disk operations hit their limit at a load the application still handles,
  • throughput stops growing even though the generator keeps adding users,
  • adding application servers does not improve the result, and sometimes makes it worse, because more parallel queries go to the database.

This picture has to be confirmed with a measurement on the database side. Without it, it is easy to tune the application when the problem sits in a single query.

The most expensive queries and execution plans

The first step is a list of queries sorted by total execution time, not by the time of a single execution. A query that takes 5 ms but runs 2 million times an hour loads the database more than a report that takes a minute. Each database has its own tools for this: in PostgreSQL the pg_stat_statements extension, in Oracle the AWR and ASH reports, in SQL Server Query Store.

An example for PostgreSQL (from version 13 the columns are called `total_exec_time` and `mean_exec_time`):

SELECT query, calls, total_exec_time, mean_exec_time, rows
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

For the few queries at the top of the list, you check the execution plan. In PostgreSQL, `EXPLAIN (ANALYZE, BUFFERS)` runs the query and shows the actual number of rows at each step and the number of pages read. Warning signs are a full read of a large table where a few rows would do, a large gap between the estimated and actual row counts (stale statistics), and a sort that does not fit in memory. The auto_explain module writes the plans of slow queries to the log automatically, which is useful during a long test.

Production-scale data

A query plan depends on table sizes and data distribution, so a test on a small database may not reveal any problem. On a table with a thousand rows, a full scan is the fastest route and a missing index bothers no one. On a table with a hundred million rows, the same query takes seconds.

Before the test you therefore need data whose size and distribution are close to production: the number of customers, several years of transaction history, and an uneven distribution (a few corporate customers with millions of operations next to millions of customers with a handful). In an operator's billing or a banking system, a good source is an anonymized copy of production; how to prepare it in line with GDPR is described in the article Test data and GDPR. We gathered the requirements for the environment itself in the article Environment for performance testing.

Locks, hot rows, and long transactions

Some bottlenecks use neither CPU nor disk, they simply make sessions wait. Typical causes:

  • Hot row. Many transactions update the same row, for example an invoice number counter or the balance of a technical account. Under load, transactions queue up and throughput drops to one transaction at a time.
  • Long transactions. A transaction opened by a batch job, or by an application that calls an external API in the middle of the transaction, holds locks and blocks others.
  • Deadlocks. Two transactions lock resources in opposite order; the database aborts one of them and the application reports an error.

Diagnosis relies on the database's wait and lock views (in PostgreSQL, among others, `pg_stat_activity` and `pg_locks`) and on wait event statistics in Oracle and SQL Server. The fixes usually lie in the design: sequences instead of counters in a table, shorter transactions, a fixed locking order.

Connection pool and the N+1 pattern

A connection pool can be a bottleneck in both directions. A pool that is too small makes application threads wait even though the database has free resources. A pool that is too large, with many application servers, opens hundreds of simultaneous queries that compete for the same cores and locks, and the database runs slower than with fewer connections. You choose the pool size by measuring in the test, starting from a small value, and you compare the total of connections from all servers with the database limit.

The N+1 pattern is a classic object-relational mapping problem: the application fetches a list of 50 orders with one query, and then fetches the items for each order separately. Instead of one query, the database receives 51. A functional test does not show this; under load, the list of the most frequent queries shows the same short query executed millions of times.

A work plan before production

  1. Prepare production-scale data and turn on query measurement in the database before the test, not after it.
  2. Run a load test at the forecast level and collect the list of queries by total time.
  3. For the first few queries, check the plans, the indexes, and the number of executions per business transaction.
  4. Check lock waits and the state of the connection pool at the peak of the test.
  5. Fix, repeat the test, and compare the query list with the previous one.
  6. Run an endurance test to see how tables and indexes grow over time.

An example of performance testing before a change in a billing system is the case study Performance testing of a billing system during a tariff change.

Questions and answers

How do I know the bottleneck is in the database and not in the application?

Compare the time spent in the database with the total response time. If request traces or the application profiler show that most of the time is spent waiting for queries or for a connection from the pool, and the application servers have idle CPU, the problem lies in the database or in access to it. The confirmation is the list of queries and waits on the database side itself.

Is it enough to add indexes?

Sometimes, but every index slows down writes and takes up space, so you add one for a specific query from the list of the most expensive ones, not just in case. An index will not help with a hot row, long transactions, or the N+1 pattern. After every change you have to repeat the test, because fixing one query often exposes the next.

How large does the test data need to be?

Large enough that query plans and database cache hits match production. The safe route is a volume close to production with a growth forecast for a year or two. A smaller database calls for caution: results from it do not scale linearly to production.

Is it possible to look for bottlenecks without a load test?

Partly. The list of the most expensive queries from production and the execution plans will reveal many problems without generating traffic. A load test is needed for phenomena that appear only under concurrency: locks, connection pool exhaustion, and new queries that production has not yet seen.

What it looks like in a project

Your system slows down under load? We'll find where it loses time.

Let's talk

Read more: System performance