Serverless Architecture
Build event-driven serverless applications - Lambda functions, API Gateway, cold starts, IAM, and the Serverless Framework for infrastructure-as-code.
skill: Serverless Architecture category: Backend tags: [Serverless, AWS Lambda, FaaS, Cloud Functions, Event-Driven] readingTime: 6
Serverless eliminates server management - you pay per invocation, scale automatically, and deploy code without provisioning. Use it for event-driven tasks, APIs with variable traffic, and batch processing. Avoid it for long-running processes (> 15 min), warm connection pools (DB connections), or very high-throughput sustained loads where EC2 is cheaper.
Workflow
- Write Lambda functions correctlyLambda runs a handler function - the runtime reuses the execution environment between invocations, enabling connection reuse but requiring careful global state management.
- Deploy with the Serverless FrameworkThe Serverless Framework translates a simple YAML config into the full CloudFormation stack - Lambda, API Gateway, IAM roles, event sources.
- Optimize cold startsCold starts (first invocation after idle period) add 100ms-2s latency. For user-facing APIs, this degrades perceived performance.
- Handle concurrent invocations and throttlingLambda has per-account and per-function concurrency limits. Without reserved concurrency, one function can starve others.
- Connect databases efficientlyLambda creates new DB connections per cold start - 1000 concurrent Lambdas = 1000 connections, exceeding PostgreSQL limits.
Output Format
Serverless: Lambda handler with reused connections, Serverless Framework YAML, provisioned concurrency, reserved concurrency, and RDS Proxy.
serverless.yml:
provider: { runtime, iam.role.statements }
functions: { handler, events: [httpApi], timeout, memorySize }
resources: { DynamoDB, SQS, etc. }Examples
Edge Cases & Gotchas
- Lambda execution time limit - Maximum Lambda timeout is 15 minutes. For longer processes, use Step Functions, ECS tasks, or Batch - not Lambda.
- Payload size limits - API Gateway request/response payloads are limited to 10MB. For large uploads, use presigned S3 URLs - Lambda should never receive binary files directly.
- Environment variable encryption - Lambda environment variables are encrypted at rest but visible in the AWS console. Use SSM Parameter Store or Secrets Manager for secrets that shouldn't be visible in plaintext.
- VPC cold starts - Lambda in a VPC used to have 10+ second cold starts for ENI attachment. AWS resolved this in 2020 - VPC cold starts are now <1s in most regions.
When to Break These Rules
- Use ECS Fargate or containers for tasks that need > 15 min runtime, shared filesystem, or stable warm connections.
- Use serverless sparingly when your traffic is consistently high - EC2 or ECS is cheaper at sustained 1000+ RPS.
Reference Files
https://docs.aws.amazon.com/lambda/https://www.serverless.com/framework/docs