Back

350,000 Rows in One Fast Table

By Pablo Fernandez7 min read

The catalogue in LabSys, the internal app I build for a pharma company, has about 350,000 articles, and people use it like a spreadsheet. They scroll it, sort it by any column, tick rows, edit cells, and open a column's filter to see every value in it with how many rows have each. Making 350,000 rows scroll smoothly is a solved problem, and I'll get it out of the way first. It was never what made the table slow.

What made it slow was everything around the rows. The total in the header, the counts next to each filter value, the list of distinct values in each of 40 columns: every one of those is an aggregate over the whole catalogue, and in production, cold, the filter options took 4 s, the facets 2.8 s and the tag counts 1.2 s. The first open of the catalogue took 7.7 s.

The usual answer is a cache with a timer, and LabSys had one: counts kept for 5 minutes. That gives you two bad choices at once. For up to five minutes after someone edits a price, the price filter shows the old prices. And every five minutes, whether anything changed or not, the seconds of work run again. The question this post answers is the one hiding under that timer: how does a cache know, exactly, when what it holds has stopped being true?

Only the rows you can see

First, the easy part. LabSys's table is a real <table> in its own scroll box, with the header held at the top. Only the rows in view are in the page, plus six either side, and two spacer rows stand in for everything above and below. Scroll this one to the bottom: the number of rows in the page never changes.

Ref.RoasterOriginProcess€/kg
CF-000001Tueste NorteBrazilNatural20.55
CF-000002VelaPeruHoney44.35
CF-000003Sur TostadoresColombiaNatural46.90
CF-000004Cerro AltoGuatemalaNatural70.70
CF-000005Sur TostadoresRwandaHoney94.50
CF-000006AlborKenyaNatural18.05
CF-000007Casa MolinaPanamaNatural41.85
CF-000008VelaEthiopiaWashed44.40
CF-000009Tueste NorteBrazilNatural68.20
CF-000010VelaPeruNatural92.00
CF-000011Sur TostadoresColombiaWashed94.55
CF-000012Cerro AltoGuatemalaNatural39.35
CF-000013Sur TostadoresRwandaNatural63.14
CF-000014AlborKenyaWashed65.70
CF-000015Casa MolinaPanamaNatural89.50
CF-000016VelaColombiaWashed92.05
CF-000017Tueste NorteGuatemalaWashed36.85
Rows: 350,000In the page: 17Showing 1 to 17
350,000 made-up rows in one scroll box. Scroll as far as you like: only the rows in view, and six either side, are ever in the page.

The demo keeps every row the same height to stay short. LabSys uses react-window's virtualizer with measured heights instead, because its cells never cut text: a long name wraps and the row grows. That has a consequence that took me a while to see. Column widths can't come from the content (table-fixed), because with virtualized rows the content changes as you scroll, the widths would change with it, and with them every row's height.

The rows themselves come from the server a page of 300 at a time, by cursor. As the end of what's loaded comes within 150 rows, the next page is asked for, and up to three pages are read ahead, one after another. A response that arrives after the filters changed is dropped. None of this is unusual, and none of it touches the numbers in the header.

The numbers nobody scrolls past

A column filter in LabSys is a menu with every value of that column and a count next to each, counted within the other filters already on. The smart search I wrote about in Search a Table in Plain Words reads those same lists to know what values exist. So they are asked for constantly, and each one is a GROUP BY over 350,000 rows.

Nothing about them changes when someone scrolls, sorts or opens a menu. They change when the data does. The fix is to stop asking a clock whether they're stale and ask the data itself.

Postgres says when data changed

Every data table in LabSys has a statement-level trigger. Any INSERT, UPDATE, DELETE or TRUNCATE, from any writer (the app, an import script, the bridge to the company's management software, me in psql), bumps that table's row in a small table_data_versions table and sends a NOTIFY. core-api holds a LISTEN on that channel and reads the versions again when told, and once a minute anyway in case a notice was lost on a dropped connection.

app, imports, bridge, psql │ INSERT / UPDATE / DELETE ▼┌──────────────────────┐ statement trigger│ catalog_articles │──────────────────────▶ table_data_versions└──────────────────────┘ source version articles 412 articles.price 37 ┌─────────────────────────────────────┘ │ NOTIFY table_data ▼┌──────────────────────┐ key = what it reads, at their versions│ core-api │──────────────────────▶ Redis└──────────────────────┘
Writers never talk to the cache. Postgres records that something changed, and core-api keys what it keeps by those versions.

Everything computed from the data goes through one small function. It builds a version key from the tables and columns the computation reads, and keeps the result in Redis under that key. If the stored version matches, it's served. If not, it's computed again:

versioned-cache.service.ts
const cached = <T>(id: string, compute: () => Promise<T>, reads?: string): Promise<T> => {
  const columns = reads === undefined ? null : tableDataVersions.reads(reads, sources);
  const version = tableDataVersions.ofReads(sources[0]!, sources, columns);
  const hit = memory.get(id);
  if (hit && hit.version === version) return hit.value as Promise<T>;
  const value = (async () => {
    const kept = await versionedCacheRepository.get<T>(`${namespace}|${id}`).catch(() => null);
    if (kept && kept.version === version) return kept.value;
    const fresh = await compute();
    void versionedCacheRepository.set(`${namespace}|${id}`, version, fresh).catch(() => undefined);
    return fresh;
  })();
  memory.set(id, { version, value }); // the same list asked twice at once is computed once
  return value;
};

There is no expiry anywhere. A count computed on Monday is served on Friday if nothing it reads changed, and it's correct, because "nothing it reads changed" is something Postgres knows rather than something a timer guesses. And since the versions live in the database and the values in Redis, a restart doesn't lose anything: after a deploy, every table's lists are ready in 0.1 to 0.2 s, where they used to take about a minute to compute again.

Per column, not per table

That first version bumped a whole table on any change, and it was already a big improvement. But the catalogue is edited all day, one cell at a time, and editing one price made all 40 columns' lists, the total, the facets and the tag counts wrong at once, so they were all computed again. Most of that work was for columns nobody had touched.

So the UPDATE trigger now works out which columns changed. A statement-level trigger in Postgres can see every row the statement touched, before and after, as two transition tables, and the trigger compares them column by column in one pass, joined by id:

0055_table_column_versions.sql
SELECT string_agg(format(
         'case when bool_or(o.%1$I is distinct from n.%1$I) then %1$L end', a.attname), ', ')
  INTO checks
  FROM pg_attribute a  -- (types without equality, like json, are compared as text: left out here)
 WHERE a.attrelid = TG_RELID AND a.attnum > 0 AND NOT a.attisdropped AND a.attname <> 'id';
 
EXECUTE format('SELECT array_remove(array[%s], NULL) FROM old_rows o JOIN new_rows n ON n.id = o.id', checks)
  INTO changed;

Each changed column gets its own version (catalog_articles.price). Rows added or removed still bump the table's own version, because every count over the table moves with them. A kept list's key is then made of exactly what it reads: the table's own version, plus the version of each column it names. A price edit moves the price filter's list and nothing else.

table_data_versions

  • articles1
  • articles.price1
  • articles.supplier_id1
  • articles.origin1
  • articles.hidden_at1
  • suppliers1
  • suppliers.name1

Kept in Redis

  • Total of the catalogueKept
  • Price filter's valuesKept
  • Supplier filter's valuesKept
  • Origin countsKept
  • Shown on the web, countKept
Every list is current: each was stored under the versions it read.
Run a change and see which kept lists Postgres's versions send back to be computed again. The rest are served from Redis as they were.

Two details in that trigger came from measuring it. Comparing 15,000 updated rows takes 1.2 s, but only after one setting: transition tables have no statistics, Postgres picked a nested loop to join them, and the same comparison took 13 s. The function now runs with enable_nestloop = off, which leaves it a hash join. And an UPDATE over more than 20,000 rows doesn't compare at all. It bumps the whole table, because at that size the comparison costs more than computing everything again.

How does core-api know which columns a list reads? From its SQL. It takes the words in the query's text and keeps the ones that are column names of the tables involved. That errs on one side only: a word that happens to be another table's column makes it read more than it does, never less. Anything it can't see through, a view, a select *, a whole row as JSON, counts as reading everything.

Computed before anyone asks

Knowing that a list is stale is half of it. Someone still has to wait while it's computed again, unless it's done first. When a table's versions move, core-api waits until its data has been still for 15 s, then computes its lists again: every column's values, and the filter sets each table was last opened with. It does this at most every 2 minutes per table, so an import writing for an hour doesn't keep it busy for an hour. At boot it goes through every table, one after another.

The person who edited the price never notices any of this. The next person to open the price filter gets a list that was computed while nobody was looking, keyed by versions that say it's current.

Where the time actually went

With the aggregates out of the way, the queries left were the ones that really run per request, and two were worth fixing. A text search written as one condition, a full-text match or a reference ilike, made Postgres score every row of the catalogue. Written as a union of the ids each index finds on its own, a sorted search went from 6 s to 0.4 s and its counts from 20 s to 0.15 s. And a sorted page now sorts only the ids and sort keys, then reads the full rows for those 300: by price, 3 s became 0.9 s.

What the table costs now

The trade is a trigger on every write to every data table. For a one-cell edit it's nothing. For an update of 15,000 rows it adds 1.2 s, once, inside the statement. In return, nothing around the table is ever computed on a timer, nothing stale is ever served, and the lists people open most are usually ready before they ask. The rows were never the problem. The numbers next to them needed someone to tell them when they had stopped being true, and Postgres already knew.

Related articles

Search a Table in Plain Words

Type a sentence into a table's search box and get its filters back as chips, the first in a third of a second, from a model that only picks real values.

AI for Every Mail Provider

A design for bringing Mailingest's spam filter, categories and AI cards to Gmail and Microsoft 365, with no need to move the mail. Two doors, one rule.

Gmail-Style Tabs for Any Inbox

Mailingest sorts mail into Gmail's five tabs on the server, so Promotions and Updates show up as folders in any mail client. I started with eleven.