Search posts

Local-first PWA sync: last-writer-wins done carefully
Exactly-once doesn’t come for free: Kafka, Flink and ClickHouse
Building an end-to-end encrypted chat app with libsodium

Stale InnoDB statistics made MySQL hash-join a million rows

table_rows was 0, so MySQL chose a hash join over a 1M-row table. Finding it in performance_schema, the ANALYZE fix (160 to 1,000+ req/s), and how to check.

Written by
Published
Reading time
7 min
Written against
MySQL 8.4, Sequelize 6
Stale InnoDB statistics made MySQL hash-join a million rows

A load test of my bidding app topped out at 160 requests per second, with MySQL using 9.4 CPUs. Every other service on that MySQL server queued behind it. The query was a paginated list with an indexed join, and the code had not changed. Why would MySQL scan a million rows for a join it has an index for? Because its statistics said the table was empty. One ANALYZE later, the same test passed 1,000 requests per second with a p95 of 2 ms.

This post is about the hospital procurement app behind it (Node.js, Sequelize, MySQL 8.4), whose bidding workflow I wrote about earlier. It covers where to look when MySQL eats CPU, how a hash join replaced an index lookup, the fix, what I could not explain, and how to check your own tables.

The symptom: one app's list starves the whole server

The test sent a mix of read requests to the app: dashboard, statistics, the list of biddings, one bidding, activities, and a few small lists. Each request type got its share of the load. The result:

Before After ANALYZE
Throughput ~160 req/s ≥1,000 req/s, ceiling not reached
p95 latency — 2 ms
MySQL CPU 9.4 —
Errors — 0

The worse part was not the app. MySQL is shared on that machine. At 9.4 CPUs for one app's reads, the other services on that server slowed down with it. A slow query on a shared database is never only one app's problem.

Where to look: the statement digest summary

When MySQL's CPU is high and no single query is slow on its own, the performance schema answers "which statement shape is doing the work". events_statements_summary_by_digest groups statements by their normalized text and keeps totals per group:

SELECT DIGEST_TEXT, COUNT_STAR,
       SUM_ROWS_EXAMINED, SUM_ROWS_SENT,
       ROUND(SUM_TIMER_WAIT / 1e12, 1) AS total_s
FROM performance_schema.events_statements_summary_by_digest
WHERE SCHEMA_NAME = 'app'
ORDER BY SUM_TIMER_WAIT DESC
LIMIT 5;

The column that gives it away is the ratio of rows examined to rows sent. A page of 10 biddings should not examine a million rows. That ratio points at the plan, not at the data size or the hardware.

The query: a page of biddings with their equipment

The list comes from Sequelize's findAndCountAll, which loads each bidding's equipment to sum quantities and prices for the row. Shortened from the app's bidding service:

const { count, rows } = await Bidding.findAndCountAll({
  attributes: ['id', 'proposalName', 'proposalStatus', 'activityStatus', 'createdAt'],
  where,
  include: [
    { model: Equipment, attributes: ['quantity', 'unitPrice'] },
    { model: Department, as: 'department', attributes: ['id', 'departmentName'] },
  ],
  order: [[safeSortKey, safeSortDir]],
  limit: pageSize,
  offset,
  distinct: true,
});

With a limit and a one-to-many include, Sequelize selects the page of biddings in a subquery and then joins Equipment onto it. Equipment has about a million rows and an index on its BiddingId foreign key. The plan I expected: take the 10 biddings, look up each one's equipment through the index, done.

What MySQL did instead: a hash join over the whole table

MySQL uses hash joins by default whenever possible. A hash join reads one side completely into a hash table and probes it with the other side. It is the right choice when no index can serve the join, or when both sides are small.

The optimizer picks between plans by estimated cost, and the estimates come from table statistics. Mine said table_rows was 0 for every table of the app, and for most tables of the other databases on the same server. To an optimizer that believes Equipment is empty, reading all of it into a hash table looks free. In reality that was a million rows per request, about 194 ms of CPU each. Even a few dozen list requests per second kept MySQL near 10 CPUs.

EXPLAIN FORMAT=TREE shows this directly: the docs call it the only format that shows hash join usage, and it names the operator, for example Left hash join. With an index lookup, you would see ref access on the BiddingId index instead.

The fix: refresh the statistics

mysqlcheck --analyze --all-databases

mysqlcheck --analyze runs ANALYZE TABLE on each table. For InnoDB it makes random dives into each index tree and rewrites the persistent statistics. It does not rebuild the table or change data, and the docs call it fast on InnoDB because it samples instead of reading every row. It does hold a read lock on each table while it runs. Right after it, the optimizer chose the index, and the rerun of the test reached 1,000 requests per second without finding the limit.

I ran it on every database, not only the app's: the other databases on the server had the same stale statistics.

Why the statistics were stale: what I know and what I don't

InnoDB keeps persistent statistics by default, and with innodb_stats_auto_recalc (also on by default) it recalculates them when more than 10% of a table's rows change. The docs add that the recalculation runs in the background, so it can lag behind a large change.

The ANALYZE TABLE page is more direct: with persistent statistics, "it is important to run ANALYZE TABLE after major changes to index column data, as statistics are not recalculated periodically (such as after a server restart)." My data reached this server through a restore of a mysqldump file when production moved to a new machine. Somewhere along the way, the statistics stayed at their empty-table values. I did not find the exact step that skipped the recalculation, and I would rather say that than guess. What I did learn is that relying on the background recalculation after a bulk load is not enough. When I upgraded the Postgres server on the same machine, the upgrade script loaded the dump, compared row counts, and ran an analyze before starting the apps. The MySQL restore needs the same step.

How to check your own tables

Compare the estimate with reality for the tables you care about:

SELECT TABLE_NAME, TABLE_ROWS
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'app'
ORDER BY TABLE_NAME;

SELECT COUNT(*) FROM app.Equipment;

Two things to know before trusting that first query:

  • TABLE_ROWS is an estimate for InnoDB. The docs say it "may vary from the actual value by as much as 40% to 50%". Off by half is normal. Zero for a table with a million rows is not.
  • The information_schema values are cached, for 24 hours by default (information_schema_stats_expiry). A stale number there may be the cache, not the optimizer's view. mysql.innodb_table_stats (column n_rows) shows what InnoDB itself has stored, and ANALYZE TABLE refreshes both.

Then run EXPLAIN FORMAT=TREE on the slow statement before and after the analyze. A plan that changes from a hash join to ref access on the index tells you the statistics were the cause.

What this does not fix

  • It is not a one-time fix. Statistics drift again after bulk loads, restores and large deletes. The analyze belongs at the end of every restore, the same way my Postgres upgrade script already does it, and the check above after any large data change.
  • Sampling can still mislead. ANALYZE TABLE samples a fixed number of pages (innodb_stats_persistent_sample_pages). Very skewed data can produce poor estimates even right after an analyze, and that needs more sample pages or a histogram.

Summary

  • When MySQL's CPU is high, read events_statements_summary_by_digest and compare rows examined with rows sent. A large ratio points at the plan.
  • The optimizer chooses plans from statistics. With table_rows at 0, a hash join that scans a million-row table looked cheaper than an index lookup.
  • mysqlcheck --analyze --all-databases (ANALYZE TABLE) only refreshes statistics, and it took the app from 160 to over 1,000 requests per second.
  • After a bulk load or restore, run ANALYZE TABLE yourself. The automatic recalculation is asynchronous and did not cover my case.
  • information_schema.TABLES is approximate and cached for 24 hours. Use mysql.innodb_table_stats, COUNT(*) and EXPLAIN to confirm.
  • A slow query on a shared database slows every app on it.

If you've hit stale optimizer statistics in MySQL or Postgres, or automated the check, I'd love to compare notes. My email is on the home page.