Senior LevelExpress JS
How do you optimize Express applications running in AWS Lambda using serverless-http?
❓ Interview Prompt: Explain running Express in AWS Lambda, serverless-http wrapper, top-level database connection pool reuse, and cold start optimizations.
Running Express inside AWS Lambda requires wrapping the app instance with 'serverless-http'.
Mitigating Lambda Cold Starts:
1
Top-Level Database Connection Pooling: Initialize database and Redis connection pools outside the exported handler function (in top-level module scope) so connection sockets are reused across warm Lambda invocations.
2
Minimize Bundle Size: Bundle code with 'esbuild' to strip unused dependencies and reduce zip artifact size below 5MB.
Code Implementation Example
javascript
import express from 'express';
import serverless from 'serverless-http';
import { PrismaClient } from '@prisma/client';
// Top-Level Module Scope: DB pool created ONCE and reused across warm Lambda hits!
const prisma = new PrismaClient();
const app = express();
app.get('/api/items', async (req, res) => {
const items = await prisma.item.findMany();
res.json(items);
});
// Export wrapped serverless handler for AWS Lambda
export const handler = serverless(app);💡Optimizing AWS Lambda Express cold starts using top-level connection pool reuse.
🎯 Interview Key Takeaway
Wrap Express with serverless-http and initialize database pools in top-level module scope for reuse across warm Lambda invocations.
#AWS Lambda#Serverless#serverless-http#Senior
Back to all Express JS Questions→