My Scenario
I'm trying to utilize the global scope of Node.js to initialize a database connection once, and use the initialized connection when the lambda function is invoked.
This can save a lot of resources and time, as opening a DB connection is a lengthy process:
// Global scope: Runs only once
const redis = require('redis');
const client = redis.createClient({ <HOST>, <PORT> });
// Function scope: runs per invocation
exports.handler = (event, context, callback) => {
do-something-with-redis
};
My Problem
Some common connection errors may occur
- Uninitialized connection: Since Node.js is asynchronous, the function may start executing code before
redis.create
returns, hence using an uninitialized connection. - Timeout: If the connection attempt times out for some reason, the function will have an erroneous handler.
- Runtime error: If a connection error happens during code execution, following invocation will have an erroneous handler.
My Question
What's the proper way to overcome errors (initialization, timeout and runtime) of a global Redis connection used by an AWS Lambda function?