ealeng

Episode 39 of 55 · Serverless

500 functions, one Postgres: 404 refused, then a pooler, a cap, retries and a queue

Five hundred function instances started at once against one Postgres with 100 connection slots, and 404 of them were refused a connection before they could run a query. Through a pooler holding 20 connections, all 500 succeeded but waited. Capped at 90 instances, 410 were turned away cleanly instead. On real AWS Lambda with an account limit of 10, 200 requests got 135 errors; with retries they all succeeded, and 500 messages sent through a queue were all processed with nothing rejected.

Lab 16 · Serverless and Event-Driven Compute10 min read
Video transcript9:58

0:00Cold open

0:01

I sent five hundred requests at the same moment to a small function that reads from Postgres.

0:08

Four hundred and four of them failed. Not after a wait: the database refused their connections before they could run a query.

0:18

Then I put a pooler in front of the database, with only twenty connections. All five hundred succeeded.

0:26

Then on real Lambda, limited to ten at once, two hundred requests got a hundred and thirty-five errors.

0:34

So why do functions break a database that one server handles fine? And what do you do when you hit a limit anyway?

0:43Intro

0:45

Hands-on system design, part thirty-nine.

0:48

Today: what a sudden spike of functions does to a database, and to the platform’s own limit.

0:55Meet Lucía

0:57

I’m Lucía, a platform engineer. Our API runs as functions on AWS Lambda: small pieces of code that Lambda runs for each request, on copies it starts as needed. Each copy is an instance.

1:12

The rule that matters today: an instance handles one request at a time. Five hundred requests at once need five hundred instances.

1:23

And our function opens its own database connection when its instance starts, and keeps it for as long as the instance lives.

1:32

Think of a car park with a hundred spaces. Every instance drives in its own car, and keeps its space while it lives. Five hundred cars are coming.

1:4301 · Where it runs

1:45

My cloud account allows only ten instances at once, so five hundred can’t happen there. Established accounts usually get a thousand.

1:55

So the first test runs on my laptop: a small function platform written for this test, with Lambda’s rules. One process per instance, connect once at start, one request at a time.

2:08

Postgres here allows a hundred connections, and keeps three for administrators. Each request runs a fifty millisecond query.

2:1902 · What you need

2:20

To run it yourself: Docker for the local part, and an AWS account for the second part, which costs a few cents.

2:29

The quick tests of the platform’s rules run in a couple of seconds, with neither.

2:3603 · Straight to Postgres

2:37

First, direct: five hundred calls at the same moment, and every instance connects straight to Postgres.

2:45

Ninety-six succeeded. Four hundred and four failed, in all three runs.

2:52

The error: the remaining connection slots are reserved for the administrator. The car park was full.

3:00

Those four hundred and four got an error, not a wait. Every space an app could use was taken: ninety-six by functions, one by the small program counting connections. The last three are kept for admins. Any other app would have been refused too.

3:17

The ninety-six that got in were fast: typically under a fifth of a second. But those are only the lucky ones. How fast the successes were says nothing about the failures.

3:3004 · In code

3:31

Here’s the function. The connection opens at the top, outside the handler. That line runs once, when the instance starts.

3:40

The handler then reuses it for every request that instance gets. That’s the usual advice on Lambda: it saves opening a connection per request.

3:51

But it also means five hundred instances hold five hundred connections.

3:5805 · A cap

4:00

Second try: the same, but the platform may start at most ninety instances. On Lambda, that’s called reserved concurrency.

4:09

Ninety succeeded. The other four hundred and ten were throttled: turned away at once, before they ever reached the database.

4:19

That’s a gate at the car park’s entrance. Almost the same number got served. And Postgres still had a few spare connections.

4:28

And a throttle is a clear “try again later”, which a caller can retry. A refused connection is just an error, with no hint to try again.

4:3906 · A pooler

4:40

Third: PgBouncer, a connection pooler. All five hundred instances connect to it instead. It holds only twenty real connections to Postgres, and lends one out for each query, then takes it back.

4:55

Twenty connections, five hundred requests. How many do you think succeeded?

5:02

All five hundred, in all three runs. Postgres never saw more than twenty from the pooler.

5:10

