Video in progress

How do you catch a slow or dangerous query in a new release before it reaches prod?

I set several nets: tests in CI on a real PostgreSQL with data volume close to prod, assertions on the number of queries per endpoint, checking the EXPLAIN plan of the important queries, a migration linter, and a pg_stat_statements comparison on a canary deploy.

📖 Answer

If the local and CI database has 100 rows, any query is fast. The problem shows up on prod's 50 million rows. So the main job is to bring the test environment closer to prod.

My nets:

  1. A real database. Testcontainers with the same major version as prod. H2 has a different planner and a different SQL dialect.

  2. The number of queries. In an integration test, the endpoint is called and the SQL count is checked:

@Test
void dashboardDoesNotExplodeIntoNPlusOne() {
    queryCounter.reset();
    client.get().uri("/dashboard").exchange().expectStatus().isOk();
    assertThat(queryCounter.selectCount()).isLessThanOrEqualTo(8);
}
  1. Plan checks. For critical queries, EXPLAIN is taken on the staging database with prod statistics, and if there's an unexpected Seq Scan on a big table, the test fails. It's brittle, so only for the 10-20 most important queries.

  2. Volume. On staging, an anonymized copy of prod or generated big data. A load test (Gatling, k6) on the main scenarios.

  3. Migrations. A linter (lock risk, an index without CONCURRENTLY), and measuring the time on a prod-sized copy.

  4. Canary. The new version gets 5% of traffic. Queries that are new or whose mean_exec_time jumped sharply in pg_stat_statements raise an alert, and the deploy stops automatically.

No net catches 100%. The goal is to see the problem quickly on a small share of users and roll back fast.