Understanding Rails

Understanding Rails · On the job · Ticket 002

Eagle Ridge's page is slow

Episode 102 · deep dive · about 11 minutes · Rails 8.1 · by

How was this episode?

The series' author reads every note, and no one else sees it. When something is wrong or unclear, it gets fixed and the episode re-cut. How this series stays right.

Was it clear?

Not endorsed yet. Are you a Rails developer? What's an endorsement?

Endorse this version To endorse: create an account, confirm your email, then link GitHub.

A senior works ticket 002 out loud: refine past the bigger-server guess, find the N+1 query in the log, count queries in a test, fix it in the view, and CI's review.

Free to watch. If it helped, support the series.

Transcript

0:00 Eagle Ridge's page is slow

On the job. Ticket two: Eagle Ridge's page is slow. Last time, notes vanished. This time, nothing is broken. Every page works. One is just slow. A slow page tempts you to guess more than almost any other ticket. So again, the work starts at the ticket, not in the code.

0:22 The ticket

Here it is. Morgan, the product manager, writes: Eagle Ridge Loop's page has gotten really slow. It's been like this since the newsletter featured it last month, and everybody started posting there. Are we outgrowing the server? Should we pay for a bigger one? Below it, a hiker, Ravi: it takes forever to open now, especially on my phone before I head out. Sometimes I give up and just go. The other trails open right away.

0:47 Shovel ready

Is it shovel ready? Not yet. We know who and where. But slow isn't something a test can check. Nobody has reproduced it. And a fix is already on the table: a bigger server. That's a guess about the cause, and it's a guess that costs money.

So read it slowly. Since the newsletter: it started at a known time. Everybody started posting there: Eagle Ridge has more notes than it used to. The other trails open right away: only one page is slow. And are we outgrowing the server? That's Morgan's guess. Keep the facts, and hold the guess loosely.

1:23 Questions for the reporter

Now, questions for Morgan. A good question splits the causes in two. Are other trails slow too? No. Cedar Falls and Granite Switchbacks open right away. Same app, same server, same code, and only one page is slow. So the cause is something about Eagle Ridge itself.

What does Eagle Ridge have that the others don't? How many notes does it have? Hundreds now. Cedar Falls has two. When did it start? About a month ago, and it gets a little worse every week. When a page gets slower as a list grows, look for work it does once for each thing in the list.

1:59 Testing the bigger server

Now test Morgan's guess. Is it slow only when the site is busy? I thought so, but no. At six on a Sunday morning, it was just as slow. Slow when nobody else is on rules out traffic. A bigger server won't fix a page that does too much work on its own.

I asked other questions too. Which device? Signed in or out? Do notes have photos? Did live notes start it? Morgan answered each one honestly, and none of them narrows it down. That's normal. Not every fair question pays off.

2:33 A hypothesis

So, a hypothesis. Only a hypothesis, until we see it. The trail page does some work once for each note. Open the page. It renders the trail's notes, and each note's partial shows note dot author dot name. A note keeps its author's id, not their name. So where does the name come from?

2:53 Reproduce it

Reproduce it. The seeds give Eagle Ridge four hundred and two notes, from seventy seven hikers. Cedar Falls has two. Start the server, and open Eagle Ridge, signed out, the way Ravi does. The page works. The log tells us what it did.

3:09 The log

Here's the request. The trail loads. The notes load, in one query. Then: user load. User load. User load. Each one points at the note partial. One query for every note on the page.

Now the bottom line. Completed two hundred OK, in a hundred and sixty four milliseconds. Four hundred and four queries, three hundred and twenty five of them cached. The cache answers an author it has already loaded. Seventy nine still reach the database: the trail, the notes, and one for each hiker.

3:43 An N+1 query

Now Cedar Falls, with two notes. Four queries, five milliseconds. Same code, same server. The difference is the number of notes. This has a name: an N plus one query. One query for the notes, then one more for each note.

3:58 Acceptance criteria and scope

Now we can write the ticket properly. A title that says what's wrong: a trail's page loads each note's author on its own. Then acceptance criteria. One: a trail's page makes the same number of queries with thirty notes as with three. Two: every note still shows its author's name and its words. Three: notes are still listed newest first. Four: posting a note still works, and followers still get their email.

Notice criterion one counts queries, not seconds. Time depends on the machine, and on what else it's doing. The number of queries doesn't. A test can check a count the same way every time.

Then what's out of scope. Showing fewer notes at a time, with pages or a show more button. How many to show is Morgan's call, and a good next ticket. Caching the page. And a bigger server. The page is slow when the site is quiet, so a bigger server wouldn't fix it.

Check it against shovel ready. We know who, where, what they expected, and what happened. It reproduces every time. The criteria can be tested, and the scope is said. It fits in one pull request. Nothing blocks starting. Now, code.

5:12 A failing test

First, a test that fails because of the bug. A new trails controller test. Make a trail with five notes, each from a different hiker, so the query cache can't hide a thing. Then assert queries count, three, around getting the page: the trail, its notes, and their authors.

Run it. One failure, and it's the right one. Seven instead of three queries were executed. And it lists them: the trail, the notes, and five user selects, one for each note. The test can see the bug.

5:44 The fix

Now the fix. Where should the authors load? My first thought is the controller. In show, set at notes to the trail's notes, includes author. In the view, render at notes. Run the test. It passes.

5:58 The trap

Before I trust it, one question. What else draws this page? Search the app for trails slash show. On master, nothing. But ticket one's fix renders this page from the notes controller, when a note is too long. If you did ticket one, that fix is in your fork. So put it in, and run every test.

