Polski

Tutorial · Scalable sites on AWS · AWS S3

A scalable web portal on AWS – from one server to millions of users (CloudFront, ALB, ECS Fargate, Aurora, ElastiCache, SQS, CDK)

We take the pierogi shop's portal through five stages of growth – from a single machine to an architecture for millions of users. CloudFront and S3 for static files, a stateless API on ECS Fargate behind an Application Load Balancer in three Availability Zones, Aurora with read replicas, ElastiCache (Valkey) as a cache, SQS for background work, autoscaling policies and costs. Everything as AWS CDK in TypeScript.

By · · 24 min read

Halina's pierogi shop appeared on a TV cooking show. The next day the portal with the menu and online orders, which had run happily on a single machine for two years, got as much traffic in an hour as it used to get in a month – and went down. In this tutorial we walk the road it should have walked earlier: from one server to an architecture that serves millions of users. At every stage we change only what is actually the bottleneck.

Prerequisites: an AWS account with AWS CLI v2 (aws configure sso), Node.js 22+, Docker (to build images), container and SQL basics. The S3 and SQS tutorials help – I don't repeat them here.

6
Well-Architected pillars – since 2021, including sustainability
15
read replicas in an Aurora cluster – one reader endpoint
6 copies
of Aurora data – across three Availability Zones
0.5 ACU
minimum per instance in this stack – Serverless v2 can even go down to 0
Diagram: Target architecture (stage 4) – who talks to whom

The rule: scale what hurts

The most common mistake when designing "for millions" is building stage 4 straight away for a product with a hundred users: you pay for NAT gateways, clusters and replicas, and the team maintains infrastructure instead of shipping features. The opposite mistake – no plan at all – ends the way it did for Halina. The sensible path is an architecture you can grow without rewriting the application, plus metrics that tell you when to move on.

StageScale (roughly)BottleneckWhat changes
0up to ~1k usersnothing – simplicity winsone machine: app + database
1~10kdatabase and app fight for RAM, static files load the servermanaged database (RDS Multi-AZ), S3 + CloudFront
2~100kone app server = no redundancystateless API, ALB, ECS Fargate in 3 AZs, autoscaling
3~1Mthe writer database (reads!)edge cache, ElastiCache, read replicas
410M+synchronous, slow operationsSQS and workers, RDS Proxy, later data partitioning

User counts are indicative – what matters is the traffic profile (requests per second at peak, the share of reads) and what the metrics say. I cover metrics and costs separately in the observability tutorial.

Stage 0. One server

Diagram: Stage 0: everything on one machine

To start with, a single EC2 (or Lightsail) instance with the app, the database and the files is fine – it costs a dozen or so dollars a month and is easy to understand. But even here it pays to follow three rules that make every later step easier: configuration from environment variables, not from files on the server (Twelve-Factor App); automatic database backups stored off the machine; infrastructure described as code (CDK, Terraform), not clicked together.

Stage 1. A separate database and static files at the edge

Diagram: Stage 1: managed database and a CDN

The first two changes give the most for the least. The database moves to Amazon RDS in Multi-AZ mode – AWS handles backups, patching and automatic failover to a standby instance in another Availability Zone when the primary fails. Static files (the built frontend, dish photos) go to S3 behind CloudFront – the API server stops wasting threads on serving JavaScript, and users get files from the nearest point of presence (PoP). How to configure the bucket securely is covered in S3 bucket security.

Stage 2. A stateless API behind a load balancer in three zones

Diagram: Stage 2: many API copies in three Availability Zones

A single application machine is a single point of failure and a performance ceiling. To run many copies, the application has to be stateless: sessions in tokens or in ElastiCache (not in process memory), files in S3 (not on disk), scheduled jobs in EventBridge Scheduler or a single worker (not in every copy). Then an Application Load Balancer (ALB) spreads the traffic and ECS Fargate runs the containers without servers to manage.

Step 1. Network and stack skeleton

mkdir pierogi-portal && cd pierogi-portal
npx aws-cdk@2 init app --language typescript

CDK app, stack and network

infra/bin/app.ts
import { App, Tags } from 'aws-cdk-lib';
import { PortalStack } from '../lib/portal-stack.js';

