跪拜 Guibai
← Back to the summary

MySQL Tuning Past the Index Fix: Explain Estimates, Change Buffer, and Flush Stalls

How to Tune MySQL

When the database is slow, nine out of ten people immediately say "just add an index." Adding an index certainly helps, but that is only the entry-level question of tuning. Today I'll go through the places in database tuning that are truly worth spending time on, all of which are useful in everyday development.

1. The right way to approach tuning

What most people call tuning actually refers only to SQL tuning, but problems at the execution layer can slow the database down just as much.

My habit is: after writing a piece of business logic that involves SQL, run it locally first, use explain to look at the execution plan: whether the index that should be used is actually being used, and whether the number of scanned rows is within expectations. Once confirmed fine, then put it online to look at real latency.

One pitfall to warn about first: this process only holds for SELECT queries. Never try modifying SQL directly against the production database. If something goes wrong there is no regret medicine.

Also, before MySQL 8.0 there was the query cache mechanism, and I stepped on that pitfall. At the time, local tests were fine, but once online, response times fluctuated wildly. After a long investigation I found the cache was causing trouble: as soon as one row in a table updated, all cache for that table was cleared. The cache kept invalidating, so speed naturally went up and down.

So for anyone on versions below 8.0, remember to add SQL_NO_CACHE to the SQL before benchmarking, to rule out cache interference and see the true query latency.

2. Explain is not omnipotent

Many people treat explain output as gospel, but the scanned row count it gives is only an estimate.

MySQL organizes data by pages. It counts index cardinality using a sampling method: randomly pick N data pages, count how many distinct values are in them, take the average, then multiply by the total number of index pages. Data keeps changing, but statistics are not updated in real time, so the estimated row count often does not match reality.

A more subtle problem is selecting the wrong index. For example, index A scans 100 rows and index B only scans 20 rows, yet the optimizer may choose A. Because it does not only look at scanned rows; it also calculates other costs: using A does not require a table lookup (回表), while using B may require one. Converted to cost, A is actually "cheaper."

If you find explain's estimate differs wildly from reality, you can:

  1. Run analyze table <table_name> to recompute index statistics;
  2. Use force index to force the correct index;
  3. Rewrite the SQL;
  4. Drop the index that misleads the optimizer and rebuild a more reasonable one.

3. Advanced index techniques

Covering index

If the fields a query needs are already in the index, there is no need to go back to the primary key index for another lookup. Take e-commerce as an example: querying a product page from the product table, the product id is already in the index, which saves one tree search. Fewer table lookups naturally means faster queries.

Composite index

For example, if you often query stock by product name, you can build a composite index on (name, stock). Once name hits, stock is taken directly from the index without a table lookup.

But don't build composite indexes carelessly; the more fields, the more space they take. Combined with the leftmost prefix principle, prefix-fuzzy queries like name like '程序员%' can also use the index; sometimes just adjusting the field order brings the SQL back to life.

Index pushdown

An optimization introduced in MySQL 5.6. Previously for combined-condition queries, after the index hit name, the remaining conditions had to be checked one by one via table lookups. After 5.6, during the index traversal phase, the fields already present in the index can be used to filter a first round; rows that don't satisfy are skipped directly, and the number of table lookups drops significantly.

Normal index or unique index

This choice is related to the change buffer. When updating data, if the target data page is in memory, just change it directly; if it's not in memory, a normal index can first record the update action into the change buffer without reading the page from disk immediately, and wait until the next time that page is actually accessed to execute the recorded actions. This process is called merge. The change buffer has a copy in memory and is also persisted to disk.

Unique indexes don't get this treatment; they must immediately determine whether the value duplicates, so only normal indexes can use the change buffer. Its proportion of the buffer pool can be adjusted with innodb_change_buffer_max_size.

For write-heavy, read-light businesses, such as billing and log systems, this mechanism saves a lot of disk reads and the benefit is obvious; if you read immediately after writing, merge is triggered right away, which only adds trouble.

Prefix index

For long fields like email, building a full index takes too much space; you can index only the first few characters. The cost is that the index doesn't hold complete information, so queries may still need to go back to the table. Long fields can also be preprocessed, such as truncation, reversal, or hashing.

But be careful: doing function operations on an indexed field breaks the orderliness of the index. A write like where id + 1 = 9999 can't use the index; change it to where id = 9998.

Two easy-to-miss pitfalls

  1. Implicit type conversion: phone is a character type, but you compare it with a number;
  2. Character set conversion: two tables have different character sets, and during a join a cast or convert function is silently added.

In essence both wrap the indexed field in a function, and the index is simply disabled.

4. SQL suddenly stutters — flush may be the culprit

redo log is the log InnoDB uses to record update operations. Write the log first, then later slowly flush to disk; this is the WAL approach. As a result, data in memory and on disk is momentarily inconsistent. Pages not yet synced are called dirty pages; synced ones are clean pages.

When are dirty pages flushed? Four situations:

  1. redo log is full; the system has to stop and advance the checkpoint to free space; at this point all updates pause. Many occasional online stutters are caused by this;
  2. Memory is insufficient and data pages must be evicted; dirty pages must first be flushed to disk to free space;
  3. MySQL decides the system is idle and flushes opportunistically;
  4. Before normal shutdown, all dirty pages are flushed.

To control the flush rhythm, set innodb_io_capacity properly to tell InnoDB how much IO capacity the machine's disk actually has. This value can be derived by stress-testing disk IOPS with a tool like fio.

Also, in MySQL 8.0 the default value of innodb_flush_neighbors was changed to 0. This parameter controls whether adjacent pages are flushed together with the dirty page. In the mechanical disk era, doing so reduced seek time and handled it in one go; on SSDs it's purely a drag.

When you actually hit a slow query, the troubleshooting order is roughly these steps: first look at the execution plan, then check whether the index was disabled by type conversion or function calls, and only at the end suspect flush.

If anything in this article is imprecise, corrections are welcome in the comments.