One error. Ticket one's test, the note over five hundred characters. Action view template error: nil is not an Active Model compatible object. The notes controller draws the trail page, but it never set at notes. So render gets nil.

6:34 The fix, again

So load the authors where the page needs them: in the view. Render the trail's notes, includes author. That works whichever controller draws the page. Run every test, with ticket one's fix in: eighteen runs, no errors. Then take ticket one's fix back out. The new test passes on its own.

Open Eagle Ridge again, and read the log. Three queries: the trail, the notes, and one user load, with every author's id in a single list. Completed in thirty six milliseconds, down from about a hundred and sixty. That's my laptop, so quote the count. The count is the same on any machine.

7:13 bin/ci and the commit

Before pushing, run what C I runs, on my own machine. Bin C I: the style check, the security audits, Brakeman, the tests, and the seeds. All of them pass.

Then a commit message that says why. Eagle Ridge drew about four hundred notes, and each loaded its author on its own: four hundred and four queries. Now three, however many notes there are. And a second paragraph on where: in the view, because ticket one's fix draws this page too.

7:43 The pull request

Push the branch, named for the ticket, and open a pull request. I pushed the test first, on its own. C I's review: three of four pass. The cross says three notes took five queries, and thirty took thirty two. And the test check is red.

8:00 CI's review

Then push the fix. The same comment updates. Every acceptance criterion passes, and the checks go green. Read those lines again. They're our acceptance criteria, word for word.

8:13 Answering the reviewer

Passing isn't the same as approved. So the comment adds what a reviewer would still ask. Answer each one, the way you would on a real pull request.

Where is your test? In the trails controller test. It failed before the fix, with seven queries instead of three. If someone drops the includes, it fails again.

Where do the authors get loaded, and why there? In the view. Loading them in the trails controller broke ticket one's page, because the notes controller draws it too.

Includes, preload, or eager load? Read the SQL each one makes. Includes and preload make two queries: the notes, then the users whose id is in a list. Eager load makes one, with a left outer join. Includes lets Rails choose, and here it chose two queries, like preload.

What did the completed line say, before and after? Four hundred and four queries before. Three after. Put the numbers in the pull request, so the reviewer doesn't have to run it.

Did you think about strict loading? It turns a lazy load into an error. Ask for the page's notes with strict loading, and no includes, and the test errors: the association named author cannot be lazily loaded. That's the N plus one, caught.

But turn it on for every note, and two other tests break. One is the job that emails followers. It loads a note on its own, then reads its trail. So turn it on only where the page loads its notes. That's a change of its own, and I left it out of this one.

Anything you noticed but left alone? Yes. Four hundred notes on one page is still a lot to draw. Showing fewer at a time is a good next ticket, and Morgan's call. Write it down, and leave it.

10:02 Closing the loop

Last, close the loop with Morgan. We don't need a bigger server. The page loaded each note's author on its own, so it got slower as the notes piled up. Now it loads them together. And one question back: how many notes should a trail show at once?

10:18 The rules

So: a slow page is a ticket like any other. Ask what the slow page has that the fast ones don't. Ask if it's slow when the site is quiet. Read the log, and count the queries. Load data where every caller of the page gets it. Then a failing test, the fix, and a review you can answer.

10:37 Your turn

Now it's your turn. Ticket two has its own page, where you ask Morgan your own questions before you see ours. Sync your fork, seed it, and open Eagle Ridge. Make a branch named for the ticket, and open a pull request in your fork. C I reviews it.

Check your understanding

  1. The log's Completed line says 404 queries, 325 cached. What does cached mean there?

    • Those 325 were answered from the same request's query cache, without asking the database again
    • Those 325 were stored for the next request
    • The browser cached those 325 notes
    Show answer

    Those 325 were answered from the same request's query cache, without asking the database again. Active Record's query cache keeps each query's result for the rest of the request. The same query again, here an author already loaded, is answered from it instead of the database. Source: Caching with Rails: SQL Caching (Rails Guides 8.1).

  2. A test counts the queries a trail's page makes with assert_queries_count. Why does it give each note a different author?

    • Because a note can't share an author
    • Because the counter skips cached queries, so notes by one author would hide the repeated loads
    • Because fixtures can't make notes
    Show answer

    Because the counter skips cached queries, so notes by one author would hide the repeated loads. The counter behind assert_queries_count returns early for a cached query. With one author, every load after the first would be cached and the N+1 would go uncounted. Source: QueryAssertions' counter skips cached queries (Rails source, v8.1.4.1).

  3. TrailsController#show sets @notes. NotesController#create renders "trails/show" when a note is too long. What is @notes there?

    • The same notes, because the template belongs to TrailsController
    • nil, because render draws the template without running any action's code
    • An empty list
    Show answer

    nil, because render draws the template without running any action's code. render only draws a template. It runs no code in the action the template is named after, so nothing set @notes. Source: Layouts and Rendering: The Difference Between render and redirect_to (Rails Guides 8.1).

  4. Which loads a trail's notes and their authors in one query, with a LEFT OUTER JOIN?

    • preload(:author)
    • eager_load(:author)
    • includes(:author), always
    Show answer

    eager_load(:author). eager_load loads the association with a LEFT OUTER JOIN in a single query. preload makes a separate query for each association. Source: Active Record Query Interface: eager_load (Rails Guides 8.1).

Sources

Every example in this episode was run on Rails 8.1.4.1 and Ruby 4.0.10.

Comments

Sign in to comment or sign up.