Database Operations · Lesson 89 of 112

Database Monitoring and Slow Queries

What you will learn

  • Why a database must be monitored
  • Which signals to watch
  • How to build a slow query log
  • How to go from a slow query to its cause and fix
  • Why averages hide problems

1. You cannot fix what you cannot see

Nobody can watch a database all day. Without monitoring you learn about problems from angry users: "the site is slow". Monitoring means collecting numbers all the time, so that you can see trouble coming, find the cause, and confirm that your fix worked.

2. What to watch

Most databases, in any product, are watched through the same few groups of signals. The exact names of the numbers differ by product (read your product's documentation), but the ideas are the same:

Signal Question it answers
Query time How long do queries take? Which ones are slowest?
Throughput How many queries per second? Is it rising?
Errors Are there failed queries, deadlocks (lesson 6.6) or refused connections?
Connections How many are open? Is the pool (lesson 12.1) nearly full?
Disk How much space is left? How fast is it growing (lesson 12.4)?
Memory and CPU Is the machine itself short of resources?
Replication delay If you have replicas (lesson 12.5), how far behind are they?

A good habit is to keep these as graphs over time and to set alerts for the dangerous ones (for example, disk almost full). A number only means something when you can compare it with what was normal yesterday.

3. The slow query log

The most useful single tool is a list of queries that took longer than a limit. Many database products can write one for you; check the documentation for the setting. The idea is simple enough to build yourself, with a wrapper that times every query:

import sqlite3, time

con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, customer INTEGER, total INTEGER)")
con.executemany("INSERT INTO orders (customer, total) VALUES (?, ?)", [(i % 500, i % 97) for i in range(200000)])
con.commit()

SLOW_SECONDS = 0.005          # 5 milliseconds, small only because this demo is small
slow_log = []

def timed(sql, params=()):
    start = time.perf_counter()
    rows = con.execute(sql, params).fetchall()
    took = time.perf_counter() - start
    if took > SLOW_SECONDS:
        slow_log.append(sql)
    return rows

def run_all():
    slow_log.clear()
    timed("SELECT * FROM orders WHERE id = ?", (500,))
    timed("SELECT * FROM orders WHERE customer = ?", (42,))
    timed("SELECT customer, SUM(total) FROM orders GROUP BY customer")
    return list(slow_log)

print("slow before the index:")
for sql in run_all():
    print("  ", sql)
slow before the index:
   SELECT * FROM orders WHERE customer = ?
   SELECT customer, SUM(total) FROM orders GROUP BY customer

The lookup by id is fast. The lookup by customer and the grouped total were slower than the limit. (The exact times vary with the machine, so the log shows only which queries crossed the line. The limit of 5 ms is small only because the demo table is small; real limits are often chosen in tenths of a second or more.)

4. From slow query to fix

A slow query log tells you what is slow. The next step is why, and lesson 7.6 gave us the tool: the query plan.

print(con.execute("EXPLAIN QUERY PLAN SELECT * FROM orders WHERE customer = 42").fetchall())
con.execute("CREATE INDEX idx_customer ON orders(customer)")
print(con.execute("EXPLAIN QUERY PLAN SELECT * FROM orders WHERE customer = 42").fetchall())
[(2, 0, 216, 'SCAN orders')]
[(3, 0, 62, 'SEARCH orders USING INDEX idx_customer (customer=?)')]

SCAN orders means the database read every row; SEARCH ... USING INDEX means it jumped straight to the matching rows. After adding the index, run the same workload and look at the log again, which is the step people forget: confirm the fix.

The same loop on the sample data. This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top). The timing needs a big table, but the plan (the "why" step) can be read on the sample tables. The index lives in your browser's copy; Reset data removes it. For EXPLAIN QUERY PLAN the cell shows only the plan text.

EXPLAIN QUERY PLAN SELECT * FROM customers WHERE phone = '+35 49854883';
CREATE INDEX idx_customers_phone ON customers (phone);
EXPLAIN QUERY PLAN SELECT * FROM customers WHERE phone = '+35 49854883';
plan
--------------
SCAN customers
(1 row)