const app = new App();
new PortalStack(app, 'pierogi-portal-prod', {
  env: { account: process.env.CDK_DEFAULT_ACCOUNT, region: 'eu-central-1' },
  domainName: 'pierogarnia.example',
});
// Tags flow to every resource that supports them – the basis of cost allocation.
Tags.of(app).add('project', 'pierogi-portal');
Tags.of(app).add('env', 'prod');
infra/lib/portal-stack.ts
import { Construct } from 'constructs';
import { CfnOutput, Stack, type StackProps } from 'aws-cdk-lib';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import { Network } from './network.js';
import { Data } from './data.js';
import { Compute } from './compute.js';
import { Edge } from './edge.js';
import { AsyncWork } from './async.js';

export interface PortalStackProps extends StackProps {
  domainName: string;
}

export class PortalStack extends Stack {
  constructor(scope: Construct, id: string, props: PortalStackProps) {
    super(scope, id, props);
    const { vpc } = new Network(this, 'Network');
    const cluster = new ecs.Cluster(this, 'Cluster', {
      vpc,
      containerInsightsV2: ecs.ContainerInsights.ENHANCED,
      enableFargateCapacityProviders: true,
    });
    const data = new Data(this, 'Data', { vpc });
    const compute = new Compute(this, 'Compute', { vpc, cluster, data });
    const jobs = new AsyncWork(this, 'Async', { cluster });
    jobs.queue.grantSendMessages(compute.api.taskDefinition.taskRole);
    compute.api.taskDefinition.defaultContainer?.addEnvironment('JOBS_QUEUE_URL', jobs.queue.queueUrl);
    const edge = new Edge(this, 'Edge', { alb: compute.api.loadBalancer });

    new CfnOutput(this, 'CdnDomain', { value: edge.distribution.distributionDomainName });
  }
}
infra/lib/network.ts
import { Construct } from 'constructs';
import * as ec2 from 'aws-cdk-lib/aws-ec2';

export class Network extends Construct {
  readonly vpc: ec2.Vpc;

  constructor(scope: Construct, id: string) {
    super(scope, id);
    this.vpc = new ec2.Vpc(this, 'Vpc', {
      ipAddresses: ec2.IpAddresses.cidr('10.20.0.0/16'),
      maxAzs: 3, // three Availability Zones: losing one leaves two thirds of capacity
      natGateways: 2, // one per AZ is the most resilient; 2 is a cost compromise
      subnetConfiguration: [
        { name: 'public', subnetType: ec2.SubnetType.PUBLIC, cidrMask: 24 },
        { name: 'app', subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS, cidrMask: 22 },
        { name: 'data', subnetType: ec2.SubnetType.PRIVATE_ISOLATED, cidrMask: 24 },
      ],
    });
    // S3 traffic from private subnets skips the NAT gateway (and its per-GB fee).
    this.vpc.addGatewayEndpoint('S3', { service: ec2.GatewayVpcEndpointAwsService.S3 });
  }
}

The VPC has three kinds of subnets: public (NAT gateways only), private with egress (API containers) and isolated (database and cache – no route to the internet at all). Three Availability Zones mean that losing one takes away a third of your capacity, not half. The S3 gateway endpoint is free and routes S3 traffic from private subnets around the NAT gateway – and its per-gigabyte fee.

Step 2. The API on Fargate with autoscaling

Fargate service, health checks and graceful shutdown

infra/lib/compute.ts
import { Construct } from 'constructs';
import { Duration } from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as patterns from 'aws-cdk-lib/aws-ecs-patterns';
import type { Data } from './data.js';

export class Compute extends Construct {
  readonly api: patterns.ApplicationLoadBalancedFargateService;

  constructor(scope: Construct, id: string, props: { vpc: ec2.IVpc; cluster: ecs.ICluster; data: Data }) {
    super(scope, id);
    const { db, cacheSg, cacheEndpoint } = props.data;

    this.api = new patterns.ApplicationLoadBalancedFargateService(this, 'Api', {
      cluster: props.cluster,
      publicLoadBalancer: false, // internal ALB, reachable only through the CloudFront VPC origin
      openListener: false, // no 0.0.0.0/0 rule – Edge allows CloudFront only
      desiredCount: 3,
      cpu: 512,
      memoryLimitMiB: 1024,
      runtimePlatform: { cpuArchitecture: ecs.CpuArchitecture.ARM64, operatingSystemFamily: ecs.OperatingSystemFamily.LINUX },
      circuitBreaker: { rollback: true }, // a failing deployment rolls back on its own
      taskImageOptions: {
        image: ecs.ContainerImage.fromAsset('../app'),
        containerPort: 3000,
        environment: {
          DB_WRITER_HOST: db.clusterEndpoint.hostname,
          DB_READER_HOST: db.clusterReadEndpoint.hostname,
          CACHE_HOST: cacheEndpoint,
        },
        secrets: { DB_PASSWORD: ecs.Secret.fromSecretsManager(db.secret!, 'password') },
      },
    });
    this.api.targetGroup.configureHealthCheck({ path: '/health/ready', interval: Duration.seconds(15), healthyThresholdCount: 2 });
    this.api.targetGroup.setAttribute('deregistration_delay.timeout_seconds', '30');

    db.connections.allowDefaultPortFrom(this.api.service);
    cacheSg.addIngressRule(this.api.service.connections.securityGroups[0], ec2.Port.tcp(6379));

    // Horizontal autoscaling: target tracking on CPU and on requests per task.
    const scaling = this.api.service.autoScaleTaskCount({ minCapacity: 3, maxCapacity: 40 });
    scaling.scaleOnCpuUtilization('Cpu', {
      targetUtilizationPercent: 60,
      scaleOutCooldown: Duration.seconds(60),
      scaleInCooldown: Duration.minutes(5),
    });
    scaling.scaleOnRequestCount('Requests', { requestsPerTarget: 1_000, targetGroup: this.api.targetGroup });
  }
}
app/src/server.ts
import express from 'express';
import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs';
import { reader, writer } from './db.js';
import { cache, cached } from './cache.js';

const app = express();
app.use(express.json({ limit: '100kb' }));
const sqs = new SQSClient({});
let draining = false;

// Liveness: is the process alive? Readiness: should the ALB send traffic here?
// Keep both shallow – a database blip must not mark every task unhealthy at once.
app.get('/health/live', (_req, res) => { res.send('ok'); });
app.get('/health/ready', (_req, res) => { res.status(draining ? 503 : 200).send(draining ? 'draining' : 'ready'); });

app.get('/api/public/menu', async (req, res) => {
  const lang = req.query.lang === 'en' ? 'en' : 'pl';
  const menu = await cached(`menu:${lang}`, 300, async () =>
    (await reader.query('SELECT id, name, price FROM dishes WHERE lang = $1 ORDER BY position', [lang])).rows);
  // CloudFront caches it for 30 s and may serve a stale copy while it refreshes.
  res.set('Cache-Control', 'public, max-age=30, stale-while-revalidate=60').json(menu);
});

app.put('/api/admin/dishes/:id/price', async (req, res) => {
  const price = Number(req.body.price);
  if (!Number.isFinite(price) || price <= 0) { res.status(400).json({ error: 'invalid price' }); return; }
  await writer.query('UPDATE dishes SET price = $1 WHERE id = $2', [price, req.params.id]);
  // Invalidate after the commit (separate DEL calls: keys may live in different cluster slots).
  await Promise.all(['menu:pl', 'menu:en'].map((k) => cache.del(k)));
  // Slow side effects (search index, newsletter, PDF menu) go to the queue.
  await sqs.send(new SendMessageCommand({
    QueueUrl: process.env.JOBS_QUEUE_URL,
    MessageBody: JSON.stringify({ type: 'dish.price-changed', dishId: req.params.id, price }),
  }));
  res.status(204).end();
});

const server = app.listen(3000);

// Before SIGTERM, ECS deregisters the task from the target group and waits for the
// deregistration delay. Now: finish in-flight requests, close pools, exit before
// stopTimeout (30 s by default) ends in SIGKILL.
process.on('SIGTERM', () => {
  draining = true;
  server.close(async () => {
    await Promise.allSettled([writer.end(), reader.end(), cache.quit()]);
    process.exit(0);
  });
  setTimeout(() => process.exit(1), 25_000).unref();
});
  • At least 3 tasks in 3 zones. With two tasks, a zone failure leaves one that suddenly has to take all the traffic. This is static stability: the spare capacity is already there, instead of hoping autoscaling kicks in during the outage.
  • ARM64 (Graviton) usually gives better price-performance than x86 – the image must be built for linux/arm64.
  • circuitBreaker: { rollback: true } – a deployment whose new tasks fail health checks rolls back to the previous version on its own.
  • Shallow health checks. If /health/ready checks the database, a brief Aurora hiccup marks every task unhealthy at once. The ALB then routes to all targets anyway (fail open), but ECS starts replacing them – which deepens the outage. Deep dependency checks belong in alarms, not in the health check.
  • SIGTERM is not the end of the world. Before sending it, ECS deregisters the task from the target group and waits deregistration_delay – the app finishes in-flight requests, closes connection pools and exits before SIGKILL.

Stage 3. Cache layers and read replicas

At a million users a typical portal sees 90–95% reads: the menu, opening hours, reviews. Every one of those requests that reaches the writer database is waste. We add three layers, starting closest to the user:

LayerWhat it holdsTTLInvalidation
CloudFront (edge)public API responses, the SPAseconds–minutes for the API, a year for hashed filesnew file names, short TTL; invalidation only in emergencies
ElastiCache (Valkey)query results, sessions, countersminutesDEL after a write (cache-aside)
Aurora replicasfull data, with replication lag–– (usually < 100 ms of lag)

Step 3. CloudFront in front of S3 and the API

CloudFront distribution with OAC and a VPC origin

infra/lib/edge.ts
import { Construct } from 'constructs';
import { Duration, RemovalPolicy } from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as s3 from 'aws-cdk-lib/aws-s3';
import * as cloudfront from 'aws-cdk-lib/aws-cloudfront';
import * as origins from 'aws-cdk-lib/aws-cloudfront-origins';
import type * as elbv2 from 'aws-cdk-lib/aws-elasticloadbalancingv2';

export class Edge extends Construct {
  readonly distribution: cloudfront.Distribution;

  constructor(scope: Construct, id: string, props: { alb: elbv2.IApplicationLoadBalancer }) {
    super(scope, id);
    // The SPA build (index.html, hashed JS/CSS) – private bucket, read only by CloudFront.
    const site = new s3.Bucket(this, 'Site', {
      blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
      enforceSSL: true,
      encryption: s3.BucketEncryption.S3_MANAGED,
      removalPolicy: RemovalPolicy.RETAIN,
    });

    // Short-lived edge cache for public API reads (menu, opening hours).
    const apiCache = new cloudfront.CachePolicy(this, 'ApiCache', {
      defaultTtl: Duration.seconds(30),
      minTtl: Duration.seconds(0),
      maxTtl: Duration.minutes(5),
      queryStringBehavior: cloudfront.CacheQueryStringBehavior.allowList('lang', 'page'),
      enableAcceptEncodingGzip: true,
      enableAcceptEncodingBrotli: true,
    });
    // Only CloudFront's origin-facing IP ranges may reach the internal ALB.
    const cloudFrontRanges = ec2.PrefixList.fromLookup(this, 'CfOriginFacing', {
      prefixListName: 'com.amazonaws.global.cloudfront.origin-facing',
    });
    props.alb.connections.allowFrom(cloudFrontRanges, ec2.Port.HTTP);
    const api = origins.VpcOrigin.withApplicationLoadBalancer(props.alb, {
      httpPort: 80,
      protocolPolicy: cloudfront.OriginProtocolPolicy.HTTP_ONLY, // see the note on end-to-end TLS
    });

    const securityHeaders = cloudfront.ResponseHeadersPolicy.SECURITY_HEADERS; // HSTS, nosniff, frame options…

    this.distribution = new cloudfront.Distribution(this, 'Cdn', {
      defaultRootObject: 'index.html',
      defaultBehavior: {
        origin: origins.S3BucketOrigin.withOriginAccessControl(site),
        viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
        cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED,
        responseHeadersPolicy: securityHeaders,
      },
      additionalBehaviors: {
        '/api/public/*': {
          origin: api,
          viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.HTTPS_ONLY,
          cachePolicy: apiCache,
          originRequestPolicy: cloudfront.OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER,
          responseHeadersPolicy: securityHeaders,
        },
        '/api/*': {
          origin: api,
          viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.HTTPS_ONLY,
          allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL,
          cachePolicy: cloudfront.CachePolicy.CACHING_DISABLED,
          originRequestPolicy: cloudfront.OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER,
          responseHeadersPolicy: securityHeaders,
        },
      },
      // SPA routing: unknown paths return index.html.
      errorResponses: [{ httpStatus: 403, responseHttpStatus: 200, responsePagePath: '/index.html', ttl: Duration.seconds(10) }],
    });
  }
}

