Skip to content

Lesson 28 of 30Putting it together

Deploying a Full-Stack App

Put it all together, a React or Next.js frontend, FastAPI on Fargate, private Postgres, secrets, CDK and keyless CI/CD.

18 min read0/3 questions

Every lesson in this track was one piece. This one assembles them into the architecture you will see at a large share of companies running on AWS, and the one you should be able to draw from memory in an interview: a frontend on the edge, a containerized API in private subnets, a managed database, secrets that never touch git, infrastructure as code, and a pipeline that deploys without a single long-lived key.

The architecture

A full-stack app on AWS
VPC (2 AZs)PublicPrivate appPrivate DBCI/CDUserUserRoute 53: example.comRoute 53example.comCloudFront: /* and /api/*CloudFront/* and /api/*S3 site bucket: private, OACS3 site bucketprivate, OACALB: HTTPSALBHTTPSNAT gatewayNAT gatewayFastAPI task: Fargate, AZ aFastAPI taskFargate, AZ aFastAPI task: Fargate, AZ bFastAPI taskFargate, AZ bRDS Postgres: primaryRDS PostgresprimaryStandby: Multi-AZStandbyMulti-AZCloudWatch: logs, alarmsCloudWatchlogs, alarmsSecrets Manager: db credsSecrets Managerdb credsECR: api:shaECRapi:shaGitHub Actions: on push to mainGitHub Actionson push to mainDeploy role: OIDC trustDeploy roleOIDC trustCloudFormation: cdk deployCloudFormationcdk deployDNSHTTPSOAC/api/*:8000:5432secretOIDCdeploypushsync

The browser looks up example.com. A Route 53 alias record points it at the CloudFront distribution.

1/7

Each piece maps to an earlier lesson: Route 53 and CloudFront (CloudFront and Route 53), S3 with OAC (S3), the VPC tiers (VPC Networking), ALB and ACM (API Gateway and Load Balancing), ECS on Fargate (Containers on AWS), RDS Multi-AZ (Databases on AWS), IAM roles and OIDC (IAM, and CI/CD to AWS with GitHub Actions), CloudWatch (Monitoring and Logs).

The frontend: S3 and CloudFront, or Amplify

A React (Vite) app or a Next.js app built with output: "export" is just files. Upload dist/ or out/ to a private bucket and serve it through CloudFront.

  • Hashed assets (/assets/index-3f9a1c.js): Cache-Control: public, max-age=31536000, immutable.
  • index.html: short TTL or no-cache, so new deploys appear immediately.
  • A single-page app needs 403/404 → /index.html custom error responses so deep links like /orders/42 load.

If your Next.js app uses server features (Server Components fetching per request, Server Actions, middleware), it needs a server. Options: AWS Amplify Hosting, which supports Next.js SSR and gives you Git-based deploys and preview branches with almost no setup, or run next start as another container on ECS behind the same ALB.

The backend: FastAPI on Fargate (or Lambda)

The API is the Docker image you already know how to build, pushed to ECR and run as an ECS service. Run uvicorn on port 8000 and add a cheap /health endpoint for the target group.

Dockerfile
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app
USER 1000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

The alternative for low or spiky traffic is Lambda behind API Gateway, with an adapter like Mangum or the Lambda Web Adapter wrapping the same FastAPI app. You trade always-on cost for cold starts and the 15-minute limit, and you will want RDS Proxy in front of Postgres.

Database and secrets

RDS Postgres runs Multi-AZ in isolated subnets. Its credentials live in Secrets Manager with automatic rotation. ECS injects the secret as an environment variable at task start through the execution role, so FastAPI simply reads it:

app/settings.py
from pydantic_settings import BaseSettings
 
class Settings(BaseSettings):
    database_url: str          # injected by ECS from Secrets Manager
    app_env: str = "production"
 
settings = Settings()

Nothing secret lives in the repository, the image, or the CDK code. The CDK code only references the secret's ARN.

Infrastructure as code with CDK

AWS CDK lets you write the whole stack in TypeScript; cdk deploy turns it into CloudFormation. High-level L3 constructs like ApplicationLoadBalancedFargateService create a cluster, task definition, service, ALB, target group, listener and security groups in one call.

lib/app-stack.ts
import { Stack, StackProps, Duration } from "aws-cdk-lib";
import { Construct } from "constructs";
import * as ec2 from "aws-cdk-lib/aws-ec2";
import * as ecs from "aws-cdk-lib/aws-ecs";
import * as ecsPatterns from "aws-cdk-lib/aws-ecs-patterns";
import * as rds from "aws-cdk-lib/aws-rds";
 
export class AppStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);
 
    const vpc = new ec2.Vpc(this, "Vpc", { maxAzs: 2, natGateways: 1 });
 
    const db = new rds.DatabaseInstance(this, "Db", {
      engine: rds.DatabaseInstanceEngine.postgres({ version: rds.PostgresEngineVersion.VER_17 }),
      instanceType: ec2.InstanceType.of(ec2.InstanceClass.T4G, ec2.InstanceSize.SMALL),
      vpc,
      vpcSubnets: { subnetType: ec2.SubnetType.PRIVATE_ISOLATED },
      multiAz: true,
      credentials: rds.Credentials.fromGeneratedSecret("app"), // stored in Secrets Manager
    });
 
    const api = new ecsPatterns.ApplicationLoadBalancedFargateService(this, "Api", {
      vpc,
      desiredCount: 2,
      cpu: 512,
      memoryLimitMiB: 1024,
      taskImageOptions: {
        image: ecs.ContainerImage.fromAsset("../api"),
        containerPort: 8000,
        secrets: { DB_SECRET: ecs.Secret.fromSecretsManager(db.secret!) },
      },
    });
    api.targetGroup.configureHealthCheck({ path: "/health", interval: Duration.seconds(15) });
    api.service.autoScaleTaskCount({ maxCapacity: 6 }).scaleOnCpuUtilization("Cpu", { targetUtilizationPercent: 60 });
 
    db.connections.allowDefaultPortFrom(api.service); // security group rule: tasks -> 5432
  }
}

Look at the last line: allowDefaultPortFrom writes the "DB security group allows 5432 from the app's security group" rule from the VPC lesson for you. (The site bucket and CloudFront distribution would be a few more lines with s3.Bucket and cloudfront.Distribution.)

Quick check
Why define all of this in CDK instead of clicking it together in the console?
Need a nudge? A hint rules out a wrong answer.

CI/CD with GitHub Actions and OIDC

The old way was storing an IAM user's access keys as GitHub secrets. Those keys never expire, and if they leak, they work from anywhere. The modern way is OIDC federation: GitHub issues each workflow run a signed token saying "I am repo acme/shop, branch main". AWS trusts GitHub's OIDC provider, checks those claims against a role's trust policy, and hands back credentials that expire within the hour.

trust policy for the deploy role
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com" },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
          "token.actions.githubusercontent.com:sub": "repo:acme/shop:ref:refs/heads/main"
        }
      }
    }
  ]
}

The sub condition is the important part. Without it, any GitHub repository could assume your role.

Pythontrust_check.py
TRUST = { "aud": "sts.amazonaws.com", "sub": "repo:acme/shop:ref:refs/heads/main",} def can_assume(token_claims): for key, expected in TRUST.items(): if token_claims.get(key) != expected: return f"denied: {key} is {token_claims.get(key)!r}" return "allowed: temporary credentials issued" print(can_assume({"aud": "sts.amazonaws.com", "sub": "repo:acme/shop:ref:refs/heads/main"}))print(can_assume({"aud": "sts.amazonaws.com", "sub": "repo:acme/shop:ref:refs/heads/feature-x"}))print(can_assume({"aud": "sts.amazonaws.com", "sub": "repo:stranger/fork:ref:refs/heads/main"}))
Output
Press Run (⌘ Enter) to see what happens.
.github/workflows/deploy.yml
name: deploy
on:
  push:
    branches: [main]
 
permissions:
  id-token: write   # lets the job request an OIDC token
  contents: read
 
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/github-deploy
          aws-region: us-east-1
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci && npm run build
        working-directory: web
      - run: npx cdk deploy --require-approval never
        working-directory: infra
      - run: |
          aws s3 sync web/dist s3://acme-site-prod --delete
          aws cloudfront create-invalidation --distribution-id E2ABCDEF123 --paths "/index.html"

cdk deploy builds the API image from ../api, pushes it to ECR and rolls the ECS service. The frontend is synced, and only index.html is invalidated because everything else has hashed names.

Quick check
A pull request from a fork tries to run the deploy workflow. Why can it not assume the deploy role?
Need a nudge? A hint rules out a wrong answer.

A request's latency budget

Where does the time go for one API call from a user in Europe to us-east-1?

Pythonlatency_budget.py
hops_ms = { "DNS lookup (cached after first visit)": 20, "TLS + request to nearby CloudFront edge": 15, "Edge to ALB in us-east-1 over AWS backbone": 75, "ALB to Fargate task": 1, "FastAPI handler logic": 8, "Postgres query (indexed)": 4, "Response back along the same path": 90,}total = 0for hop, ms in hops_ms.items(): total += ms print(f"{hop:<44} {ms:>4} ms (running {total} ms)")
Output
Press Run (⌘ Enter) to see what happens.

The code and query are about 12 ms. Distance is most of the rest. That is why static assets are cached at the edge, and why a global audience eventually justifies a second Region with Route 53 latency routing.

Put it in order6 steps

Order this pre-launch checklist from foundations to finishing touches.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

That checklist is most of this course in six lines. The project that follows has you deploy a smaller, serverless service end to end on your own account, then tear it down.

Key terms
OIDC federation
Letting an external identity provider (like GitHub) exchange signed tokens for temporary AWS credentials via a role's trust policy.
AssumeRoleWithWebIdentity
The STS call that swaps an OIDC token for short-lived role credentials.
L3 construct
A high-level CDK pattern like ApplicationLoadBalancedFargateService that creates many resources at once.
cache behavior for /api/*
A CloudFront rule sending API paths uncached to the ALB, while everything else is served from cache.
Amplify Hosting
Managed hosting for web frontends, including Next.js SSR, with Git-based deploys.
isolated subnet
A private subnet with no route to the internet at all. Where the database lives.