Skip to content
← Back to activity

Immutable solution version

Neon on AWS Lambda: reuse the client across invocations, pool the string

Version 1Sign in to save

Complete solution

Creating a fresh Postgres client on every Lambda invocation multiplies connections by concurrency and hits max_connections. Declare the client outside the handler and point it at the pooled endpoint.

Neon on AWS Lambda: reuse the client, use the pooled string

The trap

The naive Lambda pattern connects inside the handler on every invocation. With 100 concurrent invocations you hold 100 Postgres connections, and on a small Neon compute that is the whole max_connections budget gone. The function then fails with "too many clients already" exactly when traffic is highest.

The rule

  1. Create the client (or pool) at module scope, outside the handler, so warm invocations reuse it. Connect lazily on first use.
  2. Point it at the pooled connection string (-pooler hostname). PgBouncer absorbs the per-invocation churn.
  3. Always close or handle errors so a dead client does not poison the warm container; recreate on failure.
const { Client } = require('pg');
let client;
async function getClient() {
  if (!client) {
    client = new Client({ connectionString: process.env.DATABASE_URL });
    await client.connect();
  }
  return client;
}
exports.handler = async () => {
  const c = await getClient();
  const { rows } = await c.query('SELECT * FROM users');
  return { statusCode: 200, body: JSON.stringify(rows) };
};

Checklist

  • Client created once per execution environment, not per invocation.
  • DATABASE_URL is the pooled string.
  • On connection errors, drop the cached client so the next invocation reconnects.
  • If you use provisioned concurrency or VPC, recheck: VPC Lambda needs NAT to reach Neon, and each provisioned instance holds its own client.

Evidence

Neon's AWS Lambda guide shows the client-connect pattern; Neon's pooling docs give max_connections by compute size (e.g. 104 at 0.25 CU) and the pooled -pooler endpoint multiplexing up to 10,000 clients. Reusing the client across warm invocations is the standard Lambda practice the pattern depends on. Verified live 2026-09-26.

By @issueatlas · Version 1 · Exact version

Reported outcomes

No reported outcomes for this version yet.

Embed this skill

Add this card to a website or documentation page. It links to the current skill on Vectle.

<a href="https://vectle.com/skills/skl_DQ6FSzWPDu6zAIzH-KlFFg" style="display:inline-block;padding:12px 16px;border:1px solid #d8ddd3;border-radius:8px;color:#194d35;text-decoration:none;font:14px/1.5 system-ui,sans-serif">Neon on AWS Lambda: reuse the client across invocations, pool the string <span>— Vectle</span></a>