In the car park, the pooler is a shuttle bus with twenty seats: everyone gets in, in turns.

5:17

The price is waiting. Five hundred queries, twenty at a time, take at least one and a quarter seconds to get through. A typical request took one point six seconds: starting its instance, then waiting in that line.

5:3307 · A server

5:34

Last: no functions at all. One long-running server, with its own pool of twenty connections, takes the same five hundred requests.

5:44

All five hundred, the last one done in one point three seconds. A typical request took two thirds of a second, under half the pooler’s.

5:55

The same twenty connections, the same queue. Most of the difference: the server was already running, its twenty connections already open. Nothing had to start.

6:0708 · Real Lambda

6:08

Now the real cloud: Lambda. My account allows ten instances at once. Each request here does a tenth of a second of work, so ten instances serve about a hundred requests a second.

6:22

I sent two hundred requests at once through API Gateway, the front door for HTTP. Not five hundred: my laptop can’t hold that many connections open.

6:34

Still twenty times the limit. No retries.

6:38

Sixty-five were served. A hundred and thirty-five got a five-oh-three: service unavailable. That’s how the limit looks from outside.

6:49

Why sixty-five, not ten? Probably because they didn’t reach Lambda in the same instant: the answers came back over three seconds, so a freed instance could take a later one. I didn’t measure the arrivals. Another client would get another number.

7:0609 · Retries

7:08

Ten seconds later, the same two hundred. This time, each rejected request tries again, up to six more times, waiting a bit longer each time.

7:18

All two hundred were served. It took four hundred and forty-six attempts. The slowest one in a hundred took four and a half seconds.

7:28

The errors became waiting. It probably found the ten instances still running from the first burst too, which helped.

7:3810 · Backoff and jitter

7:39

The retry loop: send the request. If it succeeded, status two hundred, or the retries are used up, stop. Otherwise sleep, and try again.

7:50

The sleep is random: anywhere from zero up to a limit, and the limit doubles each time. Point two seconds, then point four, then point eight. That’s exponential backoff with full jitter.

8:03

Why random? With a fixed wait, the rejected requests would come back in the same lump they arrived in, and hit the limit together again.

8:1411 · A queue

8:15

Third Lambda test: a queue. Amazon’s SQS is a waiting line the messages sit in. It needs no open connection, so five hundred messages again.

8:28

Lambda takes at most five at a time. I set that, to keep five instances free.

8:34

Nothing was rejected. All five hundred were done seventeen point seven seconds after I started sending.

8:43

Five at a time, a tenth of a second each: ten seconds at best. It managed under thirty a second, probably because each message was its own call, with the queue’s own handling around it, and a write to a table.

8:58

A queue turns a spike into time. That’s the right shape for work nobody is waiting on.

9:06Back to Lucía

9:07

So, three lessons.

9:10

Functions multiply connections: one per instance. Put a pooler between them and the database: PgBouncer, or RDS Proxy on AWS.

9:22

A cap on instances turns errors into polite “try again later”s. And those need retries, with backoff and jitter.

9:31

If nobody is waiting for the answer, use a queue: no rejections, just time.

9:38

Next time: overload. What a service should do when more arrives than it can serve.

9:44

For today: count the connections.Lucía: Count the connections.

9:48Summary

9:49

Pool the connections, retry throttles with jitter, and queue what nobody waits for.

Key takeaways

  • ✓Every function instance opens its own database connection, so 500 instances at once asked a Postgres with 100 slots (3 kept for administrators) for 500 connections: 96 got in, and 404 failed to connect in all three runs.
  • ✓A cap of 90 instances turned the same burst into 90 served and 410 throttled, each turned away before it reached the database, so Postgres peaked at 90 connections and the failures became a clear try-again-later signal.
  • ✓A connection pooler, PgBouncer, let all 500 requests succeed while holding only 20 Postgres connections, but the typical request took 1.5 to 1.6 seconds (the p50 over three runs), against 0.67 to 0.70 seconds for one long-running server that used the same 20 connections.
  • ✓On real AWS Lambda with an account limit of 10 instances, 200 requests sent at once got 135 errors back (503 Service Unavailable) and 65 successes, because the account ran at most 10 instances at a time.
  • ✓With up to six retries, each waiting a random time that doubles from 0.2 seconds, all 200 requests succeeded, at a cost of 446 attempts and a p99 (the slowest one in a hundred) of 4.5 seconds.
  • ✓Sending 500 messages through SQS, a queue, with Lambda taking at most 5 at a time, rejected none of them and finished all 500 in 17.7 seconds, a median of 8.1 seconds from send to done: the right shape for work nobody is waiting on.

