First bottlenecks when traffic grows

Advanced · 9 min

Learn the order Taskboard breaks as traffic grows, connections, slow queries, repeated work, and the cheap fixes to try before adding servers.

Before thisPerformance across the stackBackground work and email from a featureDatabase hosting, backups and restores

programmerCave · 9 min

First bottlenecks when traffic grows

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by programmerCaveReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • In most small apps the database is the first thing to hurt, and the fixes with the best return come before any talk of more servers: connection pooling, indexes, and removing repeated queries.
  • A database accepts only a limited number of connections, and opening one per request fails with too many clients once concurrency passes that limit.
  • A connection pool caps connections and queues the rest, so 25 simultaneous requests share 5 connections instead of crashing.
  • Find the bottleneck with measurement, since the slowest resource sets the ceiling and scaling anything else does not raise it.
  • Caching, read replicas and extra instances each add a consistency or operational cost, so adopt them in response to a measured limit, not in advance.

What “traffic grows” actually means

Taskboard launched on a small plan and a small database. Then a company with 400 people adopts it, and Monday at 9am everyone opens it within the same ten minutes. Pages slow down, then some requests return errors. The temptation is to buy a bigger server or add more instances.

Often that is the wrong first move. Every system has a slowest part, and the system can only go as fast as that part. Adding capacity anywhere else changes nothing, or makes it worse. The skill in this lesson is finding the narrow part, and the usual answer for an app like this is the database.

The usual order things break

For a typical Taskboard-shaped app (one API service, one Postgres), the order I would expect, and what to do first:

  1. Connections run out. Each request opens a database connection, and Postgres has a hard cap.
  2. A few queries are slow under load. A query that took 5 ms on empty tables takes 400 ms on a large one, and many at once starve the rest.
  3. The same work is repeated. Thousands of users load the same project list, and each load recomputes it.
  4. Something outside the request path piles up. Email, exports and webhooks do work in the request path that should have been a job. (Fixed by the previous lesson.)
  5. One process is not enough. The API’s CPU is saturated.

Only the last one is solved by adding instances, and it is the last one for a reason: a Node API that mostly waits on the database uses little CPU.

Bottleneck 1: connections

Postgres processes each connection separately and caps their number with max_connections. If every request opens its own connection, then concurrent requests are limited by that cap, regardless of how fast each is.

I reproduced this on a scratch Postgres 14.25 with max_connections=10, using pg 8.23.1 on Node 26. Twenty-five simultaneous requests, each opening a connection and running a 200 ms query:

per-request connections: 10 ok, 15 failed; [ 'sorry, too many clients already' ]

The database was not busy. It was out of connection slots. The fix is a pool: the app opens a small fixed number of connections at startup and lends them out. A request that arrives when all are lent out waits in a queue:

pool(5): 25 ok in 1020 ms (25 x 200ms / 5 slots ~ 1000ms)

All 25 succeeded. They took about a second because only five ran at a time. That is the trade: a pool turns a crash into a wait. A pool is like a restaurant’s host: a fixed number of tables, and a line outside when they are full.

The pool size is a real decision. Too small and requests queue even when the database is idle. Too large, summed across every instance of your API, and you are back at max_connections. If you have four instances with a pool of 20, that is 80 connections from one service. Managed databases often cap connections low on small plans, and serverless platforms can create many instances, in which case a pooler in front of the database (PgBouncer or the provider’s built-in one) is the usual answer. The mechanics are in SQL databases with Node and connection pools and connection pooling and read-write splitting.

Bottleneck 2: queries that don’t scale with data

On a table with a hundred rows everything is fast. The queries that hurt at 10 million rows are the ones that read every row (missing index), run once per item in a list (N+1), or return far more than the screen shows (no pagination). The previous lesson performance across the stack showed how to read a plan and fix each. At this stage the process is:

  • Turn on the database’s slow-query log or use your provider’s query statistics, and list the top queries by total time. The query to fix first is the one that costs the most in total, which is often a medium-slow query called constantly rather than the single slowest.
  • Run explain analyze on it, add the index or rewrite it, and compare.
  • Paginate any list that can grow without limit. See pagination, filtering and search end to end.

Bottleneck 3: repeated work

Once queries are cheap, the next saving is not doing them. If thousands of people load the same read-mostly data, put a short-lived copy in front:

  • HTTP caching for responses that are safe to reuse: Cache-Control on static assets and on public API responses.
  • An application cache, in memory or Redis, keyed by what the query depends on, with a short expiry.
  • A CDN for the client’s static files, which you probably already have from the deploy.

Every one of these gives you two copies of the truth, and your problem becomes knowing when the copy is stale. A task the user just edited must not show its old title for a minute. Cache what is expensive and tolerant of staleness, expire it quickly, and invalidate on writes where you can. See caching in application code and caching strategies at scale.

Protecting yourself from the spike

Some load is not growth but abuse or a bug: a script hitting the API in a loop, or a client retrying aggressively. A rate limit keeps one caller from using everyone’s capacity, covered in rate limiting implementation in your app. Put timeouts on every outbound call too, so a slow third party cannot hold all your connections.

Only then, scale out

If the API’s CPU or memory really is saturated, run more instances behind a load balancer. This works cleanly only if the API is stateless: no sessions in memory, no files on local disk, and uploads in object storage. Taskboard’s cookie-session store should live in the database or Redis for this reason. If your read load is high and your data tolerates slightly stale reads, a read replica takes SELECTs off the primary, at the cost that a user may not see their own write immediately.

None of this needs a rewrite or microservices. Most apps in Taskboard’s class reach many thousands of users with one well-indexed Postgres, a pool, some caching and a few API instances. The broader picture and the techniques beyond it are in scaling, load balancing and clustering, and a quick way to size what you will need is back-of-the-envelope estimation.

How to know it worked

Test before the Monday rush, not during it. A load test replays realistic traffic against staging (never against production with real users, and never with production secrets) while you watch the metrics from observability across layers: request latency, database connections in use, query time. The first number to hit its ceiling is your next bottleneck. Fix it, test again, and stop when the app comfortably handles the traffic you expect with some margin.

What the video covers

programmerCave’s “Why Your Database is the Bottleneck (16 Rules for Building Scalable Software)” runs about eight and a half minutes and is a year and a half old. Its title says it is a blog explainer, so expect a list of rules read through quickly rather than a worked demo. I could not read a transcript, so I cannot say which of the sixteen rules overlap with the ones above. It is the closest focused pick I found for the “database is the limit” idea, from a small channel. ByteByteGo’s database scaling video is linked as a second, more visual view that goes into replication and sharding.

Where this fits

A faster, larger app is also a more attractive target. Before the launch, one deliberate pass over the whole stack for security: a security review before launch.

Check yourself

  1. 01What happens when each request opens its own database connection and traffic spikes?

    Postgres reaches max_connections and refuses new ones with an error such as 'too many clients already', so requests fail even though the server is not busy with work.

  2. 02How does a pool of five connections handle 25 simultaneous queries?

    It runs five at a time and queues the rest, so all 25 finish, just later, instead of failing.

  3. 03Why measure before adding a second API server?

    If the database is the limit, more API instances send more concurrent queries to the same bottleneck and can make it worse.

  4. 04What is the cost of adding a cache?

    You now have two copies of the data, so you must decide when the cache is stale and how it is invalidated, and bugs show up as users seeing old data.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark