Building a Real-World AI Agent on AWS · Part 3: Deploying the Agent on ECS Fargate with CI/CD and a Public Web Demo

Part 3 runs the agent as two ECS Fargate services behind API Gateway and Cognito, scales them to zero when idle, deploys with GitHub Actions and OIDC, and serves a public web demo on CloudFront for zero dollars a month.

November 24, 2026  ·  20 min read
Building a Real-World AI Agent on AWS  |  NovaNutri  |  Part 3 of 4
ECS Fargate API Gateway Cognito Docker GitHub Actions OIDC CloudFront WAF

Part 3  ·  One Image, Zero Tasks When Idle, No Keys in CI


Chapter 1

Running the Agent on ECS Fargate with API Gateway and Cognito

What you will build

Owner's browser --(Cognito sign-in, JWT)--> API Gateway HTTP API (throttled)
      --VPC Link--> Cloud Map --> ECS Fargate: api (FastAPI, LangGraph, vision model)
                                     --MCP :8765--> ECS Fargate: mcp (NovaNutri MCP server)
Both tasks: own IAM role, IAM token sign-in to Aurora, Bedrock models and Guardrail, Knowledge Base
Cost guard: services start at 0 tasks; a Lambda scales them to 0 after 60 idle minutes
The service on ECS Fargate behind API Gateway and Cognito.
Figure 1. The service on ECS Fargate behind API Gateway and Cognito.

Price first, then design

Decision Price used Why
API Gateway HTTP API with a VPC Link to Cloud Map, no load balancer $1.00 per million requests A load balancer costs about $0.0225 an hour even when idle
Public subnets with public IPs, no NAT gateway $0 A NAT gateway costs about $0.045 an hour
Fargate only while a demo runs about $0.064 an hour for both tasks 1 vCPU and 2 GB, plus 0.25 vCPU and 1 GB
Cognito for the owner only free tier Visitors see recorded results; only the owner calls paid models

One image, two commands

The API and the MCP server share one image. The default command starts the API; the MCP service overrides it with python -m novanutri.mcp_server --http.

FROM python:3.12.10-slim-bookworm
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1 HF_HOME=/opt/hf PYTHONPATH=/app/src
WORKDIR /app
COPY requirements.txt docker/requirements-serve.txt ./
ARG TORCH_INDEX=https://download.pytorch.org/whl/cpu
RUN pip install torch numpy -c requirements.txt --extra-index-url $TORCH_INDEX
RUN pip install -r requirements-serve.txt -c requirements.txt --extra-index-url $TORCH_INDEX
# Bake model weights in at pinned revisions, then forbid downloads at run time
RUN python -c "from transformers import AutoModel; AutoModel.from_pretrained('facebook/dinov2-small', revision='<commit>')"
ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
COPY src/ src/
COPY build/artifacts/ data/          # model files, checked against a SHA-256 manifest
RUN useradd --uid 10001 --no-create-home app
VOLUME ["/tmp"]                      # keeps /tmp writable (mode 1777) on a read-only root file system
USER app
EXPOSE 8000 8765
CMD ["python", "-m", "uvicorn", "novanutri.main:app", "--app-dir", "src", "--host", "0.0.0.0", "--port", "8000"]

Test it with docker compose on your VM first: health, the five MCP tools over HTTP, and one analyze and confirm. That test found a real bug: with a read-only file system, writing the MCP call log failed and made the tool fail. Logs now go to standard output in containers (CloudWatch picks them up), and a failed log write never fails a tool.

Task roles instead of keys

Task Allowed
api InvokeModel on the two models, ApplyGuardrail, rds-db:connect as novanutri_service
mcp Retrieve on the Knowledge Base, the embedding model, rds-db:connect as mcp_reader (read only)

Both sign in to Aurora with 15-minute IAM tokens. The IAM user the MCP server used during the agent build is deleted: no long-lived key remains anywhere.

Network rules: the API accepts traffic only from the VPC Link's security group, the MCP server only from the API, and Aurora only from the two tasks. The MCP server is found by name in a Cloud Map private namespace.

