Tune MySQL ‘Join’ Buffers for Better Query Performance

Updated

MySQL performance tuning illustration

In MySQL 8.0.20 and later, join_buffer_size sizes the hash join buffer. It is not a dial you turn for a smooth percentage gain — on the workload measured below it did nothing until the buffer was large enough for the hash table to stop spilling to disk, then it stopped mattering again. Find your own threshold rather than copying a number:

-- see whether the join is even using a join buffer
EXPLAIN FORMAT=TREE SELECT ... ;

-- raise it for one session only, and measure
SET SESSION join_buffer_size = 4*1024*1024;

Keep it a session or per-query setting. join_buffer_size is allocated per join, per connection, so a large global value multiplied by your connection count is how servers run out of memory.

What join_buffer_size controls in MySQL 8.0.20 and later

Before 8.0.20, join_buffer_size sized the buffer for the Block Nested-Loop join algorithm. That algorithm is gone — the MySQL 8.0 manual says of the block_nested_loop optimizer switch: “Beginning with MySQL 8.0.20, the flag controls hash joins only, and the block nested loop algorithm is no longer supported.”

Hash join took over the same variable. The hash join documentation: “Memory usage by hash joins can be controlled using the join_buffer_size system variable; a hash join cannot use more memory than this amount. When the memory required for a hash join exceeds the amount available, MySQL handles this by using files on disk.”

That last sentence is the whole tuning story. Below the threshold the build side is chunked out to temporary files; above it everything stays in memory. There is no gradient in between.

MySQL does not have a sort-merge join

Tuning articles sometimes tabulate “MySQL join algorithms” including a sort-merge join. MySQL has never implemented one. Grepping the 8.4 manual’s three join-algorithm pages for “sort-merge” returns zero matches, and the optimizer agrees — on an unindexed equi-join of two 200,000-row tables:

mysql> EXPLAIN FORMAT=TREE
    -> SELECT COUNT(*) FROM orders_a a JOIN orders_b b ON a.k = b.k;

-> Aggregate: count(0)  (cost=4.4e+9 rows=1)
    -> Inner hash join (b.k = a.k)  (cost=4e+9 rows=4e+9)
        -> Table scan on b  (cost=0.01 rows=200000)
        -> Hash
            -> Table scan on a  (cost=20000 rows=199996)

Add an index on the join column and the plan leaves the join buffer behind entirely:

-> Nested loop inner join  (cost=1.02e+6 rows=7.93e+6)
    -> Table scan on a  (cost=20168 rows=199360)
    -> Covering index lookup on b using idx_b_k (k=a.k)  (cost=1.04 rows=39.8)

Cost estimate drops from 4×109 to 1×106. If your slow join has no index on the join column, indexing it is worth more than any value of join_buffer_size.

Join buffer size vs query time

Method: two InnoDB tables, 200,000 rows each, an INT join column with 5,000 distinct values (≈40 rows per key per table, ≈8,000,000 matched rows), a CHAR(40) payload, no index on the join column. Query: SELECT COUNT(*) FROM orders_a a JOIN orders_b b ON a.k = b.k. Timing is taken inside the server with NOW(6) brackets, excluding client connection time. One warm-up per size, then seven timed runs; median reported with min and max. Created_tmp_files is sampled around each batch, divided by iteration count.

Hardware: Apple M3 Max (14 cores), 36 GB RAM, macOS 26.6 arm64, MySQL 8.4.10, innodb_buffer_pool_size = 134217728 (128 MB), stock optimizer_switch. Unedited script output:

      join_buffer_size    median_ms     min_ms     max_ms  Created_tmp_files
      128KB                   204.5      201.8      240.6                128
      256KB                   209.4      207.5      210.6                128
      512KB                   213.0      210.9      214.6                128
      1024KB                  219.4      216.9      227.9                128
      2048KB                  186.4      179.1      197.0                  0
      4096KB                  183.3      177.2      192.1                  0
      8192KB                  185.6      179.5      189.4                  0
      16384KB                 182.8      175.5      185.9                  0
      65536KB                 185.3      181.9      193.4                  0

      total improvement from 128KB to 64MB on this run: 9.4% (204.5ms -> 185.3ms)

Reading the numbers

From 128 KB to 1 MB nothing improves; the medians drift slightly upward (204.5 → 219.4 ms), which is noise — the spread at a single size is comparable to the spread across the whole range. All four created 128 temporary files per query: the hash table did not fit, so the join spilled.

At 2 MB the spill stops, Created_tmp_files goes to 0, and the median drops to 186.4 ms. From 2 MB to 64 MB — a 32× increase — nothing further happens. Total improvement across a 512× range of buffer sizes on this run: 9.4%, effectively all of it one step at one threshold.

The shape reproduced across six independent sweeps on this machine: 128 KB medians ranged 202.8–218.4 ms, 64 MB medians 182.3–187.8 ms, and the spill boundary sat at 2 MB in every sweep that instrumented it. The end-to-end figure, however, moved between 7.4% and 15.2% depending on the run. That spread is the point: the threshold is a solid, mechanical result; the percentage is not a number anyone should quote to one decimal place — including us.

How to find your own threshold

  1. Confirm a hash join is being used. EXPLAIN FORMAT=TREE on the real query. Inner hash join means join_buffer_size is in play; index lookups mean it is not, and changing the variable will do nothing.
  2. Check whether it is spilling. SHOW GLOBAL STATUS LIKE 'Created_tmp_files' before and after. A non-zero delta means the hash table exceeded the buffer; zero means more memory is wasted. (EXPLAIN ANALYZE shows real row counts, but its instrumentation inflates wall time — don’t benchmark with it.)
  3. Sweep by doubling, session-scoped, median of several runs. Stop at the first size where Created_tmp_files hits zero.
  4. Size for the build side, not the table. The hash table holds only the columns the join needs from the smaller input. Ours fit between 1 MB and 2 MB despite 200,000-row tables.

Setting it safely

-- per session, for one heavy reporting job
SET SESSION join_buffer_size = 4*1024*1024;

-- per statement, leaving everything else alone
SELECT /*+ SET_VAR(join_buffer_size = 4M) */ ...

The default is 262144 (256 KB), which this server ran. Raising the global value is rarely right: the buffer is allocated per join per connection, so 64 MB global with 200 connections running two-table joins is a 25 GB exposure that only appears under load. Give the large buffer to the sessions that need it.

Test setup, sources and limits

The benchmark table, query plans, Created_tmp_files counts and server settings were produced on the machine above and reproduced verbatim; tune-table-join-buffer.sh rebuilds the dataset and re-runs the sweep so you can generate your own. The 8.0.20 removal and hash-join memory behaviour are quoted from the MySQL manual, and the script re-checks those sentences. This is one query shape on one machine with a 128 MB buffer pool — a worked example of the method, not a recommendation to set 2 MB on your server.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.