Architecture Overview
The full stack consists of three layers, each serverless and independently deployable:
The key insight: Cloudflare sits in front of everything — both your static frontend and your API. This means DDoS protection, WAF rules, and edge caching apply uniformly without any per-service configuration.
Step 1 — S3 Static Hosting Setup
Start by creating an S3 bucket with static website hosting enabled. We deliberately leave public access blocked — Cloudflare will access the bucket via an Origin Access Control (OAC) policy, not the public internet.
# Create bucket
aws s3api create-bucket \
--bucket my-app-frontend \
--region ap-south-1 \
--create-bucket-configuration LocationConstraint=ap-south-1
# Enable static website hosting
aws s3api put-bucket-website \
--bucket my-app-frontend \
--website-configuration '{
"IndexDocument": {"Suffix": "index.html"},
"ErrorDocument": {"Key": "index.html"}
}'
# Upload build output
aws s3 sync ./dist/my-app s3://my-app-frontend \
--delete \
--cache-control "public, max-age=31536000, immutable" \
--exclude "index.html"
# index.html must NOT be cached long-term — browsers should always
# fetch the latest version to pick up new hashed asset filenames
aws s3 cp ./dist/my-app/index.html s3://my-app-frontend/index.html \
--cache-control "public, max-age=0, must-revalidate"
main.a3f9c12.js) can be cached for a year — the hash changes on every build. index.html must never be long-cached, or users will load stale HTML pointing at non-existent asset hashes after a deploy.
Step 2 — Cloudflare CDN Configuration
Add your domain to Cloudflare (free plan works for most projects) and create a CNAME record pointing to the S3 website endpoint. Then configure a Page Rule to enforce caching and HTTPS.
Cache Rules (Cloudflare Dashboard)
| Path Pattern | Cache Level | Edge TTL | Reason |
|---|---|---|---|
/*.js, /*.css, /*.woff2 |
Cache Everything | 1 year | Content-hashed — safe to cache forever |
/images/* |
Cache Everything | 30 days | Versioned filenames |
/index.html |
Bypass | — | Always serve fresh from origin |
/api/* |
Bypass | — | Dynamic API responses |
Cloudflare Worker — API Proxy with Auth Injection
A Cloudflare Worker lets you intercept and transform requests at the edge before they reach Lambda. A common use case: injecting an internal service token so Lambda doesn't need to validate the public JWT itself.
// cloudflare-worker.js (deployed via Wrangler)
export default {
async fetch(request, env) {
const url = new URL(request.url);
// Only proxy /api/* to Lambda via API Gateway
if (!url.pathname.startsWith('/api/')) {
return fetch(request); // pass through to S3
}
// Forward to API Gateway with internal service key
const apiUrl = `${env.API_GATEWAY_URL}${url.pathname}${url.search}`;
const proxyRequest = new Request(apiUrl, {
method: request.method,
headers: {
...Object.fromEntries(request.headers),
'x-internal-key': env.INTERNAL_SERVICE_KEY,
'x-forwarded-for': request.headers.get('cf-connecting-ip') ?? '',
},
body: request.method !== 'GET' ? request.body : undefined,
});
const response = await fetch(proxyRequest);
// Add security headers on every response
const newHeaders = new Headers(response.headers);
newHeaders.set('X-Frame-Options', 'DENY');
newHeaders.set('X-Content-Type-Options', 'nosniff');
newHeaders.set('Referrer-Policy', 'strict-origin-when-cross-origin');
return new Response(response.body, {
status: response.status,
headers: newHeaders,
});
},
};
Step 3 — NestJS on AWS Lambda
NestJS isn't designed for Lambda out of the box — it assumes a persistent server process. The @vendia/serverless-express adapter bridges the gap, wrapping the Express-based NestJS app to handle Lambda's event-based invocation model.
Lambda Entry Point
// lambda.ts
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import serverlessExpress from '@vendia/serverless-express';
import express from 'express';
import { AppModule } from './app.module';
import { Handler } from 'aws-lambda';
let cachedHandler: Handler;
async function bootstrap(): Promise {
const expressApp = express();
const app = await NestFactory.create(AppModule, new ExpressAdapter(expressApp));
app.enableCors({ origin: process.env.ALLOWED_ORIGINS?.split(',') ?? [] });
app.setGlobalPrefix('api');
await app.init();
return serverlessExpress({ app: expressApp });
}
export const handler: Handler = async (event, context, callback) => {
// Reuse across warm invocations — do NOT re-bootstrap on every call
if (!cachedHandler) {
cachedHandler = await bootstrap();
}
return cachedHandler(event, context, callback);
};
cachedHandler pattern is critical. Lambda reuses the execution environment across warm invocations, so bootstrapping NestJS (which initialises DI, connects to DB, registers pipes and interceptors) happens only on cold start — not on every request. Without this, you would pay the full NestJS startup cost (~400ms) on every invocation.
Lambda Function Configuration
# serverless.yml (using Serverless Framework)
service: my-api
provider:
name: aws
runtime: nodejs22.x
region: ap-south-1
memorySize: 1024 # 1GB — faster cold starts than 512MB
timeout: 29 # API Gateway max is 29s
environment:
NODE_ENV: production
DB_SECRET_ARN: ${ssm:/my-app/db-secret-arn}
ALLOWED_ORIGINS: ${ssm:/my-app/allowed-origins}
functions:
api:
handler: dist/lambda.handler
events:
- httpApi:
path: /api/{proxy+}
method: ANY
vpc:
securityGroupIds:
- !Ref LambdaSecurityGroup
subnetIds:
- !Ref PrivateSubnetA
- !Ref PrivateSubnetB
plugins:
- serverless-offline
- serverless-prune-plugin
Cold Start Optimisation
Cold starts are the main complaint about Lambda. Node.js 22 on 1 GB memory typically cold-starts in 300–600ms for a NestJS app. These strategies push it below 300ms:
- Lazy-load heavy modules: Don't
importAWS SDK clients at module level — initialise them inside the function or use the@Global()provider pattern so they're only created once. - Provisioned Concurrency: For latency-critical endpoints, AWS keeps pre-warmed instances ready. Cost: ~$0.015/hr per instance — worth it for your login or checkout endpoints.
- Keep
node_moduleslean: Use Lambda Layers for large shared dependencies (AWS SDK, Prisma client) so your deployment package stays under 5MB. Smaller zips unpack faster. - ARM64 (Graviton2): Switch to
architecture: arm64inserverless.yml— 20% better price-performance, measurably faster cold starts for I/O-heavy workloads.
Step 4 — CI/CD with GitHub Actions
A single workflow handles both the frontend (S3 deploy + Cloudflare cache purge) and backend (Lambda deploy) on every push to main:
# .github/workflows/deploy.yml
name: Deploy
on:
push:
branches: [main]
jobs:
deploy-frontend:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: '22' }
- run: npm ci && npm run build
working-directory: ./frontend
- name: Sync to S3
run: |
aws s3 sync ./frontend/dist s3://${{ secrets.S3_BUCKET }} \
--delete \
--cache-control "public, max-age=31536000, immutable" \
--exclude "index.html"
aws s3 cp ./frontend/dist/index.html \
s3://${{ secrets.S3_BUCKET }}/index.html \
--cache-control "public, max-age=0, must-revalidate"
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
AWS_DEFAULT_REGION: ap-south-1
- name: Purge Cloudflare cache
run: |
curl -X POST \
"https://api.cloudflare.com/client/v4/zones/${{ secrets.CF_ZONE_ID }}/purge_cache" \
-H "Authorization: Bearer ${{ secrets.CF_API_TOKEN }}" \
-H "Content-Type: application/json" \
--data '{"files": ["https://myapp.com/index.html"]}'
deploy-backend:
runs-on: ubuntu-latest
needs: deploy-frontend
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: '22' }
- run: npm ci && npm run build
working-directory: ./backend
- name: Deploy Lambda via Serverless Framework
run: npx serverless deploy --stage production --verbose
working-directory: ./backend
env:
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
Step 5 — Environment & Secrets Management
Never store secrets in environment variables baked into the Lambda configuration — they appear in plaintext in the AWS Console. Use AWS Secrets Manager and fetch at runtime:
// secrets.service.ts
import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';
@Injectable()
export class SecretsService implements OnModuleInit {
private client = new SecretsManagerClient({ region: 'ap-south-1' });
private cache = new Map();
async onModuleInit() {
// Pre-fetch all secrets on cold start so request handlers don't block
await Promise.all([
this.get(process.env.DB_SECRET_ARN!),
this.get(process.env.JWT_SECRET_ARN!),
]);
}
async get(secretArn: string): Promise {
if (this.cache.has(secretArn)) return this.cache.get(secretArn)!;
const { SecretString } = await this.client.send(
new GetSecretValueCommand({ SecretId: secretArn })
);
this.cache.set(secretArn, SecretString!);
return SecretString!;
}
}
Performance & Cost Comparison
| Metric | Traditional EC2 (Before) | S3 + CF + Lambda (After) |
|---|---|---|
| Frontend TTFB (global avg) | 340 ms | 18 ms (Cloudflare edge) |
| API P95 latency (warm) | 120 ms | 45 ms |
| API P95 latency (cold start) | 120 ms | 480 ms |
| DDoS protection | Paid WAF ($180/mo) | Included (Cloudflare free) |
| Monthly infra cost (10M req) | $420 (2× t3.medium) | $38 (Lambda + S3 + CF) |
| Scaling to 100× traffic | Manual or ASG (minutes) | Automatic (seconds) |
| Idle cost (nights/weekends) | Full EC2 cost | $0 (pay per invocation) |
Pitfalls & Production Gotchas
- Lambda concurrency limits: Default account limit is 1 000 concurrent executions across all functions in a region. Set a reserved concurrency on each function so one runaway endpoint can't starve others:
reservedConcurrency: 200inserverless.yml. - VPC cold starts: Placing Lambda in a VPC (required for RDS access) historically added 1–10 seconds to cold starts. With the Hyperplane ENI model (Lambda has used it since 2019), this penalty is now negligible — but only if you deploy to a subnet with enough available ENIs. Ensure your VPC subnets have /24 or larger CIDR blocks.
- WebSocket limitations: API Gateway HTTP API does not support WebSockets. If your NestJS app uses Socket.IO or WebSockets, you need API Gateway WebSocket API — a different integration with its own connection management complexity. Consider AWS App Runner for persistent-connection services.
- Cloudflare and API Gateway CORS: Both can inject
Access-Control-Allow-Originheaders. If both fire, the browser sees duplicate headers and rejects the response. Configure CORS in one place only — the NestJS app is the safest single source of truth. - S3 transfer acceleration: If you have users in multiple continents uploading files directly to S3, enable S3 Transfer Acceleration. This routes uploads through Cloudflare's (or AWS's) edge PoPs before forwarding to your bucket region.
Monitoring & Observability
Three tools cover the full observability stack for this architecture at minimal cost:
- CloudWatch Logs Insights: Query Lambda logs for error rates, cold start frequency, and P99 duration. Create a CloudWatch Dashboard that surfaces these automatically.
- AWS X-Ray: Enable active tracing on your Lambda to get distributed traces across Lambda → RDS → external API calls. Invaluable for diagnosing slow requests.
- Cloudflare Analytics: Cache hit rate, threat traffic blocked, and geographic distribution — all in the Cloudflare dashboard for free, with no additional instrumentation.
// Enable X-Ray tracing in NestJS via aws-xray-sdk
import AWSXRay from 'aws-xray-sdk-core';
import { createConnection } from 'typeorm';
// Wrap TypeORM's underlying pg/mysql2 driver
AWSXRay.captureHTTPsGlobal(require('http'));
AWSXRay.captureHTTPsGlobal(require('https'));
// In your Lambda handler
export const handler: Handler = async (event, context, callback) => {
AWSXRay.setContextMissingStrategy('IGNORE_ERROR');
if (!cachedHandler) {
cachedHandler = await bootstrap();
}
return cachedHandler(event, context, callback);
};
Conclusion
The S3 + Cloudflare + Lambda stack is not just a cost optimisation — it is a fundamentally different operational model. You eliminate patching, capacity planning, and load balancer management. Cloudflare handles global distribution and security. Lambda scales to zero and to millions of requests with identical configuration.
The tradeoffs are real: cold starts affect latency-sensitive flows, persistent connections (WebSockets, long polling) require workarounds, and debugging distributed serverless systems demands more tooling investment upfront. For most web APIs and content-driven frontends, the benefits vastly outweigh these costs.
If you are evaluating this architecture for your team or have a specific workload to discuss, book a free 30-minute architecture review.