Hardened tasks and safe deployments

  • Non-root user, readonlyRootFilesystem = true, a /tmp volume.
  • Circuit breaker with rollback on both services.
  • The API keeps meals in memory, so it runs one task and deploys stop-then-start (deployment_minimum_healthy_percent = 0, deployment_maximum_percent = 100).
  • Logs kept 3 days.
The api and mcp services in the ECS cluster.
Figure 2. The api and mcp services in the ECS cluster.

API Gateway with a JWT authorizer

resource "aws_apigatewayv2_authorizer" "cognito" {
  authorizer_type  = "JWT"
  identity_sources = ["$request.header.Authorization"]
  jwt_configuration {
    issuer   = "https://cognito-idp.${var.region}.amazonaws.com/${aws_cognito_user_pool.owner.id}"
    audience = [aws_cognito_user_pool_client.web.id]
  }
}
# Routes: GET /api/health (public), ANY /api/{proxy+} (JWT), OPTIONS /api/{proxy+} (no auth, for CORS preflight)
# Stage throttling: burst 10, rate 5 per second

The OPTIONS route matters for browsers; see the CI/CD and web demo chapter below.

The JWT authorizer on the HTTP API.
Figure 3. The JWT authorizer on the HTTP API.

Asynchronous recommend for the 30-second limit

An HTTP API waits at most 30 seconds, and two models with tools take 30 seconds to 2 minutes. With the header Prefer: respond-async, POST /api/meals/{id}/recommend answers 202 at once and runs in a background thread; the client polls GET /api/meals/{id}/recommendation (202 running, 200 done). Without the header the call stays synchronous, so notebooks and tests did not change. In the live test the answer took 33 seconds: the synchronous path would have failed.

A cost guard Lambda

def handler(event, context):
    now = datetime.now(timezone.utc)
    idle = timedelta(minutes=int(os.environ["IDLE_MINUTES"]))
    count = requests_since(now - idle, now)          # API Gateway Count metric from CloudWatch
    for s in ecs.describe_services(cluster=CLUSTER, services=SERVICES)["services"]:
        started = max((d["createdAt"] for d in s["deployments"]), default=now - idle)
        if s["desiredCount"] > 0 and count == 0 and now - started >= idle:
            ecs.update_service(cluster=CLUSTER, service=s["serviceName"], desiredCount=0)

It runs every 30 minutes from EventBridge. It only lowers counts; starting is a person's decision (scale.sh 1). A fresh start is never stopped before anyone could use it.

Moving the dataset into Aurora

The MCP tool reference_dishes read the cleaned dataset on the VM. For the cloud, copy it into Aurora in one transaction over verified TLS, and require row counts and a checksum to match before committing. Then the containers never reach back to the VM.

When the home network cannot upload

Pushing the 670 MB image from home failed every time: large uploads were reset (a 300 MB single S3 upload failed too). Do not fight it: build the image in GitHub Actions (next chapter). Two more fixes on the way:

  • GitHub now puts owner and repository IDs into the OIDC token subject. The trust policy must accept that form; CloudTrail showed the refused subject.
  • Write manifests with LF line endings so Windows, git and S3 produce the same hash.

The live test

Call Result
Any /api route without a token 401 from the JWT authorizer
GET /api/health 200: database, vision model, tables and Bedrock credentials ok
POST analyze (a demo photo) 200 in 1.6 s
POST recommend with Prefer: respond-async 202 in 0.2 s; poll returned 200 after 33 s
Models and tools both models answered; MCP tools on ECS used 6 times
Cost $0.0160
MCP tool calls in the mcp service's CloudWatch log.
Figure 4. MCP tool calls in the mcp service's CloudWatch log.

Lessons

  • Pay per request at the entry; start services at zero; stop them automatically.
  • One image with two commands keeps the API and the tool server in step.
  • Use task roles and IAM database tokens; delete test keys.
  • Plan for the API Gateway 30-second limit from the start.

Chapter 2

CI/CD with OIDC and a Public Web Demo on CloudFront

