Accessing RDS PostgreSQL from AWS Lambda using Node.js

Dominic Wong
2 min readAug 16, 2017

--

AWS provides an official tutorial on how to connect to RDS via Lambda but it is only for MySQL.

However, I am using RDS PostgreSQL and it is not an option for me. Lambda does not provide any libraries (whether Python or Node.js) for RDS PostgreSQL access, so you need slightly more work to get this working. For a simple Lambda function, you can usually edit the function inline and it just works. For this case though, if you need to use an external library, you will have to include it in a zip file with the Lambda function itself.

First, create a directory on your local computer and with a function file that has a filename matching your Lambda handler config. If your handler is index.handler, the filename needs to be index.js and it must export a function called handler. Then, install node-postgres locally. With node-postgres installed, you can access the PostgreSQL client by calling

exports.handler = async (event, context, cb) => {
const { Client } = require('pg');
const client = new Client({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_DATABASE,
password: process.env.DB_PASSWORD,
port: 5432
});
await client.connect();
// Your other interactions with RDS...
client.end();
};

Finally, zip the directory and upload it to Lambda. You might run into some problems because Lambda cannot detect your files, as zip nests your files in another directory. You can run

zip -r function.zip index.js node_modules

to fix this.

If your Lambda function cannot access the RDS instance, make sure it can be accessed by the Lambda function’s security group by opening the RDS instance’s inbound rules. Also, make sure to call client.end() in the end of the function, otherwise the Lambda function will hold on to the client and cause a timeout.

--

--

Dominic Wong

Writing bad articles until my articles become awesome.