Yash Gupta

A 17x faster contacts API from six indexes

The contacts list was slow for large customers. A request made four queries, and together they took about 515 milliseconds. After six indexes it takes about 30.

Result
515ms to 30ms, 17x
Measured on
528,000-row production copy
Stack
PostgreSQL, Drizzle ORM
Status
Live in production

What I found

I ran EXPLAIN ANALYZE on each of the four queries for the largest customer. Three separate problems showed up.

1. Two join tables had no index except their primary key

The tag and group membership tables, 335,843 and 139,989 rows, were looked up by contact ID on every request. With nothing indexed on that column, Postgres scanned both tables in full each time. Deletes cascading from contacts had the same problem finding their rows.

2. The list query's indexes had the wrong second column

The list filters by company and a deleted flag, then sorts by creation time and takes 100 rows. None of the existing composite indexes matched that shape, so Postgres gathered 94,075 index entries for the largest customer and sorted them all to return 100.

3. The ORM's default made an index useless for sorting

In Postgres, a plain ORDER BY created DESC puts nulls first. The ORM's .desc() renders an index as DESC NULLS LAST. Because those orders differ, the planner cannot use that index to return rows in order, and falls back to sorting. Nothing warns you.

What I changed

  • Indexed the contact ID column on both join tables.
  • Built the list index with the equality columns first and the sort column last, so Postgres walks the index and stops after 100 rows.
  • Declared the sort column NULLS FIRST to match what the query actually asks for.
  • Kept the deleted flag in the index key rather than as a partial-index condition, because the trash view queries for deleted rows too.

How I verified it

Before and after on a full 528,000-row copy of production, for the largest customer, per request:

QueryBeforeAfterWhat changed
List page69.3 ms0.38 msordered index scan, stops at the limit
Count38.6 ms16.3 msindex-only scan, 2,743 buffers down to 89
Tag lookup269.0 ms9.5 msfull scan to index scan
Group lookup138.0 ms4.1 msfull scan to index scan
Total~515 ms~30 ms

All six indexes applied in about 1.7 seconds of write-blocking DDL, and the planner picked them up without a manual ANALYZE.

What I took from it

  • Foreign keys on join tables are the most commonly missed index in any schema.
  • Composite index column order is not cosmetic: equality columns first, the sort column last.
  • Read the SQL your ORM generates for an index, not just for a query.