8 database trips down to 1: fixing the N+1 a join can't

An N+1 query problem is code that runs one query to fetch a list, then one more query for every item on it: ten items, eleven queries. The classic fix is a join, which asks the database to match each item to its data in a single query. But what if every item needs a different query? Our Goals panel did, so a site with eight Goals made eight trips to Postgres, our database, one after another. Each trip is a round trip: send the question, wait for the answer, only then send the next. A single UNION ALL, which stacks the results of several queries into one table, turned them into one trip, and the trick works anywhere the queries differ but their columns don't.

Eight queries, eight shapes

A Foresite Goal counts conversions, and comes in three kinds:

  • an event: name = 'signup'
  • an exact page: pathname = '/thank-you'
  • a page prefix: starts_with(pathname, '/blog/')

Some kinds can read daily rollups (per-day totals we work out ahead of time) and some need raw events (every single pageview and click), so each Goal's SQL comes out a different shape. The obvious code ran them one at a time:

for each goal in goals:
    sql = daily_sql_for(goal)       // this Goal's visitors, events and revenue per day
    totals[goal] = run("SELECT sum(visitors), sum(events), sum(revenue) FROM (" + sql + ") d")
    // ...and wait a whole round trip before starting the next one
Before · 8 queries After · 1 query AppPostgres AppPostgres 7 round trips sooner Goal 1: one query Goal 2: one query Goal 3: one query Goal 4: one query Goal 5: one query Goal 6: one query Goal 7: one query Goal 8: one query All 8 Goals in one query: the same work for Postgres
Postgres does the same work either way. What goes away is the travel in between.

One query, tagged

Every Goal's SQL returns the same columns. So we tag each one with its position, glue them together with UNION ALL, and GROUP BY the tag, which adds up each Goal's rows separately:

parts = []
args = []
for each goal, at position i:
    sql, goal_args = daily_sql_for(goal)
    parts.add("(SELECT " + i + " AS goal, visitors, events, revenue FROM (" + sql + ") d" + i + ")")
    args.add(goal_args)

rows = run("SELECT goal, sum(visitors), sum(events), sum(revenue)
            FROM (" + join(parts, " UNION ALL ") + ") g
            GROUP BY goal", args)

The details that matter:

  • The tag is a literal, not a parameter. A literal is a value typed straight into the SQL text. A parameter is a placeholder like $1 whose value travels separately, so the database can never mistake it for SQL (the mistake has a name: SQL injection). The tag is our own loop counter, never user input, so it's safe in the SQL text. Anything a user typed still goes through args.
  • Arguments are appended in the same order as the parts, so they line up with their placeholders. If you write $1, $2 by hand, renumber each part, so the second Goal's placeholders don't reuse the first Goal's numbers.
  • Every subquery needs its own alias. A subquery is a query tucked inside another one, and the alias is just a short name for its results (d0, d1...). Postgres insists.
  • A Goal with no rows produces no output row. So fill in every Goal at zero first, and let the rows overwrite them:
results = a zeroed result for every goal
for each (i, visitors, events, revenue) in rows:
    results[i] = (visitors, events, revenue)

When to use it, and when not to

Use it when each item needs a different query but they all return the same columns: configurable widgets, conversion goals, saved searches, alerts.

Use something simpler when you can:

  • Same query, different parameter: pass all the values as one array and match them in one go, with = ANY($1) and a GROUP BY, or unnest($1::bigint[]), which turns the array into rows.
  • Items that are rows in another table: a join. It was always going to be a join.

And mind the edges. Postgres allows at most 65,535 parameters (those $1 placeholders) in one statement, so split big batches into chunks. Run EXPLAIN ANALYZE, which runs the query and shows how Postgres actually went about it, to check each branch (each Goal's part of the query) still uses its index, a sorted lookup, like the one at the back of a book, that spares Postgres from reading every row. And one bad branch fails the whole statement, so check the items first.

The result

The Goals panel now costs one round trip however many Goals a site has. In fairness, our app and database share a data centre, so each saved trip was short, and this was the smallest win of the week. But its cost no longer grows with every Goal, and with a database in another region or behind a connection pooler (a middleman that shares a few database connections among many requests, and adds a hop of its own), each saved trip is worth much more.

It was one of four changes in We made our dashboard 35% faster without making any query faster.