What you will build

GitHub Actions image.yml: OIDC sign-in -> model files from S3 (checked by manifest) -> docker build
   -> pytest inside the built image -> push to ECR (immutable tag) -> new task definition revisions -> deploy mcp, then api
   -> wait stable -> confirm the running revision is the new one
GitHub Actions web.yml: demo bundle from S3 (checked) -> build -> S3 sync with cache headers -> invalidate -> check live page
Web stack (kept on): private S3 + CloudFront Free plan + WAF + ACM certificate + custom domain
Live mode: Cognito sign-in with PKCE -> analyze -> confirm -> recommend (async, polling)
CI/CD with GitHub Actions and the web demo stack.
Figure 5. CI/CD with GitHub Actions and the web demo stack.

Sign in to AWS from GitHub without keys

Create an IAM OIDC provider for token.actions.githubusercontent.com and a role that trusts only your main branch:

condition {
  test     = "StringEquals"
  variable = "token.actions.githubusercontent.com:aud"
  values   = ["sts.amazonaws.com"]
}
condition {
  test     = "StringLike"
  variable = "token.actions.githubusercontent.com:sub"
  values   = [
    "repo:${var.github_repository_with_ids}:ref:refs/heads/main",   # newer subject form with owner and repo IDs
    "repo:${var.github_repository}:ref:refs/heads/main",
  ]
}

In the workflow:

permissions:
  id-token: write
  contents: read
steps:
  - uses: aws-actions/configure-aws-credentials@v5
    with:
      role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
      aws-region: us-east-2
      mask-aws-account-id: true

Two traps:

  • Do not attach a GitHub environment to the job. With an environment, the subject becomes ...:environment:<name> and a role that trusts refs/heads/main refuses it.
  • An account can hold only one OIDC provider per URL. If several Terraform stacks need it, give it to the stack that lives longest (NovaNutri moved it to the web stack and the service stack reads it with a data source).

Keep the role narrow: push only to the app repository, read only the build-artifacts prefix, deploy only these two ECS services, and pass only this stack's execution and task roles, only to ECS tasks.

Test the image you ship

- name: Tests inside the built image
  run: |
    docker run --rm --user root \
      -v "$PWD/tests:/app/tests:ro" -v "$PWD/lambda:/app/lambda:ro" "$IMAGE" \
      sh -c "pip install --quiet pytest==<pinned> && python -m pytest tests -q -p no:cacheprovider -rs" | tee pytest.txt
    tail -n 1 pytest.txt >> "$GITHUB_STEP_SUMMARY"
  • pytest is installed only in this throwaway container, never in the image.
  • Tests use fakes, so no paid model call happens in CI.
  • -rs prints the reason for every skipped test (for example one that needs a local notebook output).
  • Tag images <commit>-<manifest hash>, make ECR tags immutable, and skip build and test when the tag already exists.
Tests running inside the built image in GitHub Actions.
Figure 6. Tests running inside the built image in GitHub Actions.

Deploy and check what actually runs

