Lambda Is Serverless, but Your Dependencies Aren't
Understanding database connections, connection pools, concurrency, and downstream bottlenecks in AWS Lambda applications.
Introduction
AWS Lambda removes the need to provision and manage application servers. You deploy your function, configure its triggers, and AWS handles the infrastructure required to execute it.
But there's an important detail that is easy to overlook:
Lambda can scale your compute much faster than the systems your function depends on.
Your database still has a connection limit. Your external API still has rate limits. Your VPC still has networking constraints. And your downstream services may not be able to handle hundreds of new concurrent requests.
This is where seemingly simple serverless applications start experiencing production problems.
Let's understand why this happens and how to design Lambda applications that scale without overwhelming their dependencies.
1. The Scaling Mismatch
Imagine a traditional backend running on a single application server.
It receives requests, processes them, and communicates with a database.
The application has a connection pool configured with a maximum of 20 database connections.
Even if hundreds of users send requests simultaneously, the application controls how many database connections it opens. The remaining requests wait for an available connection.
Now move the same application logic into AWS Lambda.
Instead of one application server handling all requests, Lambda can create multiple execution environments to process invocations concurrently.
Each execution environment runs an instance of your function.
Consider this simplified scenario:
Incoming Requests | v AWS Lambda | +-----------+-----------+ | | | v v v Lambda Lambda Lambda Env 1 Env 2 Env 3 | | | v v v Database Database Database | | | +-----------+-----------+ | v PostgreSQLThis architecture works perfectly well when the database can handle the incoming connections.
But what happens when traffic increases?
Lambda creates more execution environments. Each environment may establish its own database connections.
Suddenly, a database that previously handled 20 application connections might receive hundreds or thousands of connection attempts.
The application code has not changed. The database has not changed. Only the scaling behavior has changed.
Serverless compute scales independently. Your dependencies don't automatically scale with it.
2. The Database Connection Problem
Let's make the problem concrete.
Suppose you have:
- A PostgreSQL database with a maximum of 200 connections.
- A Lambda function configured to handle up to 500 concurrent executions.
- A database client that opens up to 5 connections per execution environment.
Your potential connection demand is:
[
500 \times 5 = 2,500
]
Your database can only accept 200 connections.
You can see the problem.
The database connection limit is exhausted long before Lambda reaches its configured concurrency.
This is a simplified upper-bound calculation. Actual connection usage depends on how many environments are active, how clients establish connections, and how connections are reused.
The important relationship is:
\text{Concurrent Environments}
\times
\text{Connections per Environment}
]
This is why database connection management deserves special attention in Lambda applications.
Why connection pools can make things worse
Connection pooling is a common solution in traditional backend applications.
Instead of opening a new database connection for every request, the application maintains a pool and reuses existing connections.
For example, with Node.js and PostgreSQL:
import { Pool } from "pg";
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 10,});
export async function handler(event) { const result = await pool.query( "SELECT * FROM users LIMIT 10" );
return { statusCode: 200, body: JSON.stringify(result.rows), };}This is a reasonable pattern for a long-running Node.js server.
But consider what happens when you deploy it to Lambda.
Each execution environment can create its own pool.
If Lambda creates 100 environments and every pool allows 10 connections, the theoretical connection demand becomes:
[
100 \times 10 = 1,000
]
You did not create one shared pool for the entire Lambda function.
You created one pool per execution environment.
This distinction is easy to miss.
3. Reuse Connections Across Invocations
One of the first things to do when building Lambda applications is to initialize reusable clients outside the handler.
Lambda execution environments can be reused across multiple invocations. Objects initialized outside the handler can therefore survive between invocations in the same environment.
For example:
import { Pool } from "pg";
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 1, idleTimeoutMillis: 30000, connectionTimeoutMillis: 5000,});
export async function handler(event) { const result = await pool.query( "SELECT * FROM users LIMIT 10" );
return { statusCode: 200, body: JSON.stringify(result.rows), };}Notice that the pool is initialized outside the handler.
This allows subsequent invocations handled by the same warm environment to reuse the pool.
There are two important details here:
- Lambda does not guarantee that an execution environment will be reused.
- Different concurrent execution environments still have independent pools.
Setting
max: 1 means each environment can maintain at most one connection through this pool. It does not mean the entire Lambda function uses only one connection.Also, this example assumes that your handler does not need multiple simultaneous database operations. If it does, adjust the pool size according to actual workload requirements.
For Lambda, smaller per-environment pools are often more appropriate than copying the pool configuration from a traditional application server.
AWS recommends reusing execution environments and database connections where appropriate, while also considering connection pooling for workloads with frequent short-lived database connections.
4. Amazon RDS Proxy: Put a Connection Manager Between Lambda and Your Database
AWS provides a service specifically useful for this problem: <Entity value="Amazon RDS Proxy" category="software" disambig="AWS managed database connection proxy"/>.
Instead of connecting directly to PostgreSQL or MySQL, your Lambda functions connect to RDS Proxy.
The proxy maintains a pool of database connections and manages how client connections are multiplexed onto backend database connections.
The architecture becomes:
Lambda Invocations | +-----------+-----------+ | | | v v v Lambda Lambda Lambda Env 1 Env 2 Env 3 | | | +-----------+-----------+ | v RDS Proxy | Shared Connection Pool | v RDS DatabaseThe important difference is that Lambda execution environments no longer need to establish a separate long-lived database connection directly to the database for every client connection.
RDS Proxy manages the database-side connections and can reuse them across client sessions.
This helps with:
- Sudden increases in Lambda concurrency.
- Frequent database connection establishment.
- Connection exhaustion.
- Database failover scenarios.
- Applications with many short-lived database interactions.
AWS recommends considering RDS Proxy for Lambda applications that make frequent short database connections or open and close large numbers of connections.
Does RDS Proxy eliminate connection limits?
No.
It reduces connection pressure on the database, but it does not make the database infinitely scalable.
The database still has limits on:
- Maximum connections.
- CPU and memory.
- Query execution capacity.
- Transaction throughput.
- Lock contention.
- I/O capacity.
There is also an important concept called session pinning.
Certain session-level operations can cause RDS Proxy to pin a client session to a particular backend database connection. This reduces the effectiveness of connection multiplexing.
Long-running transactions and certain session state changes can also reduce connection reuse.
So RDS Proxy is not a replacement for understanding your database workload.
It is a connection management layer, not a magic database scaling solution.
5. Concurrency Is a Resource Management Tool
Lambda concurrency is often discussed in terms of performance.
How many requests can the function handle? How quickly can it scale? How do we avoid throttling?
But concurrency is also an important way to protect downstream services.
AWS provides a feature called reserved concurrency.
Reserved concurrency allows you to set a maximum concurrency for a function and reserves that capacity from the account's available concurrency pool.
For example:
Lambda Function: order-processor
Reserved Concurrency: 50
Maximum Concurrent Executions: 50Even if thousands of requests arrive, Lambda will not execute more than 50 concurrent invocations of this function.
Additional requests may be throttled or handled according to the behavior of the event source.
Why would we intentionally limit a serverless function?
Because the database might only be able to support 50 concurrent workloads from that function.
Or perhaps an external payment provider allows only a certain number of concurrent requests.
In those situations, limiting Lambda concurrency is not a performance problem. It is a protection mechanism.
Reserved concurrency vs. provisioned concurrency
These two features are often confused.
Feature | Reserved concurrency | Provisioned concurrency |
|---|---|---|
Primary purpose | Reserve and cap concurrency | Pre-initialize execution environments |
Limits maximum concurrency | Yes | Not by itself |
Reduces cold starts | No | Yes, for allocated capacity |
Protects downstream services | Yes | Not directly |
Additional charge | No additional charge for the setting | Additional charge |
Provisioned concurrency is useful when you need predictable startup latency.
Reserved concurrency is useful when you need to protect a dependency from excessive parallel execution.
They solve different problems.
For example, increasing provisioned concurrency does not automatically make your database capable of handling more connections.
6. Not Every Dependency Is a Database
Database connections are only one example.
Your Lambda function may communicate with several other systems:
- Payment gateways
- Third-party REST APIs
- Redis or other caching systems
- Internal microservices
- Search engines
- SMTP services
- Message brokers
Each dependency has its own capacity constraints.
Consider an application that processes incoming orders and calls a payment provider.
The payment provider might allow 100 requests per second.
Your Lambda function, however, could receive enough traffic to generate 500 requests per second.
The result might be:
- HTTP 429 responses.
- Increased latency.
- Request timeouts.
- Failed transactions.
- Repeated retries.
- Cascading failures.
Lambda has successfully scaled. The payment provider has not.
This is why we need to think about downstream capacity when designing serverless applications.
Reuse HTTP connections
Another useful optimization is to reuse HTTP clients and connections.
For example, in Node.js, avoid creating a new HTTP client or connection pool for every invocation when the client supports safe reuse.
You can initialize reusable clients outside the handler:
import https from "node:https";
const agent = new https.Agent({ keepAlive: true, maxSockets: 10,});
export async function handler(event) { const response = await fetch( "https://api.example.com/orders", { headers: { Authorization: `Bearer ${process.env.API_TOKEN}`, }, dispatcher: undefined, } );
return { statusCode: response.status, };}The example above illustrates the idea of reusing a client, but Node.js
fetch does not use https.Agent as its dispatcher. For Node.js built-in fetch , use a compatible Undici dispatcher such as Agent instead.The broader principle is to reuse supported HTTP clients and connection pools across warm invocations rather than repeatedly creating them.
Connection reuse reduces TCP and TLS handshake overhead, but it does not solve API rate limits or downstream capacity constraints.
7. Use SQS to Control the Rate of Work
Sometimes limiting Lambda concurrency is not enough.
Imagine you receive 10,000 image-processing requests within a few seconds.
Each request requires calling an external service that can process only 50 requests per second.
If you invoke Lambda directly for every request, you can overwhelm that service.
A better architecture is to introduce a queue.
Incoming Requests | v Amazon SQS | v Lambda Worker | v External ServiceSQS decouples incoming traffic from processing capacity.
Messages can accumulate in the queue while Lambda processes them at a controlled rate.
You can configure the Lambda event source mapping to limit the maximum concurrency used to consume messages.
For example:
Queue: image-processing
Maximum Lambda Concurrency: 20
Worker: Receive message Process image Call external API Store result Delete messageNow the worker cannot scale without limit just because the queue contains thousands of messages.
This gives you a mechanism to control how quickly work reaches the downstream dependency.
Why this is useful
SQS provides:
- Buffering during traffic spikes.
- Decoupling between producers and consumers.
- Retry handling.
- Dead-letter queue support.
- Controlled processing concurrency.
But remember that SQS uses at-least-once delivery for standard queues.
Your worker should be idempotent so that processing the same message more than once does not produce duplicate side effects.
Also, configure visibility timeouts, batch sizes, retry behavior, and dead-letter queues carefully.
For more control over the processing rate, consider event source mapping maximum concurrency and, where appropriate, provisioned pollers or other event-source-specific scaling controls.
8. Backpressure: Stop Accepting Work You Cannot Process
Queues help buffer traffic, but buffering alone does not solve every overload problem.
If incoming work consistently arrives faster than your system can process it, the queue will continue growing.
Eventually, you may run into:
- Increased processing delays.
- Higher storage costs.
- Expired messages.
- User-facing timeouts.
- Downstream service degradation.
This is where backpressure becomes important.
Backpressure is the idea of controlling incoming work based on the capacity of the system processing it.
For example, imagine:
Incoming Work: 500 requests/secondProcessing Capacity: 50 requests/secondThe system is receiving work ten times faster than it can process it.
Instead of blindly increasing concurrency, we need to decide what to do with excess demand.
Possible strategies include:
- Queueing work for later processing.
- Rejecting requests temporarily.
- Applying rate limits.
- Reducing concurrency.
- Prioritizing critical operations.
- Returning a retryable response to clients.
For synchronous APIs, API Gateway throttling and Lambda reserved concurrency can help protect the backend.
For asynchronous workflows, SQS provides a durable buffer.
The key is to make overload behavior intentional rather than allowing it to emerge as a production incident.
9. VPC Networking Has Its Own Constraints
A Lambda function that needs to access private resources, such as an RDS database in a VPC, must be configured for VPC access.
AWS manages the networking infrastructure using Hyperplane Elastic Network Interfaces (ENIs).
You do not need to manually create and manage these interfaces for normal Lambda VPC connectivity.
However, networking still deserves attention.
Things to consider include:
- Subnet IP address availability.
- Security group rules.
- Network ACL configuration.
- NAT gateway capacity and cost.
- VPC endpoint configuration.
- Connection limits and DNS behavior.
For example, Lambda uses Hyperplane ENIs associated with subnet and security group combinations. AWS documents that these ENIs can support up to 65,000 connections or ports, with additional ENIs allocated as required.
That does not mean every Lambda function has an independent 65,000-connection allowance. The networking resources are shared according to the relevant subnet and security group combinations.
Also, if your function needs to access AWS services privately, VPC endpoints can avoid sending that traffic through a NAT gateway.
One more easily overlooked issue: Lambda documents a limit of 20 concurrent TCP connections for DNS resolution. This is relevant in specific DNS configurations and is worth knowing when investigating unusual DNS failures.
For the details, see:
10. A Practical Checklist Before Scaling Lambda
Before deploying a Lambda application that communicates with databases and external services, I would review the following.
Area | Questions to ask |
|---|---|
Database connections | Is the connection pool initialized outside the handler? |
Pool sizing | How many connections can each environment create? |
Database capacity | Can the database handle peak connection demand? |
RDS Proxy | Would connection pooling and multiplexing help? |
Concurrency | Is reserved concurrency configured appropriately? |
HTTP clients | Are clients and supported keep-alive connections reused? |
External APIs | Are rate limits and concurrent request limits understood? |
Queue processing | Should SQS buffer incoming work? |
Retries | Can retries amplify an outage? |
Idempotency | Can the same event be processed more than once safely? |
Monitoring | Are throttles, connection counts, latency, and queue age monitored? |
Networking | Are VPC configuration and subnet capacity appropriate? |
Also monitor the actual behavior of your dependencies.
For example, useful CloudWatch metrics include:
- Lambda
ConcurrentExecutions
- Lambda
Throttles
- Lambda
Duration
- Lambda
Errors
- RDS
DatabaseConnections
- RDS CPU utilization
- RDS Proxy client and database connection metrics
- SQS
ApproximateAgeOfOldestMessage
- SQS
ApproximateNumberOfMessagesVisible
A healthy Lambda function does not necessarily mean a healthy application.
Your database might be approaching its connection limit while Lambda reports successful invocations.
Your external API might be returning 429 responses while your function itself remains operational.
Monitor the entire dependency chain.
Conclusion
AWS Lambda removes server management, but it does not remove the constraints of the systems your application depends on.
Your database still has a connection limit. External APIs still have rate limits. Networks still have finite capacity. And every downstream service has a maximum workload it can handle.
The mistake is assuming that because Lambda can scale automatically, the entire application can scale automatically.
A reliable serverless architecture needs to account for those boundaries.
Start by reusing connections across warm invocations. Size connection pools carefully. Consider RDS Proxy for relational database workloads. Use reserved concurrency to protect downstream services. Introduce queues when you need to buffer and control incoming work. And monitor dependencies instead of looking only at Lambda metrics.
Serverless does not mean limit-less. It means you no longer manage the servers, but you still need to manage the capacity of everything around them.
Further Reading
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article