I was watching Cristian Planas’s RailsConf talk, A Rails Performance Guidebook, where he flags greedy selects (pulling back more columns from the database than you’ll actually use) as an antipattern. It reminded me of an endpoint whose p99 was way too high because of a few very “heavy” columns (columns that contain large amounts of data, like JSON or TEXT), on a screen that never even showed them. In this post I’ll demonstrate why Cristian’s point stands.
All queries below run against a stripped-down calls table. Most of
it is narrow, but a call keeps its whole transcript:
CREATE TABLE calls (
id BIGINT PRIMARY KEY,
account_id BIGINT NOT NULL,
...
summary MEDIUMTEXT, -- 2 KB
notes MEDIUMTEXT, -- 1 KB
transcript JSON, -- ~290 KB
transcript_text MEDIUMTEXT, -- 36 KB
KEY index_calls_on_account_id (account_id)
);
Every call belongs to an account and the only secondary index is on
account_id. I measured on MySQL 8.4 running locally, with
the default 128 MB buffer pool. Production gives it far more memory,
but it also has far more data than one 5 GB table, so most of the
transcripts won’t be cached there either.
One account gets 15,000 calls, 7 in 8 of them completed. The list can be sorted
two ways: by id, which the index serves, or by started_at, which needs a
filesort. started_at is shuffled against id, so the two orders really return
different pages.
CREATE TABLE calls (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
account_id BIGINT NOT NULL,
title VARCHAR(255) NOT NULL,
status VARCHAR(32) NOT NULL,
started_at DATETIME NOT NULL,
deleted_at DATETIME,
summary MEDIUMTEXT,
notes MEDIUMTEXT,
transcript JSON,
transcript_text MEDIUMTEXT,
KEY index_calls_on_account_id (account_id)
) ENGINE=InnoDB;
DELIMITER $$
CREATE PROCEDURE seed()
BEGIN
DECLARE i INT DEFAULT 1;
START TRANSACTION;
WHILE i <= 15000 DO
INSERT INTO calls (account_id, title, status, started_at,
summary, notes, transcript, transcript_text)
VALUES (1, CONCAT('Call ', i),
IF(i % 8 = 0, 'scheduled', 'completed'),
'2024-01-01' + INTERVAL (i * 7919 % 15000) HOUR,
REPEAT('s', 2000), REPEAT('n', 1000),
JSON_OBJECT('text', REPEAT('x', 290000)),
REPEAT('m', 36000));
SET i = i + 1;
IF i % 1000 = 0 THEN COMMIT; START TRANSACTION; END IF;
END WHILE;
COMMIT;
END$$
DELIMITER ;
CALL seed();
ANALYZE TABLE calls;
The sparse variant later on is the same seed with
IF(i <= 2, 'completed', 'scheduled'), so only the two calls with the lowest ids are
completed.
If you’ve ever used an API that follows the JSON:API spec, you’re already aware
of the “sparse fieldset” feature: a client asks for something like
fields[calls]=title,started_at and only gets those attributes back. On an
endpoint like the one from the intro, that’s the obvious way to avoid
serializing the heavy columns.
The problem comes when the fieldset only filters the response from the API to
the client. If it doesn’t affect the database query, the query will still run
SELECT *, MySQL will read the transcripts, and Rails will load them into memory.
InnoDB stores a table as a B-tree ordered by the primary key (the clustered index), with the full rows sitting in its leaf pages. A secondary index points to rows by id, so to read a row found through it, InnoDB looks the id up in the clustered index.
A page is 16 KB, and a row has to fit in roughly half of one. When it doesn’t,
ROW_FORMAT=DYNAMIC moves the longest values out to overflow pages and leaves a
20-byte pointer in the row. So the heavy call columns, transcript and
transcript_text, live off-page. I’ll call these values blobs from here on.
Every blob is extra pages on top of the row’s, about 18 for one transcript,
and each of them comes from disk when it isn’t in the buffer pool (which on an
SSD is roughly a thousand times slower than memory). Reading a lot of blobs also
pollutes the buffer pool by pushing out the row pages other queries need.
Now let’s take a look at two queries that list calls and how MySQL executes them, especially how it handles the blobs.
The default order is newest first (id DESC):
SELECT * FROM calls
WHERE account_id = ? AND deleted_at IS NULL AND status = 'completed'
ORDER BY id DESC
LIMIT 30
InnoDB appends the primary key to every secondary index, so
index_calls_on_account_id is physically (account_id, id). The entries come
out already ordered by id and MySQL walks them backwards without a filesort. But
status and deleted_at aren’t in the index, so for every entry it has to fetch
the row from the clustered index to check them.
Each call goes through the whole chain before the next one starts:
status and deleted_atSeven in eight calls are completed, so the first page stops after 35 rows:
-> Limit: 30 row(s)
(actual time=0.236..3.57 rows=30)
-> Filter: (status = 'completed' and deleted_at is null)
(actual time=0.235..3.56 rows=30)
-> Index lookup on calls using index_calls_on_account_id
(account_id=1) (reverse)
(actual time=0.159..3.49 rows=35)
SELECT * takes about 4 ms. The blobs are read, but only for 35 rows.
This was the happy path, though. The execution time depends on the distribution of the rows. In a copy of the table where only the two calls with the lowest ids are completed, the same query walks all 15,000 calls to find them and takes 19 s instead of 4 ms. That is what made this case confusing for me at first: the same query was fast for some tenants and slow for others.
Now let’s sort the same list by started_at. It isn’t in any index, so MySQL
has to visit every candidate, sort them, and only then take the first 30:
deleted_at and status: 13,125 rows(id, started_at) pairs and sort them by started_atThe plan for SELECT *:
-> Limit: 30 row(s)
(actual time=17141..17178 rows=30)
-> Sort row IDs: calls.started_at DESC, limit input to 30 row(s) per chunk
(actual time=17141..17178 rows=30)
-> Filter: (status = 'completed' and deleted_at is null)
(actual time=7.81..17129 rows=13125)
-> Index lookup on calls using index_calls_on_account_id
(account_id=1)
(actual time=7.8..17111 rows=15000)
MySQL is smart enough not to carry whole rows through the sort, only the
(id, started_at) pairs. That doesn’t save the query, though. Almost all of the
17 seconds go to the index lookup, where InnoDB reads the blobs of all 15,000
candidates, just for the query to return 30 of them.
This looked like a bug to me, since the sort only needs the WHERE and ORDER BY columns. The 30 winners are read again afterwards anyway, so there’s no reason to read every blob before it. It turns out I wasn’t the first to notice; #110998 traces it to a regression in MySQL 8.0.20 and #115555 is verified on 8.0 and 8.4.
Above I said the sort has no reason to read every blob, that MySQL could be
smarter about which columns it reads. That set of columns is called the read_set.
Before execution, the server builds the list of columns InnoDB reads for every
row it visits. The read_set includes not just the SELECT list, but also
whatever is needed for filtering and sorting. For example, let’s take a look at
the following query:
SELECT id, title, started_at FROM calls
WHERE account_id = ? AND deleted_at IS NULL AND status = 'completed'
ORDER BY started_at DESC
LIMIT 30
It returns three columns but reads six, id, title and started_at from the
SELECT, plus account_id, deleted_at and status from the WHERE. All six sit on
the row page, and the query takes 31 ms. Make it SELECT * and the read_set
also picks up transcript, transcript_text, summary and notes,
roughly 330 KB for every row InnoDB visits.
The read_set also explained something I noticed in production. The pagination
runs a COUNT(*) with the same WHERE before the main query and
it was much faster than the list itself, even though both walk the same rows.
Here it takes 24 ms against the 17 s of the SELECT *, because its read_set
holds only the three WHERE columns, all on the row page.
The blobs hurt because MySQL reads them for rows it then throws away. If an index answers the whole WHERE and hands the entries over already in the requested order, there’s nothing to throw away.
For the first query, that’s an index on the WHERE columns:
KEY (account_id, status, deleted_at)
To the index, IS NULL is just another equality, so after three equalities
the entries come out already in id order. On the copy where only two calls
are completed, the query now reads those two rows instead of 15,000 and takes
0.07 ms instead of 19 s.
For the second query, the sort column goes at the end:
KEY (account_id, status, deleted_at, started_at)
After the same three equalities, the entries come out in started_at order.
There’s no sort and MySQL reads 30 rows. Even a SELECT * then pays only for the
blobs of the rows it returns and runs in a mere 1.9 ms instead of 17 s.
The problem is that an index serves one query shape. These two queries already need two different indexes. Every other filter or sort on the list would need one of its own. The queries here are also a simplification: a real list usually carries more conditions (permissions for example) that no index can fully answer, so the blobs get read for discarded rows again.
And even when the query itself takes a couple of milliseconds, the rows it
returns still have to get to the application. With SELECT *, the 30 calls are
about 10 MB that MySQL sends over the network and Rails then parses into
memory.
When no index serves the query, we can still keep the blobs out of the part that visits every row. We split the work in two: a narrow query finds the ids of the page, and only then are the full rows read (for those same ids).
SELECT calls.* FROM calls
JOIN (
SELECT id FROM calls
WHERE account_id = ? AND deleted_at IS NULL AND status = 'completed'
ORDER BY started_at DESC
LIMIT 30
) page USING (id)
ORDER BY calls.started_at DESC
This is called a deferred join. The inner query visits the same 15,000
rows and sorts them, but with the narrow read_set. The outer one reads
the blobs of only the 30 rows that made the page. The result is the
same as the SELECT *, and it takes 31 ms instead of 17 s.
The problem for me here was the fact that it wasn’t easy to implement on the application layer. The inner query still has to carry every filter, permission check and sort from the request.
But why complicate things? If the list doesn’t show the blobs, we can just… not
select them. With .select, the heavy columns never enter the read_set. All
we need is for the SELECT to follow the sparse fieldset:
# Every attribute that reads a heavy column names the columns it reads.
# An attribute can read a column under a different name, or several of them.
HEAVY_COLUMNS = {
transcript: %w[transcript],
transcript_text: %w[transcript_text],
highlights: %w[transcript transcript_text],
}.freeze
def selected_columns(fields)
# No fields[calls] in the request, nothing changes.
return Call.column_names if fields.nil?
# A heavy column stays as long as any requested attribute reads it,
# the rest drop out of the SELECT.
heavy = HEAVY_COLUMNS.values.flatten
needed = HEAVY_COLUMNS.values_at(*fields).compact.flatten
Call.column_names - (heavy - needed)
end
fields = params.dig(:fields, :calls)&.split(",")&.map(&:to_sym)
Call.where(...).select(selected_columns(fields))
The plan doesn’t change and neither does the number of rows visited. Each visit just gets as cheap as in the narrow query. Sorted by start time, that’s 17 s against 31 ms.
The catch is that every call it loads is now a partial model. If a callback, a
cache key or a serializer helper reads one of the dropped columns, Rails raises
ActiveModel::MissingAttributeError. On top of that,
HEAVY_COLUMNS has to be kept in sync with the serializer by hand.
And .select only fixes the query it’s on. Calls get loaded in other places
too: a preload through includes(:calls) on another model, a find, a
background job, or an update, which loads the whole record before it writes a
single column. Each of those still runs SELECT * and still reads the blobs,
unless someone remembers to add a select there as well.
The durable fix is to move the heavy columns out of the table, either into something like S3 or into their own table, one row for each call:
CREATE TABLE calls (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
account_id BIGINT NOT NULL,
title VARCHAR(255) NOT NULL,
status VARCHAR(32) NOT NULL,
started_at DATETIME NOT NULL,
deleted_at DATETIME,
KEY index_calls_on_account_id (account_id)
);
CREATE TABLE call_contents (
call_id BIGINT PRIMARY KEY,
summary MEDIUMTEXT,
notes MEDIUMTEXT,
transcript JSON,
transcript_text MEDIUMTEXT,
FOREIGN KEY (call_id) REFERENCES calls (id)
);
This is the option I like best. Nobody filters or sorts by a transcript, so a
list never needs the join. On the seed, the same SELECT * sorted by start time
goes from 17 s to 11 ms. That’s even faster than the narrow query on the
original table (31 ms), because the 2 KB summary moved off the row page too.
Once the blobs aren’t in the calls table, nothing that loads calls can read them by accident, whether it’s the list, a preload or a background job. There’s no column list to maintain, no partial model and no index to match to the query.
The cost is a data migration on a big table, and a join or a second query wherever the content is needed.
If a migration is what holds you back, Rails can get you most of the way there without
it. ignored_columns keeps the heavy columns out of every query Call makes
and a second model on the same table reads them when they’re needed:
class Call < ApplicationRecord
self.ignored_columns += %w[summary notes transcript transcript_text]
has_one :content, class_name: "CallContent", foreign_key: :id
end
class CallContent < ApplicationRecord
self.table_name = "calls"
end
A list, a preload or an update no longer selects the blobs. Code that needs
them asks for call.content explicitly. There’s still a catch, though.
With the default binlog_row_image=FULL, every UPDATE on a call
writes the whole row to the binlog, before and after (blobs included). A status
change or a bumped updated_at is about 660 KB of binlog every time and every
replica has to replay it. A backfill of a new column multiplies that by every row
in the table.
Here are all the numbers side by side:
| query | rows visited | time |
|---|---|---|
newest first, SELECT * |
35 | 4 ms |
newest first, two completed calls, SELECT * |
15,000 | 19 s |
newest first, two completed calls, SELECT * with the WHERE index |
2 | 0.07 ms |
by start time, SELECT * |
15,000 | 17 s |
| by start time, narrow | 15,000 | 31 ms |
by start time, SELECT * as a deferred join |
15,000 | 31 ms |
by start time, SELECT * with the new index |
30 | 1.9 ms |
by start time, SELECT * on the split table |
15,000 | 11 ms |
Although it wasn’t the main point of this post, I think another really important lesson here is the difference between rows read and rows returned. The list returned 30 rows and read up to 15,000, each with every selected column, heavy ones included. A sparse fieldset doesn’t necessarily change that because, on its own, it only trims the response.
So when a list endpoint is slow and its plan looks fine, run a COUNT(*) with
the same WHERE. If the count is fast and the SELECT * isn’t, the time goes to
columns nobody asked for, usually a TEXT, BLOB or JSON. Selecting fewer
columns or adding the right index fixes that one query, but moving the heavy
columns into their own table should fix it for every query on the table.