Five hundred function instances started at the same moment, and 404 of them were refused a database connection before they could run a query. This chapter follows Lucía, a platform engineer whose API runs as functions, through one spike and the four things that fix or soften it: a connection pooler, a concurrency cap, retries with backoff and jitter, and a queue. The examples come from Lab 16 (Serverless and Event-Driven Compute) of the system design labs. One script ran the spike against a local stand-in platform, and another ran the limit on real AWS Lambda, so the chapter says which numbers came from which.

Why many instances overwhelm one database

On AWS Lambda, your code runs in an instance: a copy of the function that Lambda starts as needed. An instance handles one request at a time, so 500 simultaneous requests need 500 instances. Each instance opens its own database connection when it starts, and keeps that connection for as long as it lives.

Think of a car park with 100 spaces. Each instance drives in its own car and keeps its space while it lives. Five hundred cars arrive at once, and most of them find no space.

The lab's Postgres allows 100 connections, and keeps 3 of them for administrators, so applications have 97. Every connection that a function opens is a space taken for as long as that function instance is alive. The code pattern most Lambda guides recommend makes this worse, not better: the connection is opened at the top of the file, outside the handler, so it is made once per instance and reused by every request that instance serves. That saves a connection per request, but it means 500 instances hold 500 connections.

Where the spike ran

Lucía's account allows only 10 instances at once, so 500 cannot run on it. The lab's spike script (03_spike.py) therefore ran on a small local function platform (local_faas.py) that copies Lambda's execution rules: one process per instance, a connection opened once at start, one request at a time. The platform, Postgres 17 with max_connections set to 100, and PgBouncer all ran in Docker on one Apple M4 Max laptop. Each request ran a query that sleeps for 50 milliseconds.

The second script (04_throttle.py) ran against real AWS Lambda, with the account's limit of 10 instances. The chapter's Lambda numbers are from that run.

Straight to Postgres

When the 500 calls arrive at once and each instance connects directly, the first 96 get their connection and run. The other 404 fail during their cold start, with this error from Postgres:

remaining connection slots are reserved for roles with the SUPERUSER attribute

The error does not mean the queries were slow. It means the database refused the connection before there was a query to run. The successful calls were fast, and that says nothing about the failed ones. Postgres's 97 usable slots were full: 96 for the functions, and one for the small program counting connections.

Any other application on the same database would have been refused too, which is why this is a database problem, not a function problem.

A cap turns failures into throttles

Lambda lets you limit how many instances a function may run at once, called reserved concurrency. With the platform limited to 90 instances, 90 calls were served, and 410 were turned away at the gate, before any instance started. Postgres peaked at 90 connections instead of 96, and it had a few spare.

A throttle is a different kind of answer from a refused connection. It is deliberate and quick, and it tells the caller that trying again later may work. A refused connection is only an error.

The lab's counts use "throttled" for these 410 calls. That is the lab's own label, not an HTTP status code.

Try it · 500 instances, one Postgresrecorded results, 03_spike.py

Each of the 500 instances opens its own connection. Postgres has 97 usable slots (3 are kept for administrators), so the rest of the connections fail during cold start with "remaining connection slots are reserved for roles with the SUPERUSER attribute".

Succeeded
96 of 500
Failed to connect
404
Peak Postgres connections
96
p50 ms (3 runs)
162–174

Postgres connection slots: 100 total, 3 for administrators

in use at the recorded peakfreekept for administrators

Latency is the range of the three runs' p50 and p99; the success and failure counts were identical in every run. “Throttled” is the lab's own label for a call the platform turned away, not an HTTP status.

A pooler serves everyone, more slowly

A connection pooler sits between the functions and the database. PgBouncer, the one the lab used, accepts client connections from all 500 instances and holds only 20 real Postgres connections. It lends one of those to a client for each transaction and takes it back afterwards. On AWS, RDS Proxy is the managed version of the same idea.

