Production Reality
Latency You Can Actually Fix
N plus one queries are a latency amplifier, which is why they survive staging and die in production. Pooling, planner diagnostics and cache keys are the rest of it.
Averages are the enemy here. A mean response time of 180 milliseconds with a 99th percentile of four seconds means one request in a hundred is terrible, and those requests are not randomly distributed: latency tracks how much data an account holds, so the worst experience in your product belongs to your largest customer. Read percentiles per endpoint, or you are not reading anything.
The path, and what each hop costs you
- Browserbundle size and render; the only hop your user can actually see
- CDN or edgenearly free when it hits; the one hop whose cost is a wrong cache key
- Function or servercold start, concurrency ceiling, and wall-clock billing while it waits
- Connection poolermandatory under serverless concurrency; transaction mode silently breaks some SQL features
- Postgresmissing index, N plus one, lock contention, a plan built on stale statistics
Most of the time in a slow page is spent in the last two hops, and most engineering attention goes to the first two. Measure before you believe anything at all about your own system, including the parts of this lesson.
N plus one is a latency amplifier
The pattern is one query to fetch a list and then one query per item in it, and the arithmetic is why it survives review and kills you later. Two hundred extra round trips at one millisecond each, roughly what you get with the database in the same region, is two hundred milliseconds and nobody notices. The identical code at twenty-five milliseconds per round trip, because the database moved region, or a pooler was added, or you are crossing the public internet, is five seconds. The bug did not change, the latency it multiplies did, which is why this passes staging and dies in production.
The fix is to ask for everything in one round trip: a join, an IN clause over the collected identifiers, or your data layer's explicit eager loading. The habit worth building is counting queries per request in development, with the number on the page, in red above ten. Then this gets caught in the hour it is written rather than the quarter it becomes urgent.
Finding the real problem instead of guessing
Two tools answer two different questions. pg_stat_statements tells you which statements cost most in aggregate, which is almost never the one you suspect: a one millisecond query called two hundred times per request outranks a three hundred millisecond report that runs twice a day. EXPLAIN with ANALYZE and BUFFERS tells you why one statement is slow, and its most diagnostic line is estimated rows against actual rows. When those differ by orders of magnitude the planner was working from bad information, usually stale statistics, a correlation between columns it cannot see, or a function it cannot look inside, so inform the planner rather than rewrite the query by feel.
Two structural ones worth checking today. Foreign key columns carry no index unless you created one, so deleting a parent row or updating its key scans the child table, which is the most common missing index in an application nobody has profiled. And OFFSET pagination reads and discards every row it skips, so page five hundred reads five hundred pages of rows before returning anything; keyset pagination, asking for rows after the last value you saw, does not.
Connections are a resource, and serverless multiplies them
Postgres uses one operating system process per connection, a fixed and fairly expensive unit, which is why the connection limit is low relative to the number of concurrent function instances a serverless platform will cheerfully start. Concurrency times connections per instance exceeds the limit, and the failure is not slowness, it is a flood of connection errors under exactly the load you wanted. A pooler is mandatory, not an optimisation.
Know what you give up. Supabase's Supavisor exposes session mode and direct connections on one port and transaction mode on another. Transaction mode is what makes pooling effective at serverless concurrency, and it breaks prepared statements, session level SET, LISTEN and NOTIFY, and advisory locks. Teams adopt the pooler, meet a class of mysterious errors, and lose a week to them.
Caching, in the correct order
Caching is the fourth thing to try, not the first. Do less work. Then do it once. Then move it out of the request into a job. Only then cache, because a cache in front of a bad query is a faster way to serve a stale wrong answer, and you have now added an invalidation problem on top of a performance problem.
When you do cache, the key must include every input that varies the output, including identity, for the reason the tenancy lesson gave. Concretely: Cache-Control private for anything personal, s-maxage for the shared layer against max-age for the browser, ETag for revalidation, stale-while-revalidate so expiry is not a latency cliff. Vary needs one warning of its own. Vary on Cookie is correct and close to useless at a shared layer, because every distinct cookie string becomes its own entry, so one analytics cookie that changes per visitor fragments your hit rate to nothing. Strip the cookies that do not change the response before the cache sees them, or keep personalised responses out of the shared layer and cache the shell instead. And expiry on a popular key sends every waiting request to your database at once, so either hold a lock while one refills or serve the stale value while a single refresh happens behind it.
Timeouts on everything that leaves your process
Many HTTP clients default to no timeout at all. That is how one slow vendor consumes your entire function concurrency: every instance alive, none doing anything, and your product down because of a dependency that is merely slow. Give every outbound call a timeout that fits inside your own budget, retry only idempotent operations and only with backoff and jitter, and put a circuit breaker in front of anything you can degrade without. Then decide, per dependency, what your product does while it is unavailable, because that decision gets made either by you now or by an exception handler at the worst moment.
Key takeaways
This is one lesson of 541.
The whole Foundation is free — 16 subjects, beginner to advanced. Sign in to track what you have read, take the end-of-module quizzes, and use the terminal.