for svc in mcp api; do
  aws ecs describe-task-definition --task-definition "$CLUSTER-$svc" --query taskDefinition > current.json
  jq --arg image "$IMAGE" '.containerDefinitions[0].image = $image
    | del(.taskDefinitionArn, .revision, .status, .requiresAttributes, .compatibilities, .registeredAt, .registeredBy)' \
    current.json > next.json
  arn=$(aws ecs register-task-definition --cli-input-json file://next.json --query taskDefinition.taskDefinitionArn --output text)
  aws ecs update-service --cluster "$CLUSTER" --service "$svc" --task-definition "$arn"
done
aws ecs wait services-stable --cluster "$CLUSTER" --services mcp api
# then compare each service's running task definition with the new one

Why the last check: a circuit-breaker rollback also ends "stable". Without comparing the running revision, a failed deploy looks like success. Let CI own the task definition: tell Terraform to ignore it on the services (lifecycle { ignore_changes = [desired_count, task_definition] }) so a later plan never rolls a deploy back.

Measured: a rolling deploy onto running services was stable in about 2 minutes 20 seconds.

The deploy step confirming the running task definition revisions.
Figure 7. The deploy step confirming the running task definition revisions.

Host the web demo for $0 a month

The site is a React and Vite page that replays recorded results. Hosting:

  • A private S3 bucket; CloudFront reads it with origin access control; the bucket policy names only this distribution.
  • An ACM certificate in us-east-1 with DNS validation at your registrar, and one CNAME for the subdomain.
  • CloudFront's flat-rate Free plan: $0 a month with no overage, 1 million requests, 100 GB transfer, and a WAF web ACL included (without the plan the WAF alone would cost $5 a month plus $1 per rule).
  • WAF rules: rate limit 300 requests per 5 minutes per IP, the AWS IP reputation list and the common rule set.

Trap: the Free plan refuses a custom response headers policy. Use the managed security headers policy (HSTS, nosniff, frame and referrer policies) and write the Content-Security-Policy as a meta tag during the build. When you switch policies, update the distribution first and delete the old policy second, or Terraform fails with "policy in use".

Keep the site in its own Terraform stack that reads nothing from the service stacks, so tearing those down never touches the public page.

The CloudFront distribution on the flat-rate Free plan.
Figure 8. The CloudFront distribution on the flat-rate Free plan.

Publish the page

web.yml runs on a change to the page: download the demo bundle (13 files, about 2 MB) from S3 and check each against a manifest in git, type check and build, upload hashed assets with a one-year cache and everything else with five minutes, delete old files last, invalidate CloudFront, then fetch the live page and check status, title, the CSP tag and HSTS. Run time: under a minute.

Live mode for the owner

  • Built only while three repository variables are set (API URL, Cognito domain, client id); without them the page has no live code and its CSP allows only its own origin.
  • Sign-in: Cognito hosted page, authorization code with PKCE and a state value. Keep only the access token, in the tab's session storage. Never read the email, so no screenshot shows it.
  • A run: analyze, confirm, then recommend with Prefer: respond-async and poll every 5 seconds for up to 4 minutes. An uploaded photo is cropped to 4:3 and scaled to 640 x 480 in the browser before upload.

The CORS lesson: the browser's preflight (OPTIONS, no token) got 401 because the authorized catch-all route also caught OPTIONS. An unauthorized OPTIONS /api/{proxy+} route fixed the 401 but returned 405 from the service, so the service now answers OPTIONS with an empty 204; API Gateway adds the CORS headers.

Live runs: a sample photo in 26 s for $0.0187 with 8 MCP tool calls; an uploaded photo in 16 s for $0.0141.

A live-mode run: both models' lunch ideas side by side.
Figure 9. A live-mode run: both models' lunch ideas side by side.

Lessons

  • No keys in CI: OIDC plus a narrow role, and no environments on that job.
  • Run the tests inside the image you push.
  • After a deploy, read what is running; "stable" is not proof.
  • Give the public site its own stack and a fixed $0 plan.

Next: Part 4 runs the same services on Amazon EKS with Helm and Pod Identity, and finds a bug only Kubernetes shows.

See it running

Live demo: novanutri.novapunkai.com

Case study and 2-minute video: novapunkai.com/projects/novanutri

Building a Real-World AI Agent on AWS · NovaNutri

Part 1 Project Design and a Data Pipeline from Airflow to Iceberg
Part 2 Honest Model Evaluation and an Agent with MCP, Bedrock and a Guardrail
Part 3 Deploying the Agent on ECS Fargate with CI/CD and a Public Web Demo
Part 4 The Same Services on Amazon EKS, and a Demo Video Made by Code

NovaNutri is a portfolio technology demo, not a commercial product. Nothing it produces is medical or nutrition advice. Data: Nutrition5k (Google Research, CC BY 4.0), USDA FoodData Central (CC0), Dietary Guidelines for Americans 2025-2030.

AWS, Amazon Bedrock and other product names are trademarks of their owners. This series is independent and not endorsed by Amazon Web Services.