
Lambda + PostgreSQL: You Probably Have This Connection Problem
A connection pool that works perfectly on a traditional backend can become a problem on lambda. Here's the mental model that changed how I manage SQL connections in serverless
Series: Thinking in Lambda (1 article)
- 1Lambda + PostgreSQL: You Probably Have This Connection Problem This article
If you've spent years building traditional backend system, you already have a mental model for database connections: create a pool, give it a reasonable size,reuse connections,and let the application handle traffic.
I've done exactly that.
Then you move to lambda, keep doing what you already know, and eventually realize something important:
the code still looks familiar, but the runtime model has completely changed.
That's where the connection problem starts.
Let's use a pretty normal stack:
- aws lambda
- nodejs
- postgres (RDS)
- pg
The code that looks perfectly fine
import { Client } from "pg";
export const handler = async (event: { userId: string }) => { const client = new Client({ connectionString: process.env.DATABASE_URL, connectionTimeoutMillis: 3_000, }); await client.connect(); try { const result = await client.query( "SELECT id, email, status FROM users WHERE id = $1", [event.userId], );
return { statusCode: result.rowCount ? 200 : 404, body: JSON.stringify(result.rows[0] ?? null), }; } finally { await client.end(); }};
Nothing here looks crazy. Connect, run the query, close connection.
That's a lifecycle we're used to seeing in backend applications
But there's a small problem
Every Lambda invocation now needs to establish a new database connection before doing useful work
So every time:
connect -> authenticate -> query -> disconnectNow imagine traffic goes up. Lambda starts scaling, 10 concurrent executions become 50 then 100 then 300, lambda is happy but you postgres might not be.
You're suddenly asking the database to deal with hundreds of connection attempts around the same time.
And that's usually when the symptoms start showing up:
- higher latency
- connection timeouts
- too many connections
- failures that only appear during traffic spikes
Lambda might actually be scaling faster than your database can comfortably follow.
Okay, so let use a pool. That's normally next improvement.
Instead of opening and closing a connection for every invocation, create the pool outside the handler:
import { Pool } from "pg";const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 1, min: 0, connectionTimeoutMillis: 3_000, idleTimeoutMillis: 60_000,});pool.on("error", (error) => { console.error("Unexpected PostgreSQL connection error", error);});export const handler = async (event: { userId: string }) => { const result = await pool.query( `SELECT id, email, status FROM users WHERE id = $1`, [event.userId], ); return { statusCode: result.rowCount ? 200 : 404, body: JSON.stringify(result.rows[0] ?? null), };};
Now the pool belongs to the lambda execution environment, not to a single invocation. If AWS keeps that environment warm, later invocations processed by the same environment can reuse the connection.
But this is where I made another assumption coming from traditional backend. The default pool configuration in a normal nodejs service might have something like:
const pool = new Pool({ max: 10 }) Ten connections, sounds harmless and on a persistent application server, it might be perfectly reasonable, but put the same configuration on inside lambda and the meaning changes.
So if lambda scales to 300 environments and each pool can open 10 connections: 300 x 10 = 3,000 possible connections, pg won't open all of them immediately, but that's the capacity you've allowed.
That's where the mental model changes. For a lambda doing one database operation at a time, I usually start with:
max: 1 Not because 1 is magic, but because the pool should match the concurrency inside one execution environment.
But
max: 1 isn't enough, 300 lambda environments can still mean roughly 300 database connections. If postgres can't safely handle that, I also limit lambda concurrency:GetUserFunction: Type: AWS::Serverless::Function Properties: Handler: dist/get-user.handler ReservedConcurrentExecutions: 100Sometimes scaling safely means putting a limit on scaling
What about RDS Proxy?
when traffic is bursty, multiple lambdas share the database, or connection pressure becomes a real problem, RDS Proxy starts to make sense.
const pool = new Pool({ connectionString: process.env.DATABASE_PROXY_URL, max: 1,});The architecture becomes:
lambda -> pgpool -> RDS Proxy -> PostgreSQL The local pool reuses connections inside the lambda environment. RDS Proxy manages connection pressure across many environments.
It won't fix slow queries, bad indexes, locks, CPU, or I/O. It solves a much more specific problem: connections
what I learned
The connection pool wasn't the problem. The mistake was assuming that a familiar configuration meant the same thing in a completely different runtime
In a traditional server, a connection pool limits pressure. In lambda, an improperly sized pool multiplies it. That’s the core question I now ask whenever lambda talks to a relational database: What happens to the database when lambda inevitably scales? Because if your product is successful, it definitely will.
Series: Thinking in Lambda (1 article)
- 1Lambda + PostgreSQL: You Probably Have This Connection Problem This article
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article