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:
-
A real database. Testcontainers with the same major version as prod. H2 has a different planner and a different SQL dialect.
-
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);
}
-
Plan checks. For critical queries,
EXPLAINis taken on the staging database with prod statistics, and if there's an unexpectedSeq Scanon a big table, the test fails. It's brittle, so only for the 10-20 most important queries. -
Volume. On staging, an anonymized copy of prod or generated big data. A load test (Gatling, k6) on the main scenarios.
-
Migrations. A linter (lock risk, an index without
CONCURRENTLY), and measuring the time on a prod-sized copy. -
Canary. The new version gets 5% of traffic. Queries that are new or whose
mean_exec_timejumped sharply inpg_stat_statementsraise 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.
Sign up to mark studied questions and save your progress.