
Serverless Node.js: Architecting for Lambda
Abhay Vachhani
Developer
Serverless doesn't mean "no servers"; it means "someone else's servers." It changes the economic model of computing: you pay only for the milliseconds your code runs. For Node.js, which boots up quickly, this is a match made in heaven. But to build enterprise-grade serverless apps, you must go beyond a simple "Hello World" function.
1. The Cold Start Problem & Provisioned Concurrency
When your function hasn't run for a while, the provider (AWS, Vercel, Google) shuts down the container. The next request triggers a "Cold Start," adding 1s+ of latency.
- Bundle Optimization: Use tools like
esbuildto tree-shake your code. A smaller zip file = faster start. - Provisioned Concurrency: For critical paths (like checkout), you can pay AWS to keep X number of containers "warm" and ready to serve traffic instantly, eliminating cold starts entirely for those requests.
2. Managing Dependencies with Layers
If every Lambda function includes node_modules (100MB+), your deployments will be slow and your cold starts painful.
Lambda Layers allow you to package your dependencies (like sharp or ffmpeg) separately. You upload them once, and multiple functions can mount the same layer. This keeps your function code tiny and fast to update.
3. Handling Failures: SQS and Dead Letter Queues
Serverless functions often process events from queues (SQS). If a batch of 10 messages arrives and message #5 fails, the default behavior is to retry the entire batch.
The Fix: Use ReportBatchItemFailures. Your function returns the IDs of the specific messages that failed. SQS will only retry those specific messages, preventing "poison pills" from blocking the entire queue.
4. Infrastructure as Code (IaC): SST vs CDK
Clicking buttons in the AWS Console is not a strategy. You need IaC.
- AWS CDK: Define your infrastructure using TypeScript classes. Great for full control.
- SST (Serverless Stack): A wrapper around CDK tailored for modern full-stack apps. It offers a "Live Lambda Development" environment where you can debug local code against real AWS resources.
Conclusion
Serverless is perfect for "glue code," sporadic workloads, and highly scalable APIs. But it requires discipline. By optimizing your bundle size, using layers for dependencies, and handling partial batch failures correctly, you can build a serverless backend that is both cheaper and more resilient than a traditional VPS.
FAQs
Can I run a full Express app on Lambda?
Yes, using wrappers like `serverless-http` or `aws-serverless-express`, but it's often an anti-pattern (Monolith inside a Lambda). It increases cold starts. Ideally, break it down into smaller functions.
Is Serverless cheaper than a VPS?
For low to medium traffic, yes, drastically. For consistent, high-throughput loads, a dedicated server or container (EC2/Fargate) is usually more cost-effective.