All 500 requests succeeded in all three runs, and Postgres never saw more than 20 connections from the pooler. The price is waiting. Five hundred queries of 50 milliseconds each, 20 at a time, take at least 1.25 seconds (500 × 0.05 s ÷ 20) just in line. The typical request took 1.5 to 1.6 seconds, because it also waited for its instance to start.

The lab then ran one long-running server with its own pool of 20 connections, and no functions at all. It served all 500 requests with the same 20 connections and the same queue, with a typical request of 0.67 to 0.70 seconds. The difference is the start-up: the server was already running and its connections already open, so nothing had to start for each request.

Real Lambda: a limit of 10

On the real account, the limit is 10 instances, and each request does 100 milliseconds of work. Ten instances can serve about 100 requests a second, whatever the arrival rate. The lab sent 200 HTTP requests at once through API Gateway, the front door that routes HTTP calls to Lambda. It sent 200 rather than 500 because the laptop could not hold that many connections open at the same moment.

With no retries, 65 requests were served and 135 got 503 Service Unavailable. That is what the limit looks like from outside. The lab did not measure when the requests reached Lambda, so it cannot say exactly why 65 were served instead of 10. Some requests likely arrived after an earlier one had finished, freeing an instance.

Retries with backoff and jitter

A rejected request can try again. The lab's client retries up to six times. Each wait is random between zero and a limit that doubles each time, starting at 0.2 seconds: a random wait up to 0.2 seconds, then up to 0.4, then up to 0.8. This is exponential backoff with full jitter.

With those retries, all 200 requests were served, using 446 attempts in total (about 2.2 per request). The slowest one in a hundred took 4.5 seconds. The errors became waiting.

The randomness is the point. If every rejected request waited exactly 0.2 seconds, they would all come back at the same moment, in the same lump that hit the limit the first time. Random waits spread them out.

Try it · A burst against a limit of 10 instancesrecorded run, 04_throttle.py, real Lambda

200 requests arrive at once through API Gateway. The account allows 10 instances, so 135 are answered with 503 Service Unavailable and never retried.

Served
65 of 200
Rejected (503)
135
Attempts
200
Instances at most
10
Served
33%
Rejected
68%
Pathp50p99Until the last
HTTP, no retry1,375 ms3,247 ms3.3 s

One recorded run per path. Queue latency is from send to done. The rejected count is the lab's count of 503 responses; the 446 attempts include the 200 first tries.

A queue turns the spike into time

Some work has no one waiting for the answer. For that, a queue is the better shape. The lab sent 500 messages to Amazon's SQS, a queue that functions read from, and set the queue's poller to take at most 5 messages at a time (MaximumConcurrency, the setting that caps how many invocations the poller runs at once), which keeps the other 5 instances free. Nothing was rejected. All 500 were processed in 17.7 seconds, a median of 8.1 seconds from send to done. The messages wait in SQS rather than on open connections, so the sender had no connection to be refused for.

The workflow and the results

The local spike (03_spike.py, three runs per design, 500 calls at once, 50 ms query each, PgBouncer restarted before each run). p50 is the typical successful request, and p99 is the slowest one in a hundred:

Design Succeeded Failed or throttled Peak Postgres connections p50 (three runs) p99 (three runs)
Straight to Postgres 96 404 failed to connect 96 162–174 ms 201–221 ms
Capped at 90 instances 90 410 throttled 90 109–127 ms 137–185 ms
Through PgBouncer, 20 connections 500 0 20 1,522–1,643 ms 2,113–2,257 ms
One long-running server, 20 connections 500 0 20 671–696 ms 1,292–1,312 ms

The counts were identical in all three runs of every design. The latency ranges are the lowest and highest of the three runs' values.

The real Lambda limit (04_throttle.py, one run per path, account limit 10, 100 ms of work per request):

Path Served Rejected (503) Attempts Instances p50 p99 Until the last
HTTP, no retry 65 of 200 135 200 10 1,375 ms 3,247 ms 3.3 s
HTTP, up to 6 retries 200 of 200 0 446 10 2,031 ms 4,494 ms 4.5 s
500 messages through SQS, at most 5 at once 500 of 500 none 500 5 8.1 s 15.1 s 17.7 s

