One of the biggest selling points of AWS Lambda is automatic scaling.
You deploy a function, connect it to an API, and AWS handles the compute infrastructure. When traffic increases, Lambda can create more execution environments to handle incoming requests.
Sounds great.
But what happens when every Lambda invocation needs a PostgreSQL connection?
Your application might scale from a few concurrent requests to hundreds while the database still has a limited number of available connections.
Suddenly, a system designed to scale automatically starts failing under traffic.
The problem isn't necessarily Lambda or PostgreSQL.
It's the mismatch between serverless concurrency and traditional database connection management.
I've worked on migrating more than 40 API endpoints to AWS Lambda, helping reduce hosting costs by 30%. That experience reinforced how important it is to think beyond the cost and scalability of the compute layer.
Let's look at why database connections become a bottleneck, how to manage them, and when RDS Proxy is worth adding.
1. The Hidden Problem With Serverless Scaling
Consider a traditional backend application running on a few servers.
Each server maintains a database connection pool.
Application Server A ── Pool (10 connections) ──┐ ├── PostgreSQL Application Server B ── Pool (10 connections) ──┘ The database receives connections from a relatively predictable number of application instances.
With AWS Lambda, the architecture is different.
As concurrent requests increase, Lambda can create additional execution environments.
For conventional Lambda functions, each execution environment processes one invocation at a time.
Now imagine a hypothetical workload where:
- Lambda reaches 300 concurrent executions.
- Each execution environment opens one database connection.
- The database has 200 connections available for this workload.
The application could attempt to establish more connections than the database can accommodate.
And that's with only one connection per execution environment.
If every environment creates a pool of five connections, the theoretical connection demand becomes much larger.
These are illustrative numbers, not measurements from a production system.
The important point is that compute concurrency and database connection capacity are two different scaling limits.
2. Why PostgreSQL Connections Aren't Free
Every PostgreSQL connection consumes resources.
PostgreSQL uses a process-based architecture, with a backend process handling each client connection.
Connections require memory and introduce management overhead.
When too many connections compete for resources, database performance can degrade even when individual queries are relatively simple.
You can inspect connection activity using:
SELECT state, COUNT(*) FROM pg_stat_activity WHERE backend_type = 'client backend' GROUP BY state; This helps identify how many client connections are active, idle, or in other states.
You can also inspect the configured connection limit:
SHOW max_connections; However, max_connections isn't the number your Lambda application can safely consume.
Other services, maintenance tasks, reserved connection slots, and existing application workloads also need capacity.
Increasing the connection limit might appear to solve the problem, but it can increase resource consumption without improving query throughput.
Sometimes the correct solution is fewer connections, not more.
3. Reuse Connections Across Lambda Invocations
A common mistake is opening a new database connection inside every handler invocation.
For example:
import pg from "pg"; export const handler = async (event) => { const client = new pg.Client({ connectionString: process.env.DATABASE_URL, }); await client.connect(); try { const result = await client.query( "SELECT id, name FROM products LIMIT 10" ); return { statusCode: 200, body: JSON.stringify(result.rows), }; } finally { await client.end(); } }; This creates and closes a connection on every request.
For a low-volume API, the cost might be acceptable. Under frequent invocations, repeated connection setup adds latency and database overhead.
Lambda execution environments can be reused.
This means objects initialized outside the handler can survive across multiple invocations handled by the same environment.
A more efficient approach is to create a small pool outside the handler:
import pg from "pg"; const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 1, connectionTimeoutMillis: 2000, idleTimeoutMillis: 30000, }); export const handler = async () => { const result = await pool.query( "SELECT id, name FROM products LIMIT 10" ); return { statusCode: 200, body: JSON.stringify(result.rows), }; }; For this example, max: 1 limits the pool to one connection per execution environment.
The pool can reuse its connection when the same environment handles another invocation.
The connection timeout also prevents the client from waiting indefinitely for a connection.
AWS recommends reusing connections outside Lambda handlers when practical.
Reference: AWS Lambda Best Practices.
But there's a catch.
Connection reuse reduces connection churn. It doesn't guarantee a low total connection count.
If Lambda creates hundreds of execution environments, each environment can maintain its own connection.
A locally bounded pool is not a globally bounded pool.
4. Use Reserved Concurrency to Protect the Database
AWS Lambda supports reserved concurrency.
It controls the maximum number of concurrent executions allowed for a function while reserving that capacity from the account's concurrency allocation.
This can help protect downstream systems.
For example, you might configure a function with a maximum concurrency of 50.
aws lambda put-function-concurrency \ --function-name orders-api \ --reserved-concurrent-executions 50 The function won't scale beyond that concurrency limit.
This creates a predictable upper bound for concurrent executions of that function.
However, it also introduces a trade-off.
Requests beyond the available concurrency can be throttled. For synchronous APIs, that may result in user-facing errors unless upstream services handle the situation appropriately.
Reserved concurrency should therefore be chosen using real workload data.
A useful starting estimate for conventional Lambda functions is:
Expected connection demand ≈ Concurrent execution environments × Connections per environment This isn't an exact production formula. Execution environment reuse, connection lifecycle, and application behavior affect actual demand.
It also doesn't account for connections from other services.
Still, it's useful for identifying configurations that could overwhelm the database.
Reference: AWS Lambda Reserved Concurrency.
5. When RDS Proxy Becomes Useful
For applications using Amazon RDS, AWS provides RDS Proxy.
It sits between Lambda and the database, managing a pool of database connections.
AWS Lambda | +----------+----------+ | | | v v v Lambda A Lambda B Lambda C | | | +----------+----------+ | v RDS Proxy | Managed Connection Pool | v PostgreSQL Without a proxy, each Lambda execution environment may establish its own direct database connection.
With RDS Proxy, multiple client connections can share a smaller pool of backend database connections when their transaction and session behavior allows reuse.
This is particularly useful for workloads with frequent, short database operations.
AWS recommends RDS Proxy for Lambda workloads that open and close large numbers of database connections.
Reference: Using AWS Lambda with Amazon RDS.
But RDS Proxy isn't magic.
It doesn't make slow SQL queries faster or increase the database's actual processing capacity.
If the database is already saturated by expensive queries, connection pooling alone won't solve the problem.
6. Watch Out for Connection Pinning
One detail that deserves more attention is session pinning.
RDS Proxy normally tries to reuse backend database connections across client sessions when it's safe.
But certain operations create session-specific state.
For example, changing PostgreSQL session variables can cause RDS Proxy to pin a client session to a particular backend connection.
Once pinned, that database connection cannot be freely reused by other client connections.
This reduces the benefits of multiplexing.
Long-running transactions can also keep database connections occupied, even without session pinning.
That's why adding RDS Proxy doesn't automatically mean your application can support unlimited Lambda concurrency.
You still need to inspect how the application uses transactions and session state.
AWS exposes a metric called DatabaseConnectionsCurrentlySessionPinned, which can help identify whether pinning is reducing connection reuse.
Reference: AWS RDS Proxy Session Pinning.
7. What Should You Monitor?
A serverless API can appear healthy at the Lambda layer while the database is approaching its connection limit.
I'd monitor both sides of the architecture.
| Metric | What it reveals |
|---|---|
| Lambda concurrent executions | How quickly compute demand is growing |
| Lambda throttles | Whether requests exceed concurrency limits |
| Lambda duration | Whether requests are becoming slower |
| RDS database connections | Connection pressure on PostgreSQL |
| Database CPU and memory | Whether queries are exhausting resources |
| RDS Proxy connection borrow latency | Whether clients are waiting for available connections |
| RDS Proxy pinned connections | Whether session pinning limits pooling efficiency |
For PostgreSQL, I'd also inspect pg_stat_activity to identify idle transactions and long-running queries.
One useful warning sign is rising connection borrow latency while Lambda concurrency increases.
That suggests the application may be waiting for database capacity rather than spending time executing useful queries.
Another is a large number of idle connections consuming resources without performing much work.
Don't rely on Lambda duration alone to diagnose the problem.
A slow request might be waiting for a connection, executing inefficient SQL, or calling another service.
Those require different fixes.
8. When You Don't Need RDS Proxy
Not every Lambda application needs an additional database proxy.
If your application has low concurrency, predictable traffic, and a small number of reused connections, direct PostgreSQL connections may be sufficient.
RDS Proxy introduces additional cost and another infrastructure component to configure and monitor.
There are also architectural alternatives.
For applications with simple, predictable key-value access patterns, DynamoDB may be worth considering.
Unlike PostgreSQL, DynamoDB doesn't require the application to manage traditional database connections.
However, choosing DynamoDB changes the data-modeling and query trade-offs. It's not a drop-in replacement for relational SQL.
AWS discusses these considerations in its database selection guide for Lambda applications.
My preference is to start with the workload's actual requirements.
If direct connections are working reliably, there's no need to add complexity purely for architectural appearance.
If connection churn and concurrency are becoming measurable problems, RDS Proxy becomes a more compelling option.
9. A Practical Production Checklist
Before deploying a Lambda-backed PostgreSQL API at scale, I'd verify a few things.
First, determine how many database connections the application can safely use.
Next, check whether connections are reused within Lambda execution environments and whether client-side pool sizes are appropriate.
Then load-test the application with realistic concurrency, including traffic spikes rather than only steady request rates.
If connection pressure becomes a problem, evaluate reserved concurrency and RDS Proxy.
Finally, test failure scenarios such as database restarts, stale connections, and connection acquisition timeouts.
The important part is measuring the complete request path.
Optimizing Lambda execution time doesn't help much if most of the request is spent waiting for PostgreSQL.
Final Thoughts
AWS Lambda makes scaling compute easier, but it doesn't remove the limits of the systems your functions depend on.
PostgreSQL connections are one of those limits.
Three lessons are worth remembering:
- Serverless scaling isn't database scaling. More concurrent Lambda executions can create more database connection demand.
- Reuse connections, but understand the limits. A small pool per execution environment can still become a large number of connections across many environments.
- Add RDS Proxy when the workload justifies it. Connection pooling helps manage concurrency, but it doesn't replace query optimization or database capacity planning.
Serverless architecture can reduce infrastructure management and hosting costs, but reliable scaling still requires understanding the dependencies behind every function.
Sometimes the bottleneck isn't your application code.
It's the number of connections your application is trying to open.
