When measuring latency, averages hide the real failures. During load testing, our dashboard endpoint degraded from an acceptable 150ms to over 800ms at the 99th percentile.
### The Investigation
Profiling the database using EXPLAIN (ANALYZE, BUFFERS) revealed that a seemingly innocuous JOIN across tenant records was triggering full sequential scans. PostgreSQL query planning opted for sequential scans because the foreign key columns were missing covering indexes for active tenant partitions.
### The Fix
Rather than throwing more CPU cores at the database, we tackled the access pattern directly: 1. Created a compound partial index scoped exclusively to active records. 2. Refactored the query from a monolithic join into a parameterized Common Table Expression (CTE) with bounded memory limits.
### The Result
Latency dropped from 800ms to 120ms at p99, and the buffer cache hit ratio rose to 99.4%. The biggest lesson: query planning behavior shifts dramatically once data volume passes cache boundaries. Always test query plans with realistic data distributions.