Two things worth knowing. A VPC origin (since November 2024) lets CloudFront connect to an ALB in a private subnet – the load balancer has no public address, so nobody can bypass CloudFront (and its WAF rules) by attacking the ALB directly. On top of that, the ALB's security group admits only the ranges from CloudFront's managed prefix list. The /api/public/* path has a short cache policy (30 s by default, honouring the app's Cache-Control), while the rest of /api/* gets no caching and forwards headers, cookies and query strings. At 1,000 menu requests per second with a 30 s TTL, each point of presence sends roughly one request per 30 seconds per response variant to the application.

Step 4. Aurora with a replica and ElastiCache

Aurora Serverless v2, ElastiCache Serverless and data access code

infra/lib/data.ts
import { Construct } from 'constructs';
import { Duration, RemovalPolicy } from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as rds from 'aws-cdk-lib/aws-rds';
import * as elasticache from 'aws-cdk-lib/aws-elasticache';

export class Data extends Construct {
  readonly db: rds.DatabaseCluster;
  readonly cacheSg: ec2.SecurityGroup;
  readonly cacheEndpoint: string;

  constructor(scope: Construct, id: string, props: { vpc: ec2.IVpc }) {
    super(scope, id);
    const subnets = { subnetType: ec2.SubnetType.PRIVATE_ISOLATED };

    // Aurora PostgreSQL: a writer and a reader in different AZs, both Serverless v2.
    this.db = new rds.DatabaseCluster(this, 'Db', {
      engine: rds.DatabaseClusterEngine.auroraPostgres({ version: rds.AuroraPostgresEngineVersion.VER_17_9 }),
      vpc: props.vpc,
      vpcSubnets: subnets,
      credentials: rds.Credentials.fromGeneratedSecret('portal'), // password lives in Secrets Manager
      defaultDatabaseName: 'portal',
      writer: rds.ClusterInstance.serverlessV2('writer'),
      readers: [rds.ClusterInstance.serverlessV2('reader1', { scaleWithWriter: true })],
      serverlessV2MinCapacity: 0.5,
      serverlessV2MaxCapacity: 32,
      storageEncrypted: true,
      backup: { retention: Duration.days(14) },
      deletionProtection: true,
      removalPolicy: RemovalPolicy.SNAPSHOT,
    });

    // ElastiCache Serverless (Valkey): no nodes to size, data replicated across AZs.
    this.cacheSg = new ec2.SecurityGroup(this, 'CacheSg', { vpc: props.vpc, allowAllOutbound: false });
    const cache = new elasticache.CfnServerlessCache(this, 'Cache', {
      engine: 'valkey',
      majorEngineVersion: '8',
      serverlessCacheName: 'pierogi-portal',
      subnetIds: props.vpc.selectSubnets(subnets).subnetIds,
      securityGroupIds: [this.cacheSg.securityGroupId],
      cacheUsageLimits: {
        dataStorage: { maximum: 10, unit: 'GB' },
        ecpuPerSecond: { maximum: 50_000 },
      },
    });
    this.cacheEndpoint = cache.attrEndpointAddress;
  }
}
app/src/db.ts
import { readFileSync } from 'node:fs';
import pg from 'pg';

// Aurora presents certificates from the Amazon RDS CA – bundle it in the image
// (https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem).
const base: pg.PoolConfig = {
  database: 'portal',
  user: 'portal',
  password: process.env.DB_PASSWORD,
  ssl: { ca: readFileSync('/app/certs/rds-global-bundle.pem', 'utf8') },
  max: 10, // 40 tasks × 10 × 2 pools = 800 connections – watch max_connections
  idleTimeoutMillis: 30_000,
  connectionTimeoutMillis: 2_000,
};

// Writes and reads that must see them go to the cluster (writer) endpoint...
export const writer = new pg.Pool({ ...base, host: process.env.DB_WRITER_HOST });
// ...everything else to the reader endpoint, which balances across replicas.
export const reader = new pg.Pool({ ...base, host: process.env.DB_READER_HOST });
app/src/cache.ts
import { Cluster } from 'iovalkey';

// ElastiCache Serverless speaks cluster mode and requires TLS.
export const cache = new Cluster([{ host: process.env.CACHE_HOST!, port: 6379 }], {
  dnsLookup: (address, callback) => callback(null, address),
  redisOptions: { tls: {} },
});

const inflight = new Map<string, Promise<unknown>>();

/** Cache-aside: try the cache, otherwise load from the database and store with a TTL. */
export async function cached<T>(key: string, ttlSeconds: number, load: () => Promise<T>): Promise<T> {
  const hit = await cache.get(key).catch(() => null); // cache down ≠ site down
  if (hit) return JSON.parse(hit) as T;

  // One load per key per task, even if 500 requests miss at the same moment.
  const pending = inflight.get(key) as Promise<T> | undefined;
  if (pending) return pending;
  const promise = (async () => {
    const value = await load();
    const ttl = Math.round(ttlSeconds * (0.9 + Math.random() * 0.2)); // jitter: no synchronized expiry
    await cache.set(key, JSON.stringify(value), 'EX', ttl).catch(() => undefined);
    return value;
  })().finally(() => inflight.delete(key));
  inflight.set(key, promise);
  return promise;
}
Diagram: Cache-aside: reading the menu and invalidating after a price change
  • The reader endpoint balances connections, not queries. It is a DNS record that rotates through the replicas – a connection pool opened in one moment may land on a single replica. With many API tasks it evens out statistically.
  • Read your own writes from the writer. A replica lags (usually under 100 ms). Read the "order placed" screen after an INSERT from the writer pool; the catalogue and menu from reader.
  • Watch the connections. 40 tasks × 2 pools × 10 connections = 800 connections. When autoscaling starts adding tasks, the database may run out of connections before it runs out of CPU. RDS Proxy helps here by sharing connections between clients.
  • The cache must not take the site down. A Valkey error in cached() means a database read, not a 500. inflight turns 500 simultaneous misses in one task into a single query (protection against a cache stampede), and a random ±10% TTL spreads key expiry.

