Joseph Justus
Joseph Justus
DTDrizzle Team
Created by Joseph Justus on 4/20/2024 in #help
How not to exceed the max connections limit in the DB in a Serverless env like AWS lambda?
[question] What is the recommended way to use drizzle in a serverless environment like AWS lambda - that scales infinitely, in a way we do not exceed the max db connection limits and throttle/crash the DB? context: AWS lambda creates a new runtime instance with every concurrent request when there aren't any free instances to serve the request. And since lambdas can scale quickly, this leads to situations where each spawned instance creates a new connection to the DB if drizzle is initialized outside the handler function as recommended in the docs for connection reuse as shown below.
const databaseConnection = ...;
const db = drizzle(databaseConnection);
const prepared = db.select().from(...).prepare();
// AWS handler
export const handler = async (event: APIGatewayProxyEvent) => {
return prepared.execute();
}
const databaseConnection = ...;
const db = drizzle(databaseConnection);
const prepared = db.select().from(...).prepare();
// AWS handler
export const handler = async (event: APIGatewayProxyEvent) => {
return prepared.execute();
}
Question: If we move the connection creation and drizzle initialization steps inside the handler and close it after use each time, would it slow down and significantly increase the response time of each request as the connection and prepared statements are no longer cached?
Would using AWS RDS proxy help in any way? Are there other strategies to avoid this problem in a serverless environment?
3 replies