plan
----------------------------------------------------------
SEARCH customers USING INDEX idx_customers_phone (phone=?)
(1 row)
EXPLAIN QUERY PLAN SELECT * FROM transactions WHERE description = 'Refund';
CREATE INDEX idx_txn_description ON transactions (description);
EXPLAIN QUERY PLAN SELECT * FROM transactions WHERE description = 'Refund';
plan
-----------------
SCAN transactions
(1 row)

plan
-------------------------------------------------------------------
SEARCH transactions USING INDEX idx_txn_description (description=?)
(1 row)
EXPLAIN QUERY PLAN SELECT * FROM attendance WHERE class_date = '2026-02-02';
CREATE INDEX idx_attendance_date ON attendance (class_date);
EXPLAIN QUERY PLAN SELECT * FROM attendance WHERE class_date = '2026-02-02';
plan
---------------
SCAN attendance
(1 row)

plan
----------------------------------------------------------------
SEARCH attendance USING INDEX idx_attendance_date (class_date=?)
(1 row)
print("slow after the index:")
for sql in run_all():
    print("  ", sql)
slow after the index:
   SELECT customer, SUM(total) FROM orders GROUP BY customer

The WHERE customer = ? query is gone from the log. The grouped total remains: it must add up all 200,000 rows by nature. An index on customer will not remove that work. For a query like this the answers are different: ask whether it needs to run so often, whether the result can be saved for a while, or whether it belongs in a separate analytics database (chapter 13).

Worked example: "the site is slow every morning"

The tailor shop's staff complain that the orders page crawls at 9 a.m. The owner has monitoring in place.

Step What the owner looks at What it shows
1. When graphs of query time slow only from 9:00 to 9:30
2. What slow query log for that period one query, run 400 times: orders by customer phone
3. Why query plan of that query SCAN, no index on phone
4. Fix create an index on phone (lesson 7.3)
5. Confirm the next morning's log and graph the query has left the log; the page is fast

The story is made up, but the five steps (when, what, why, fix, confirm) are the normal loop.

5. Averages hide problems

Suppose 99 queries take 10 ms and one takes 10 seconds. The average is about 110 ms, which looks fine, while one user waited 10 seconds. That is why people watch the slowest queries and percentiles (for example the time within which 95% or 99% of queries finish), not only the average. Record the slowest cases, not only the typical ones.

Common mistakes

  • No monitoring until something breaks.
  • Watching only the average and missing the worst cases.
  • Setting an alert for everything, so that real alerts are ignored. Alert on things a person must act on.
  • Adding an index without checking that the plan changed and the query left the log.
  • Measuring on a tiny test database and trusting the result for production.

Key takeaways

  • Monitoring collects numbers continuously so that you see trouble early and can confirm fixes.
  • Watch query time, throughput, errors, connections, disk, memory and CPU, and replica delay.
  • A slow query log records the queries that exceed a limit.
  • The loop is: when, what, why (query plan), fix, confirm.
  • Look at the slowest queries and percentiles, not only the average.

Practice

1. Why is a single number, such as "2 GB used", not very useful on its own?

Show answer

Without history you cannot tell whether it is normal, growing or about to be a problem. A trend over time gives it meaning.

2. What does a slow query log contain?

Show answer

The queries that took longer than a chosen limit (and usually when they ran and how long they took).

3. A logged query shows SCAN orders in its plan. What is the likely fix?

Show answer

An index on the column used in the WHERE clause (lesson 7.3), then check the plan changes to SEARCH ... USING INDEX and that the query leaves the log.

4. After adding the index in the lesson, the GROUP BY query was still slow. Why?

Show answer

It has to read and add up all 200,000 rows, so an index on customer does not remove the work. It needs a different answer, such as running it less often, saving the result for a while or moving it to an analytics database.

5. 99 queries take 10 ms and one takes 10 seconds. Why does the average (about 110 ms) mislead?

Show answer

It hides the one very slow request that a real user experienced. Percentiles and the slowest queries show it.

6. Name the five steps of the loop in the worked example.

Show answer

When it is slow, what query is slow, why (query plan), fix, and confirm the fix.