Stage 4. Background work through a queue

Diagram: Stage 4: respond right away, do the rest in the background

Generating the PDF menu, sending a newsletter after a price change, recomputing recommendations – none of this has to happen before the user gets a response. The API drops a message into SQS and answers in milliseconds, and workers process the queue at their own pace. The details – idempotency, DLQs, message visibility – are in the SQS tutorial.

A queue and workers scaled by queue depth

infra/lib/async.ts
import { Construct } from 'constructs';
import { Duration } from 'aws-cdk-lib';
import * as ecs from 'aws-cdk-lib/aws-ecs';
import * as sqs from 'aws-cdk-lib/aws-sqs';
import * as patterns from 'aws-cdk-lib/aws-ecs-patterns';

export class AsyncWork extends Construct {
  readonly queue: sqs.Queue;

  constructor(scope: Construct, id: string, props: { cluster: ecs.ICluster }) {
    super(scope, id);
    const dlq = new sqs.Queue(this, 'Dlq', { retentionPeriod: Duration.days(14) });
    this.queue = new sqs.Queue(this, 'Jobs', {
      visibilityTimeout: Duration.minutes(2),
      receiveMessageWaitTime: Duration.seconds(20),
      deadLetterQueue: { queue: dlq, maxReceiveCount: 5 },
      encryption: sqs.QueueEncryption.SQS_MANAGED,
    });

    // Workers scale on queue depth, independently of the web tier.
    new patterns.QueueProcessingFargateService(this, 'Worker', {
      cluster: props.cluster,
      queue: this.queue,
      image: ecs.ContainerImage.fromAsset('../app', { file: 'Dockerfile.worker' }),
      cpu: 512,
      memoryLimitMiB: 1024,
      minScalingCapacity: 0,
      maxScalingCapacity: 20,
      scalingSteps: [
        { upper: 0, change: -1 },
        { lower: 100, change: +2 },
        { lower: 1_000, change: +5 },
      ],
      capacityProviderStrategies: [
        { capacityProvider: 'FARGATE_SPOT', weight: 3 }, // interruptible, much cheaper
        { capacityProvider: 'FARGATE', weight: 1 },
      ],
    });
  }
}

