Skip to content

Instantly share code, notes, and snippets.

@streamich
Forked from maxbeatty/lambda.js
Last active April 29, 2024 19:45
Show Gist options
  • Save streamich/6175853840fb5209388405910c6cc04b to your computer and use it in GitHub Desktop.
Save streamich/6175853840fb5209388405910c6cc04b to your computer and use it in GitHub Desktop.
using node-postgres (`pg`) in AWS Lambda
import λ from "apex.js";
import { Pool } from "pg";
// connection details inherited from environment
const pool = new Pool({
max: 1,
min: 0,
idleTimeoutMillis: 120000,
connectionTimeoutMillis: 10000
});
export default function λ(async (event, context) => {
// https://github.com/brianc/node-postgres/issues/930#issuecomment-230362178
context.callbackWaitsForEmptyEventLoop = false; // !important to reuse pool
const client = await pool.connect();
try {
await client.query("SELECT NOW()");
} finally {
// https://github.com/brianc/node-postgres/issues/1180#issuecomment-270589769
client.release(true);
}
});
@NuniTelo
Copy link

NuniTelo commented Mar 3, 2023

This is perfect.
For anyone that may work with this, please don't forget:

finally{
    client.release();
}

Without that, after ~10 requests, your Lambda will throw an error.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment