Lab / 02 · Databases
Three experiments on things I’ve fixed in production: a missing index, the N+1 problem, and a race condition that pays out money twice. Run each one and read the database’s side of the story.
Numbers here are illustrative, from a 1M-row test table. On the live site they come from real EXPLAIN ANALYZE runs against Postgres.
Every index speeds up reads and slows down writes. I index for the queries that actually run hot, not every column.
(user_id, created_at) serves “a user’s recent orders”. (created_at, user_id) mostly doesn’t. Equality first, then range.
Row locks are simple when conflicts are common, like a hot wallet. A version column scales better when they’re rare.