QueueProcessingFargateService scales workers in steps based on ApproximateNumberOfMessagesVisible: an empty queue scales in (down to zero), more than 100 messages adds 2 tasks, more than 1,000 adds 5. The workers run mostly on Fargate Spot (up to 70% cheaper, but AWS can reclaim a task with a two-minute warning) – with idempotent processing an interrupted message simply returns to the queue.

Autoscaling policies

Autoscaling over a day (illustrative data) – The number of API tasks follows traffic with a lag of minutes; the minimum of 3 tasks stays even at night.
Traffic (k requests/min)Fargate tasks
0043
0223
0423
0654
08118
101410
122418
141713
161511
183023
202620
22108
PolicyHow it worksWhen
Target trackingkeeps a metric near a target (e.g. CPU 60%, 1,000 requests per task)the default choice for an API
Step scalingspecific steps for alarm thresholdsqueues, unusual metrics
Scheduledchanges min/max at a given timeknown peaks: Friday 5 p.m., a TV campaign
Predictive (EC2 ASG)forecasts from history, scales ahead of timea repeating daily pattern on EC2

Make scale-out fast (short cooldown) and scale-in cautious (5 minutes or more): a brief dip in traffic should not kill tasks you will need again a minute later. Before a known peak (a TV appearance!), raise the minimum with a scheduled action – autoscaling reacts to metrics, so it is always a few minutes behind the traffic.

Costs: what grows with traffic

Monthly infrastructure cost at each stage (illustrative data) – Order-of-magnitude estimate for eu-central-1, on-demand prices without discounts or the free tier. Price your own variant in the AWS Pricing Calculator.
ComputeDatabaseCacheCDN and transferALB, NAT, IPv4
Stage 0 (~1k)15 USD/month0 USD/month0 USD/month1 USD/month0 USD/month
Stage 1 (~10k)30 USD/month30 USD/month0 USD/month5 USD/month0 USD/month
Stage 2 (~100k)110 USD/month140 USD/month0 USD/month40 USD/month90 USD/month
Stage 3 (~1M)450 USD/month650 USD/month120 USD/month300 USD/month160 USD/month
Stage 4 (10M+)2200 USD/month2400 USD/month600 USD/month1800 USD/month500 USD/month

Cost grows more slowly than traffic – the cost per thousand users falls from stage to stage – but some items catch people out:

  • NAT Gateway – an hourly fee per gateway plus a fee for every gigabyte processed. Pulling images from ECR and calling AWS services from private subnets through NAT can cost more than the containers themselves. VPC endpoints (the S3 gateway endpoint is free; interface endpoints for ECR, Secrets Manager and CloudWatch Logs are billed hourly) usually pay for themselves.
  • Public IPv4 addresses have been billed since 2024 – including those on NAT gateways and load balancers.
  • Data transfer to the internet – CloudFront has a free tier and lower rates than transfer straight from an ALB or S3. Since November 2025 there are also flat monthly plans (Free, Pro, Business, Premium) covering the CDN, WAF and DDoS protection – handy for predictable traffic.
  • Commitment discounts: Compute Savings Plans cover Fargate, Lambda and EC2, and since December 2025 Database Savings Plans cover Aurora, RDS, DynamoDB and ElastiCache, among others. Buy them for your stable baseline, not for peaks.

Well-Architected: checking the architecture

The AWS Well-Architected Framework is a set of questions across six pillars. Here is how our stack does:

PillarWhat we didWhat's next
Operational excellenceIaC (CDK), automatic deployment rollbackrunbooks, game days, alarms (separate tutorial)
Securityprivate subnets, ALB without a public IP, secrets in Secrets Manager, encryptionWAF on CloudFront, least-privilege IAM
Reliability3 AZs, min. 3 tasks, Aurora with a replica, DLQbackup restore tests, AZ failure drills
Performance efficiencycaching at three levels, Graviton, scaling on requestsload tests before campaigns
Cost optimizationServerless v2, Fargate Spot for workers, S3 endpointSavings Plans, cost tags, budgets
SustainabilityGraviton, scaling to zero where possiblelog and data retention, smaller images

Deploy and verify

npx cdk bootstrap            # once per account and region
npx cdk diff                 # what will change – always before a deploy
npx cdk deploy pierogi-portal-prod
curl -sI "https://$(aws cloudformation describe-stacks --stack-name pierogi-portal-prod \
  --query "Stacks[0].Outputs[?OutputKey=='CdnDomain'].OutputValue" --output text)/api/public/menu?lang=pl"
Second menu request – a response from the CloudFront cache (example)
HTTP/2 200
content-type: application/json; charset=utf-8
cache-control: public, max-age=30, stale-while-revalidate=60
age: 12
x-cache: Hit from cloudfront
via: 1.1 3f4b6f0e2a7c1d9e8b5a.cloudfront.net (CloudFront)
x-amz-cf-pop: WAW51-P2
strict-transport-security: max-age=31536000
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
referrer-policy: strict-origin-when-cross-origin

x-cache: Hit from cloudfront and age: 12 mean the response came from the Warsaw point of presence and is 12 seconds old – the application never saw it. The security headers were added by the managed SECURITY_HEADERS policy (more in Security headers and CSP).

Common mistakes

  • Autoscaling without a database connection budget – 40 tasks with large pools exhaust max_connections faster than any traffic does.
  • A cache without an invalidation plan – users see the old price for an hour. Versioned keys, short TTLs and DEL after writes.
  • One Availability Zone "because it's cheaper" – saving a few tens of dollars ends in hours of downtime when the zone fails.
  • Deep health checks – the ALB and ECS take healthy tasks out because the database had a bad second.
  • No load test before a peak – tools like k6 or Artillery against a staging environment will find the bottleneck before television does.

Containers on Fargate behind an ALB

  • no servers to patch, per-task scaling in seconds to minutes
  • the same app from 3 to hundreds of copies, with no code changes
  • mature integrations: Secrets Manager, CloudWatch, X-Ray/OpenTelemetry

When it's too much or too little

  • a higher price per vCPU than EC2 under steady, high load
  • for low traffic, App Runner, Lambda or a single machine is cheaper and simpler
  • cold start of new tasks (image pull) – minutes, not milliseconds

Test yourself

Question: After enabling autoscaling, the API starts returning "too many connections" errors although database CPU is low. What do you do first?

  • Move Aurora to a bigger instance class
  • Cap the connection pools per task and add RDS Proxy
  • Turn off autoscaling

Question: Why is the ALB internal in this stack, with CloudFront connecting through a VPC origin?

  • Because an internal ALB is cheaper
  • So nobody can bypass CloudFront and WAF by attacking the ALB directly
  • Because CloudFront does not support public ALBs
Interview question: design the backend for a portal that peaks at 50k requests per second, 95% of them reads.

A good answer starts with questions: what is the traffic profile (peaks, geography), which data may be stale and for how long, what are the availability requirements. Then the layers: a CDN for static files and public reads with a short TTL (most traffic ends at the edge), a stateless API in several zones behind a load balancer autoscaling on requests, cache-aside in Redis/Valkey with invalidation on write and stampede protection, a database with read replicas and deliberate routing of "read your own writes" to the writer, connection pooling (RDS Proxy). Writes and slow operations go asynchronously through a queue with idempotent workers. Plus: static stability (headroom for losing a zone), metrics and alarms on p99 and errors, load tests, a cost estimate. The candidate who brings up data partitioning or multi-region only when the requirements justify it – not "because Netflix does" – does best.

What's next