The N+1 problem, as found on a Craft 2 site
On this page
The site is a large hospital system's main site, Craft 2, a few hundred pages, and every page is built from a modules field: a list of blocks the editors stack up, with forms, callouts, provider lists and so on nested inside. The editors asked for a utility page that answers one question: for every form on the site, which pages is it embedded on? Forms get retired and nobody wants to find the orphaned embed by clicking through the site.
The first version was the obvious Twig.
{% for entry in craft.entries.section('forms') %}
{% set relations = [] %}
{% set pages = craft.entries.section('pages') %}
{% for page in pages %}
{% for module in page.modules %}
{% if module.type.handle == "Form" and module.form.first().id == entry.id %}
{% set relations = relations | merge([page]) %}
{% endif %}
{% endfor %}
{% endfor %}
...
{% endfor %}
It worked on my machine with twenty test pages. On the real content it sat there long enough that I opened the debug toolbar instead of waiting.
Counting
Craft in dev mode puts the Yii debug toolbar at the bottom of the page, and its database panel lists every query the request ran. Scrolling it was the whole lesson. One SELECT for the pages. Then the same SELECT against the matrix block tables, over and over, identical except for the owner id. One per page. Then, because the whole thing sat inside a loop over the forms, one per page per form.
That shape has a name, and I had never heard it applied to my own code: N+1. One query to get the list, then N more queries, one for each item, to get the thing you actually wanted off it. The database is not slow. You are just asking it the same question a few hundred times when you could ask once.
The reason I had not noticed it earlier is that page.modules does not look like a query. It looks like a property. Craft loads the related blocks the first time you touch the field and hands them back, which is exactly the convenience that hides the cost. Add a {% cache %} tag around the block, which this template also had, and the second load is fast enough that you stop thinking about the first one.
Eager loading
Craft 2 has had an answer for a while: tell the query up front which relations you are going to use, and it fetches all of them in one extra query and attaches them to the right elements.
{% set pages = craft.entries({
section: 'pages',
with: [
'modules'
]
}) %}
That is the entire diff. Two queries instead of a few hundred, and the audit page loads like a normal page. I also pulled the pages query out of the forms loop, since it was fetching the same list once per form, but the with is what made the difference you could feel.
It goes one level further
Two months later I hit the same thing on the page templates themselves. The modules on this site are Neo blocks, nested two levels deep: a level-one block for the section, with child blocks inside it that pick the partial to render. The partial looped the level-one blocks and then called module.children on each one, and children is another query per block.
Neo has a way to short-circuit that. You hand each block the already-loaded list, and it answers children from memory instead of the database.
{% for module in entry.modules %}
{% do module.useMemoized(entry.modules) %}
{% endfor %}
{% for module in entry.modules if module.level == 1 %}
{% for item in module.children %}
{% include "_controllers/" ~ item.type with { module: item } %}
{% endfor %}
{% endfor %}
Same principle as with: load the set once, then walk it in memory.
It is not a Craft thing
Once I knew the name I went back through my Laravel work and found it everywhere. Post::all() and then $post->author->name in the Blade loop. One query for the posts, one per post for the author. The fix there is Post::with('author')->get(), and Eloquent will even accept nested relations, with('author.profile'). I had written the slow version on and off for six years and attributed the slowness to the server.
The rule I took away
Any time there is a loop over records and a relationship touched inside the loop, count the queries before shipping it. Dev mode and the toolbar make that a thirty-second check. Then eager-load exactly the relations the template uses. Not every relation, just those, because every with is another result set held in memory for the whole request, and I suspect that will be its own lesson one day.