For the queue row, the p50 and p99 are from send to done, and "until the last" is the time to finish all 500.

Where each part ran

  • Local (Docker, one laptop): the 500-instance spike, the three designs against Postgres, and PgBouncer. The function platform is a stand-in that follows Lambda's rules; it is not Lambda, and it has no AWS network or scaling behaviour.
  • Real AWS Lambda: the 200-request burst through API Gateway, the retry run, and the 500-message queue run, on an account with a limit of 10 instances. Those runs cost a few cents.

Caveats

  • Single runs for the Lambda numbers. Each Lambda path ran once. The retry run followed the no-retry run, so instances from the first burst may still have been warm and helped it. The lab did not measure this.
  • No 500-instance run on real Lambda. The 500-instance spike is local only. The real-Lambda burst is 200 requests, because the laptop could not hold 500 connections open at once.
  • The arrival times were not measured. The reason 65 requests were served, not 10, is not established by the lab.
  • The CloudWatch figure is not in the results. The lab's README says CloudWatch counted 381 throttles on the function in that minute (the 135 rejections plus 246 retried attempts). That number is not in the recorded results file, so treat it as the README's observation.
  • The local platform is a stand-in. It copies Lambda's rules, but its timings are not Lambda timings, and its database is a local Postgres container.
  • PgBouncer was tested, RDS Proxy was not. The chapter names RDS Proxy as the AWS version of the same idea, but the lab did not run it.
  • Not tested: reserved concurrency on the real AWS function (the cap of 90 ran only locally), provisioned concurrency, dead-letter queues for the SQS messages, long-running jobs, the cost of each design, and a real AWS database under a spike.

The checklist

  1. Count the connections before you count the requests. Every function instance holds its own connection for its whole life, so 500 instances need 500 slots on the database.
  2. Put a pooler between the functions and the database, such as PgBouncer or RDS Proxy, and expect each request to wait for a free connection.
  3. Cap the instances, and treat the cap as a throttle the caller can retry.
  4. Retry throttles with exponential backoff and random jitter, with a limit on the number of retries.
  5. Queue work that nobody is waiting for. A queue rejects nothing; it trades rejections for time.

Quiz

Try it · Check your understanding0 of 3 answered
  1. 1.Four hundred and four of 500 simultaneous function calls failed with a connection error, not a slow answer. Why?

  2. 2.A cap of 90 instances turned 410 calls away. Why is that better for the database than letting them connect and fail?

  3. 3.A client retries rejected requests on a fixed 1-second timer. Why does the lab use a random wait that doubles each time instead?

Check your understanding

Try each question before opening its answer.

Why did the cap of 90 instances give a better result for Postgres than letting all 500 instances connect?

Because with the cap, at most 90 instances existed, so Postgres peaked at 90 connections instead of 96 and the 410 turned-away calls never touched the database. Without the cap, 404 instances failed during their cold start, each after trying to connect. The cap does not make the spike smaller; it makes the answer to the spike a deliberate "try again later".

The pooler succeeded for all 500 requests, yet it was slower than the long-running server. Why?

Both used 20 Postgres connections, but the pooler's functions each had to start first, and the 500 requests queued for those 20 connections. The lab's arithmetic gives at least 1.25 seconds just for the queue. The server was already running with its connections open, so it paid neither the start-up nor the wait for an instance, and its typical request took 0.67 to 0.70 seconds.

Why does the retry loop use random waits instead of waiting a fixed 0.2 seconds each time?

A fixed wait would send all the rejected requests back at the same moment, into the same limit that rejected them. Random waits between zero and a doubling limit spread the retries across time, so fewer of them land on the limit together. This is exponential backoff with full jitter.

Which of the four fixes would you use for a caller that is waiting for an answer, and which for a background job that nobody waits on?

For a caller that waits, retries with backoff and jitter, because the answer has to come back to that caller and a throttle is a retryable answer. For a background job, a queue, because the 500 messages were all processed with nothing rejected, at the cost of a median of 8.1 seconds from send to done, which nobody waiting would accept but nobody waiting does not need.

For the full system design track, see the System Design index.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.