09. Inventory Planning Agent — AWS Deployment#
A fast, conceptual revision guide for 09-inventory-agent-aws-deployment. Covers how a multi-container AI agent (Gradio + FastAPI + LangChain + SQLite) is architected, containerized, deployed declaratively to AWS ECS Fargate via CloudFormation, and automated end-to-end with keyless GitHub Actions CI/CD (OIDC).
System Architecture & App Separation#
Revision Notes#
Reference files: frontend/app.py, backend/api.py, backend/db_client.py, db/schema.sql, 01-understand-the-system.html
Concept#
The Inventory Planning Agent is split into two independent services — a public Gradio UI (frontend on port 7860) and a private FastAPI + LangChain API (backend on port 8000) backed by a SQLite database (inventory and sessions tables). Splitting the UI from the agent backend mirrors real production systems: the API stays hidden from the public internet, can serve multiple clients (UI, CLI, ERP webhooks), and scales or restarts independently of the frontend.
End-to-End Request Flow#
Public HTTP traffic terminates at the ALB and stateless Gradio UI, while FastAPI/LangChain reasoning and encrypted EFS SQLite persistence remain isolated behind Cloud Map private DNS.
Key Mental Models#
- The backend's four endpoints (
backend/api.py):GET /health(no API key) — Returns{"status": "ok"}for container and platform liveness checks.POST /chat(requiresX-API-Key) — Prepends optional[SKU: ...]context, invokes the LangChain agent with conversation history, logs the turn tosessions, and returns the reply. On LLM/tool failure it returns HTTP 502 with the exception details instead of an opaque 500.GET /inventory/{sku_id}(requiresX-API-Key) — Direct database read used by the UI's "Lookup SKU" panel.POST /inventory(requiresX-API-Key) — Idempotent upsert (INSERT ... ON CONFLICT(sku_id) DO UPDATE) for adding or modifying SKUs.
- Stateless backend, client-held conversation memory: The backend keeps no in-memory chat state between requests. Gradio holds the conversation
historyin the browser session and sends it on everyPOST /chatcall; the backend converts it intoHumanMessage/AIMessageobjects for the agent. This lets backend tasks restart or scale out without dropping active conversations. - Configuration via environment variables: Neither container hardcodes secrets or addresses.
BACKEND_URL,API_KEY,OPENAI_API_KEY,OPENAI_MODEL,DB_PATH, andPORTare injected at runtime — locally via.env/docker-compose.yamland on AWS via ECS task definitions + SSM Parameter Store.
Code Reference#
import os
import uuid
import requests
from dotenv import load_dotenv
import gradio as gr
load_dotenv()
# Environment-driven URL lets the same image target localhost, Docker Compose DNS, or AWS Cloud Map
BACKEND_URL = os.getenv("BACKEND_URL", "http://localhost:8000")
API_KEY = os.getenv("API_KEY", "dev-secret")
HEADERS = {"X-API-Key": API_KEY}
# One session ID per server instance groups turns in the backend audit log (good enough for local/single-user)
SESSION_ID = str(uuid.uuid4())
def chat(user_message: str, history: list, sku_id: str) -> tuple[str, list]:
"""Send message to backend and return updated history."""
# Normalize Gradio history (messages dict format or legacy tuple format) into OpenAI-style role/content dicts
backend_history = []
for msg in history:
if isinstance(msg, dict):
backend_history.append({"role": msg["role"], "content": msg["content"]})
else:
# Fallback for older Gradio versions that pass (user, assistant) tuples
human, assistant = msg
backend_history.append({"role": "user", "content": human})
if assistant:
backend_history.append({"role": "assistant", "content": assistant})
# Strip optional SKU filter so empty whitespace becomes None instead of an invalid lookup key
payload = {
"query": user_message,
"session_id": SESSION_ID,
"sku_id": sku_id.strip() or None,
"history": backend_history,
}
# -> {
# "query": "Should we reorder SKU001 today?",
# "session_id": "6f2a9c18-...", "sku_id": "SKU001", "history": []
# }
try:
# 60s timeout accommodates multi-step LLM reasoning and tool calls on the backend
resp = requests.post(f"{BACKEND_URL}/chat", json=payload, headers=HEADERS, timeout=60)
resp.raise_for_status()
agent_reply = resp.json()["response"]
# -> "SKU001 (Wireless Mouse) currently has 45 units on hand..."
except requests.exceptions.ConnectionError:
agent_reply = "Error: Cannot reach the backend. Make sure the backend server is running."
except requests.exceptions.HTTPError as e:
agent_reply = f"Backend error {e.response.status_code}: {e.response.text}"
except Exception as e:
agent_reply = f"Unexpected error: {e}"
# Return "" to clear the input textbox while appending both turns to the chatbot state
history.append({"role": "user", "content": user_message})
history.append({"role": "assistant", "content": agent_reply})
return "", history
def lookup_sku(sku_id: str) -> str:
if not sku_id.strip():
return "Enter a SKU ID above and click Lookup."
try:
# Uppercase the SKU to match normalized primary keys in SQLite; shorter timeout since no LLM is involved
resp = requests.get(f"{BACKEND_URL}/inventory/{sku_id.strip().upper()}", headers=HEADERS, timeout=10)
# ... (see full file: app.py)
$ python frontend/app.py
* Running on local URL: http://0.0.0.0:7860
--- Sample UI interaction ---
User (SKU: SKU001): Should we reorder SKU001 today?
Assistant: SKU001 (Wireless Mouse) currently has 45 units on hand with an average
demand of 12 units/day, a 5-day lead time, and 20 units of safety stock.
Reorder point = (12 × 5) + 20 = 80 units. Since 45 < 80, you should reorder
at least 35 units now (recommended order: 95 units to cover the next cycle).
import os
import uuid
from typing import Optional
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Security, Depends
from fastapi.security.api_key import APIKeyHeader
from pydantic import BaseModel
import db_client
import agent as agent_module
load_dotenv()
API_KEY = os.getenv("API_KEY", "dev-secret")
# auto_error=True immediately rejects requests missing X-API-Key with HTTP 403 before route logic runs
api_key_header = APIKeyHeader(name="X-API-Key", auto_error=True)
app = FastAPI(title="Inventory Planning Agent API")
# ---------------------------------------------------------------------------
# Auth
# ---------------------------------------------------------------------------
def verify_api_key(key: str = Security(api_key_header)) -> str:
# Shared-secret gate used as a FastAPI dependency on protected endpoints
if key != API_KEY:
raise HTTPException(status_code=403, detail="Invalid API key")
return key
# ---------------------------------------------------------------------------
# Startup
# ---------------------------------------------------------------------------
@app.on_event("startup")
def startup():
# Idempotent bootstrap ensures tables and seed SKUs exist even on a brand-new EFS volume
db_client.init_db()
db_client.seed_sample_data()
# ---------------------------------------------------------------------------
# Models
# ---------------------------------------------------------------------------
class ChatRequest(BaseModel):
# Pydantic validates incoming JSON types and auto-generates OpenAPI docs at /docs
query: str
session_id: Optional[str] = None
sku_id: Optional[str] = None
history: Optional[list[dict]] = None # [{"role": "user"|"assistant", "content": "..."}]
class ChatResponse(BaseModel):
session_id: str
response: str
class InventoryItem(BaseModel):
sku_id: str
# ... (see full file: api.py)
$ uvicorn api:app --host 0.0.0.0 --port 8000
INFO: Started server process [12041]
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
$ curl -s -X POST http://localhost:8000/chat \
-H "Content-Type: application/json" \
-H "X-API-Key: dev-secret" \
-d '{"query": "Do we need to reorder SKU001?", "sku_id": "SKU001"}'
{
"session_id": "6f2a9c18-4b10-4d3e-9a88-1c3e2b7f4091",
"response": "Yes — SKU001 has 45 units on hand, which is below its reorder point of 80 units (12 units/day × 5-day lead time + 20 safety stock). Recommend placing a reorder."
}
Tool-Calling Agent, Reorder Math & Guardrails#
Revision Notes#
Reference files: backend/agent.py, backend/tools/inventory_lookup.py, backend/tools/reorder_calculator.py
Concept#
Instead of letting an LLM guess stock numbers or do mental arithmetic, the agent delegates facts and math to two deterministic @tool functions inside a LangChain tool-calling loop (create_tool_calling_agent + AgentExecutor). The LLM handles natural-language understanding, tool orchestration, and plain-English explanation; Python handles database queries and arithmetic.
How One Question Flows Through the Agent#
- User asks: "Should I reorder SKU001?"
- Round 1: The LLM sees the tool schemas (function names, type hints, docstrings) and emits a tool call for
lookup_inventory(sku_id="SKU001"). - LangChain runs the Python function against SQLite and returns the SKU's live metrics (
current_inventory,avg_demand,lead_time,safety_stock). - Round 2: The LLM passes those exact numbers to
calculate_reorder(...). - Python computes the deterministic formula:
- Reorder point =
avg_demand * lead_time + safety_stock. - If
current_inventory <= reorder_point: reorder is needed, with recommended quantitymax(0, int(reorder_point + avg_demand * lead_time - current_inventory)). - Otherwise: no reorder needed, and it reports estimated
days_until_reorder = (current_inventory - reorder_point) / avg_demand.
- Reorder point =
- Final turn: The LLM synthesizes the tool output into a concise, actionable recommendation. If the user provides numbers directly (no SKU), the agent skips
lookup_inventoryand callscalculate_reorderdirectly; if numbers are missing, the system prompt instructs it to ask.
Four Production Guardrails in agent.py#
temperature=0: Produces consistent, deterministic business recommendations rather than creative phrasing.max_iterations=6: Hard cap on reasoning rounds to prevent infinite tool-calling loops and runaway token bills.timeout=45andmax_retries=2: Absorbs transient OpenAI hiccups without hanging requests indefinitely.- Model configurable via
OPENAI_MODEL: Defaults togpt-4o-mini(cheapest reliable tool-calling model) and can be upgraded (e.g., togpt-4.1-mini) via environment variable without touching code.
Safety Choice: Read-Only Tools#
Both tools only read data or compute numbers. Keeping an agent's toolset read-only dramatically reduces the blast radius of prompt injection; any future write tool (such as place_order) would require human confirmation, authorization checks, and spend caps.
Code Reference#
import os
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.messages import HumanMessage, AIMessage
from tools.reorder_calculator import calculate_reorder
from tools.inventory_lookup import lookup_inventory
load_dotenv()
# System prompt enforces tool-first grounding so the model never invents stock counts or reorder math
SYSTEM_PROMPT = """You are an expert Inventory Planning Agent. Your job is to help users manage inventory and decide when and how much to reorder.
You have access to two tools:
1. lookup_inventory — retrieves live inventory data from the database for a given SKU.
2. calculate_reorder — computes whether a reorder is needed and the recommended quantity.
Guidelines:
- Always look up the SKU from the database first if the user mentions one.
- Use calculate_reorder with the actual numbers (from DB or user input).
- Explain your reasoning clearly and in plain English.
- If information is missing (e.g., demand, lead time), ask the user for it.
- Keep responses concise but actionable.
"""
TOOLS = [lookup_inventory, calculate_reorder]
# OpenAI model used by the agent. gpt-4o-mini is the cheapest model with
# reliable tool calling; set OPENAI_MODEL=gpt-4.1-mini for higher quality.
OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
def build_agent() -> AgentExecutor:
# temperature=0 keeps tool selection and numerical reasoning deterministic;
# timeout and retries guard FastAPI workers against transient API stalls.
llm = ChatOpenAI(
model=OPENAI_MODEL,
temperature=0,
api_key=os.getenv("OPENAI_API_KEY"),
timeout=45,
max_retries=2,
)
# chat_history carries prior conversation turns; agent_scratchpad is required by
# create_tool_calling_agent to track intermediate tool calls and their outputs.
prompt = ChatPromptTemplate.from_messages([
("system", SYSTEM_PROMPT),
MessagesPlaceholder(variable_name="chat_history"),
("human", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
])
agent = create_tool_calling_agent(llm, TOOLS, prompt)
# max_iterations=6 prevents runaway tool-calling loops from burning tokens or timing out requests
return AgentExecutor(agent=agent, tools=TOOLS, verbose=True, max_iterations=6)
# Module-level singleton avoids rebuilding the LLM client and prompt graph on every HTTP request
_executor: AgentExecutor | None = None
def get_executor() -> AgentExecutor:
# ... (see full file: agent.py)
> Entering new AgentExecutor chain...
Invoking: `lookup_inventory` with `{'sku_id': 'SKU001'}`
SKU: SKU001 | Name: Wireless Mouse | Current Inventory: 45 units | Avg Demand: 12.0 units/day | Lead Time: 5 days | Safety Stock: 20 units
Invoking: `calculate_reorder` with `{'current_inventory': 45, 'avg_demand': 12.0, 'lead_time': 5, 'safety_stock': 20}`
Reorder Needed: YES | Reorder Point: 80.0 units | Recommended Order Qty: 95 units
You should reorder SKU001 (Wireless Mouse). Current stock (45 units) is below
the reorder point of 80 units; recommended order quantity is 95 units.
> Finished chain.
from langchain_core.tools import tool
import sys
import os
# Add backend/ to sys.path so db_client resolves whether invoked from backend/ or repo root
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import db_client
# @tool exposes the function signature and docstring as the JSON schema the LLM reads to call it
@tool
def lookup_inventory(sku_id: str) -> str:
"""
Look up current inventory data for a given SKU ID from the database.
Args:
sku_id: The unique product identifier (e.g., 'SKU001').
Returns:
Inventory details as a formatted string, or a not-found message.
"""
# Normalize to uppercase so user inputs like 'sku001' still hit the primary key
row = db_client.get_inventory(sku_id.upper())
# -> {
# "sku_id": "SKU001", "name": "Wireless Mouse", "current_inventory": 45,
# "avg_demand": 12.0, "lead_time": 5, "safety_stock": 20
# }
if not row:
# Return a plain-text message instead of raising so the agent can recover and ask the user
return f"No inventory record found for SKU '{sku_id}'."
# Pipe-delimited summary gives the LLM explicit units alongside every field for downstream math
return (
f"SKU: {row['sku_id']} | Name: {row['name']} | "
f"Current Inventory: {row['current_inventory']} units | "
f"Avg Demand: {row['avg_demand']} units/day | "
f"Lead Time: {row['lead_time']} days | "
f"Safety Stock: {row['safety_stock']} units"
)
>>> from tools.inventory_lookup import lookup_inventory
>>> lookup_inventory.invoke({"sku_id": "sku001"})
'SKU: SKU001 | Name: Wireless Mouse | Current Inventory: 45 units | Avg Demand: 12.0 units/day | Lead Time: 5 days | Safety Stock: 20 units'
>>> lookup_inventory.invoke({"sku_id": "SKU999"})
"No inventory record found for SKU 'SKU999'."
Containerization & Persistent Storage Pitfalls#
Revision Notes#
Reference files: backend/Dockerfile, frontend/Dockerfile, backend/init_db.py, backend/db_client.py, docker-compose.yaml, README.md
Concept#
Docker packages the app and its exact Python dependencies (python:3.11-slim) into immutable images so local runs (docker compose up --build) behave identically to cloud tasks on AWS Fargate. Several subtle production bugs were deliberately solved in this module's Docker setup.
Key Mental Models & Pitfalls Avoided#
- Never mount a persistent volume over bundled code (
schema.sqltrap):db/schema.sqlis baked into the backend image at/app/db/schema.sql.- The persistent volume (Docker
db_datalocally, AWS EFS in the cloud) is mounted at a separate path (/app/data), withDB_PATH=/app/data/inventory.db. - Mounting the volume at
/app/dbwould hideschema.sqlinside the container and crashinit_db()on a real cloud mount.
- Idempotent startup (
init_db.py+INSERT OR IGNORE):- On startup, the backend runs
init_db.pybefore launchinguvicorn(2 workers) and also initializes on FastAPI startup. - Schema creation uses
CREATE TABLE IF NOT EXISTS, and sample SKU seeding (SKU001,SKU002,SKU003) usesINSERT OR IGNOREso user edits to inventory records survive container restarts.
- On startup, the backend runs
- Python health check instead of
curl:python:3.11-slimdoes not ship withcurl. Both Docker and ECS health checks run a one-line Pythonurllib.request.urlopencall againsthttp://127.0.0.1:8000/healthso no extra OS packages are needed. - Cross-architecture builds (
--platform linux/amd64): Apple Silicon Macs build ARM64 images by default, but the ECS Fargate task definitions targetX86_64. Pushing an ARM image to an x86 Fargate task fails withexec format error; explicitly building with--platform linux/amd64prevents this on any developer machine. - Local vs. Cloud service discovery: In
docker-compose.yaml,frontendreaches the backend via Docker's built-in DNS (http://backend:8000) and waits ondepends_on: backend (condition: service_healthy). On AWS, the exact sameBACKEND_URLenv var is switched to Cloud Map private DNS (http://backend.inventory-<ver>.local:8000).
Code Reference#
"""Run this once to initialize the database and seed sample data."""
import db_client
# Both calls are idempotent (CREATE TABLE IF NOT EXISTS + upsert), so running on every container boot is safe
db_client.init_db()
db_client.seed_sample_data()
print("Database initialized and seeded at:", db_client.DB_PATH)
$ python init_db.py
Database initialized and seeded at: ../db/inventory.db
import sqlite3
import os
from typing import Optional
DB_PATH = os.getenv("DB_PATH", "../db/inventory.db")
# schema.sql ships inside the image next to the backend code. The persistent
# volume (EFS on AWS) is mounted at a *different* path (/app/data) so the
# schema file is never hidden by the mount.
SCHEMA_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "db", "schema.sql")
def _connect() -> sqlite3.Connection:
# 30s lock timeout lets concurrent Uvicorn workers wait on SQLite writes instead of failing immediately
conn = sqlite3.connect(DB_PATH, timeout=30)
# sqlite3.Row allows accessing columns by name (row["sku_id"]) and converting cleanly with dict(row)
conn.row_factory = sqlite3.Row
return conn
def init_db() -> None:
# Ensure the parent directory exists before SQLite attempts to create the file (important on fresh volumes)
db_dir = os.path.dirname(os.path.abspath(DB_PATH))
os.makedirs(db_dir, exist_ok=True)
with open(SCHEMA_PATH) as f:
sql = f.read()
with _connect() as conn:
conn.executescript(sql)
def get_inventory(sku_id: str) -> Optional[dict]:
with _connect() as conn:
# Parameterized ? placeholder prevents SQL injection
row = conn.execute(
"SELECT * FROM inventory WHERE sku_id = ?", (sku_id,)
).fetchone()
return dict(row) if row else None
def upsert_inventory(data: dict) -> None:
fields = ["sku_id", "name", "current_inventory", "avg_demand", "lead_time", "safety_stock"]
values = [data.get(f) for f in fields]
# -> ['SKU001', 'Wireless Mouse', 45, 12.0, 5, 20]
with _connect() as conn:
# ON CONFLICT DO UPDATE makes both seeding and API updates idempotent atomic upserts
conn.execute(
"""
INSERT INTO inventory (sku_id, name, current_inventory, avg_demand, lead_time, safety_stock)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(sku_id) DO UPDATE SET
name = excluded.name,
current_inventory = excluded.current_inventory,
avg_demand = excluded.avg_demand,
lead_time = excluded.lead_time,
safety_stock = excluded.safety_stock,
updated_at = datetime('now')
""",
values,
)
def log_session(session_id: str, user_query: str, agent_response: str, sku_ref: Optional[str] = None) -> None:
with _connect() as conn:
conn.execute(
# ... (see full file: db_client.py)
>>> import db_client
>>> db_client.init_db()
>>> db_client.upsert_inventory({
... "sku_id": "SKU001", "name": "Wireless Mouse",
... "current_inventory": 45, "avg_demand": 12.0, "lead_time": 5, "safety_stock": 20
... })
>>> db_client.get_inventory("SKU001")
{'sku_id': 'SKU001', 'name': 'Wireless Mouse', 'current_inventory': 45, 'avg_demand': 12.0, 'lead_time': 5, 'safety_stock': 20, 'updated_at': '2026-04-12 10:15:02'}
AWS Infrastructure as Code (CloudFormation Stack)#
Revision Notes#
Reference files: infra/inventory-stack.yaml, 01-understand-the-system.html
Concept#
Rather than clicking through the AWS Console or running dozens of imperative CLI commands (one per resource), the entire AWS environment (~35 resources) is declared in a single CloudFormation template (infra/inventory-stack.yaml). You describe the desired end state; CloudFormation resolves dependencies, builds resources in order, tracks them as one versioned stack (inventory-stack-v1, v2, ...), and tears them all down cleanly with a single delete command.
The AWS Building Blocks (Mapped to Their Roles)#
- Networking (VPC, 2 Public Subnets, Internet Gateway, Route Table):
- Isolated VPC (
10.0.0.0/16) split into two public subnets (10.0.1.0/24,10.0.2.0/24) across two Availability Zones (required by ALB). - Both subnets route
0.0.0.0/0to the Internet Gateway so tasks can pull images from ECR and call the OpenAI API without paying for a NAT Gateway.
- Isolated VPC (
- Chained Security Groups (Zero-Trust Hop-by-Hop Firewall):
AlbSecurityGroupaccepts HTTP:80from0.0.0.0/0.FrontendSecurityGroupaccepts:7860only fromAlbSecurityGroup.BackendSecurityGroupaccepts:8000only fromFrontendSecurityGroup.EfsSecurityGroupaccepts NFS:2049only fromBackendSecurityGroup.
- ECR (Elastic Container Registry): Stores versioned Docker images (
inventory-backend,inventory-frontend) shared across stack versions. - ECS + Fargate (Serverless Containers):
- Cluster (
inventory-<ver>) runs two Services (inventory-backend,inventory-frontend) on Fargate (no EC2 servers to patch or manage). - Task Definitions specify image URI, CPU/memory (backend
1 vCPU / 2 GiB, frontend0.5 vCPU / 1 GiB), env vars, SSM secrets, EFS volume mount, and log driver. - Rolling updates + Circuit Breaker:
MaximumPercent: 200,MinimumHealthyPercent: 100starts new healthy tasks before stopping old ones;DeploymentCircuitBreaker(Enable: true,Rollback: true) automatically reverts broken deployments.
- Cluster (
- Application Load Balancer (ALB): Public entry point on port
80forwarding toFrontendTargetGroup(:7860, target typeip). Uses a 120-second idle timeout (to accommodate multi-step LLM responses) and sticky cookies (lb_cookie) so multi-replica Gradio sessions stay pinned to one task. - AWS Cloud Map (Private DNS): Registers the backend task's private IP under
backend.inventory-<ver>.localinside the VPC so the frontend discovers it without exposing the backend publicly. - EFS + Access Point (Persistent Disk): Encrypted network filesystem with mount targets in both subnets. An Access Point pins the root directory (
/inventorydb) and POSIX UID/GID (1000:1000) so containers can always read/write SQLite regardless of container user, with transit encryption enabled. - SSM Parameter Store (
SecureString): StoresOPENAI_API_KEY(/inventory/openai-api-key) andAPI_KEY(/inventory/api-key) encrypted with KMS; ECS injects them as container environment variables at task launch. - Two Distinct IAM Roles:
TaskExecutionRole(for ECS itself) — Pulls images from ECR, pushes logs to CloudWatch, and fetches/decrypts the two SSM secrets (ssm:GetParameter+kms:Decryptscoped viakms:ViaService).TaskRole(for the running app) — Grantsssmmessages:*(for ECS Exec debugging inside running containers) and EFSClientMount/ClientWrite.
- CloudWatch Logs: Captures stdout/stderr from both services (
/ecs/inventory-<ver>/backendand/frontend) with 7-day retention.
Each Security Group allows inbound traffic only from its immediate upstream Security Group ID rather than broad CIDR blocks, enforcing hop-by-hop least privilege across the versioned stack.
Code Reference#
AWSTemplateFormatVersion: "2010-09-09"
Description: >
Inventory Planning Agent - one versioned deployment (the AWS equivalent of an
Azure resource group). Creates: VPC + 2 public subnets, security groups,
EFS (persistent SQLite), ECS Fargate cluster, Cloud Map private DNS for the
internal backend, public ALB for the Gradio frontend, IAM roles, log groups.
Delete this stack to remove every resource it created.
# ---------------------------------------------------------------------------
# Parameters - all passed from the CLI (see docs/02-deploy-by-hand.html)
# ---------------------------------------------------------------------------
Parameters:
# Scopes every resource name so v1 and v2 stacks can run side-by-side for safe rollbacks
Version:
Type: String
Description: Deployment version tag (v1, v2, ...). Used in every resource name.
AllowedPattern: "^[a-z0-9-]{1,12}$"
ConstraintDescription: lowercase letters, digits and dashes only (max 12 chars, e.g. v1, v2, demo-3)
# Immutable ECR URIs pin exact container builds for reproducible deploys
BackendImage:
Type: String
Description: Full ECR image URI for the backend, e.g. 123456789012.dkr.ecr.us-east-1.amazonaws.com/inventory-backend:v1
FrontendImage:
Type: String
Description: Full ECR image URI for the frontend
# Pass SSM parameter *names* (not raw secret values) so secrets never appear in CloudFormation events
OpenAIKeyParameterName:
Type: String
Default: /inventory/openai-api-key
Description: SSM Parameter Store SecureString holding the OpenAI API key
ApiKeyParameterName:
Type: String
Default: /inventory/api-key
Description: SSM Parameter Store SecureString holding the internal X-API-Key
OpenAIModel:
Type: String
Default: gpt-4o-mini
Description: OpenAI chat model used by the agent (must support tool calling)
# MinValue: 0 lets you scale Fargate tasks to zero to pause compute cost while keeping EFS data intact
DesiredCount:
Type: Number
Default: 1
MinValue: 0
MaxValue: 3
Description: Number of tasks for each service (0 = stopped, like min-replicas 0)
# Fargate requires valid CPU/Memory pairs; 1024 CPU (1 vCPU) + 2048 MiB handles 2 Uvicorn workers comfortably
BackendCpu:
Type: Number
Default: 1024
Description: Backend task CPU units (1024 = 1 vCPU)
BackendMemory:
Type: Number
Default: 2048
Description: Backend task memory in MiB
# ... (see full file: inventory-stack.yaml)
$ aws cloudformation deploy \
--template-file infra/inventory-stack.yaml \
--stack-name inventory-agent-v1 \
--capabilities CAPABILITY_NAMED_IAM \
--parameter-overrides Version=v1 \
BackendImage=123456789012.dkr.ecr.us-east-1.amazonaws.com/inventory-backend:v1 \
FrontendImage=123456789012.dkr.ecr.us-east-1.amazonaws.com/inventory-frontend:v1
Waiting for changeset to be created..
Waiting for stack create/update to complete
Successfully created/updated stack - inventory-agent-v1
Security (Defence in Depth), Design Trade-Offs & Cost Control#
Revision Notes#
Reference files: infra/inventory-stack.yaml, backend/api.py, 01-understand-the-system.html
Defence in Depth (Layered Security)#
- Perimeter: Only the ALB is publicly reachable (port
80); neither container accepts direct internet traffic despite having public IPs for outbound calls. - Network segmentation: Security groups enforce strict hop-by-hop ingress (
ALB → Frontend → Backend → EFS). - Application authentication: Even though the backend has no public URL, it still requires
X-API-Keyon/chatand/inventory(defence in depth if a misconfiguration ever exposes it). - Secret management & encryption: Secrets live in KMS-encrypted SSM Parameter Store (never in git or images); EFS encrypts data both at rest and in transit.
- Known classroom gap: The Gradio UI itself has no user login and runs over plain HTTP. Anyone with the ALB URL can consume OpenAI credits. In production, add HTTPS via AWS Certificate Manager (redirecting HTTP → HTTPS) and authentication (e.g., Amazon Cognito or SSO on the ALB).
Key Architectural Trade-Offs (Interview-Ready)#
- Public subnets with public IPs vs. Private subnets + NAT Gateway:
- Choice: Tasks sit in public subnets with
AssignPublicIp: ENABLED, while Security Groups block all unwanted inbound traffic. - Why: Saves ~\$32/month per NAT Gateway in a learning environment.
- Production upgrade: Move tasks to private subnets behind a NAT Gateway (or VPC Endpoints for ECR/SSM/Logs).
- Choice: Tasks sit in public subnets with
- SQLite on EFS vs. Managed RDS/Aurora:
- Choice: Single SQLite file on EFS (
timeout=30). - Why: Zero database server cost/setup and identical local-to-cloud schema; fine for single-task demos.
- Production upgrade: Multiple concurrent backend tasks writing to SQLite over NFS risk lock contention; switch to Amazon RDS (PostgreSQL) for multi-replica production workloads.
- Choice: Single SQLite file on EFS (
- One CloudFormation stack per version (
v1,v2):- Why: Gives complete blast-radius isolation (like an Azure Resource Group). You can spin up
v2side-by-side withv1, verify it, and deletev1cleanly without leftover resources.
- Why: Gives complete blast-radius isolation (like an Azure Resource Group). You can spin up
- Azure Container Apps vs. AWS ECS Fargate (Key Conceptual Shifts):
- Azure Container Apps hides VPCs, ingress, and DNS inside a managed environment and can scale to zero automatically on idle.
- On AWS ECS Fargate, you explicitly declare VPC, ALB, Cloud Map, EFS, and IAM in CloudFormation, and ECS does not auto-wake from 0 tasks when HTTP traffic arrives.
Cost Control: The "Rented Car" Mental Model#
- Keep running: Paying for Fargate vCPU/RAM + ALB + public IPv4s + EFS/Logs + OpenAI tokens.
- Pause (
--desired-count 0): Stops Fargate compute charges ("engine off"), but you still pay ~\$1/day ("parking spot") for the ALB, its public IPs, and DNS. Must be manually resumed (--desired-count 1). - Delete the stack (
delete-stack): Returns the car — removes compute, ALB, EFS, VPC, and DNS, dropping ongoing AWS cost to nearly \$0. - Preventive guardrails: Always configure an AWS Budget alert (e.g., \$10/month at 80%) and an OpenAI monthly spend limit.
Manual Deployment Lifecycle & Troubleshooting#
Revision Notes#
Reference files: 02-deploy-by-hand.html, README.md
The 5 Phases of the 11-Step Manual Deploy#
- Prepare (Steps 1–2): Verify AWS identity (
sts get-caller-identity), create one-time AWS service-linked roles (for ECS/ELB if absent), and create shared ECR repositories (inventory-backend,inventory-frontend). - Pack (Steps 3–4): Authenticate Docker to ECR, build both images for
linux/amd64, push them tagged with$VERSION, and writeOPENAI_API_KEY+API_KEYinto SSM Parameter Store asSecureString. - Build (Step 5): Run one
aws cloudformation deploycommand (~7 minutes) to provision the entire versioned stack (--capabilities CAPABILITY_IAM --disable-rollback). - Verify (Steps 6–9): Check ECS running task counts, inspect internal Cloud Map DNS, optionally exec into a running container via ECS Exec (Session Manager) to curl the private backend, open the ALB
FrontendURL, run the chat test, and prove persistence by stopping the backend task and confirming edited SKUs survive on EFS. - Operate & Clean Up (Steps 10–11): Pause services (
--desired-count 0), perform targeted rolling updates when code changes, or rundelete-stackto remove every versioned resource.
The Four-Question Troubleshooting Method#
Whenever a deployment fails or the UI returns 503/errors, inspect in this exact order:
- Did CloudFormation reject a resource? → Check failed stack events (
describe-stack-events). - Did ECS fail to schedule or register tasks? → Check ECS service events (
describe-services). - Why did a container exit? → Inspect stopped task reasons (
list-tasks --desired-status STOPPED+describe-tasks) — catches image pull errors, SSM permission errors, orexec format error. - What did the app print before crashing? → Tail CloudWatch Logs (
/ecs/inventory-<ver>/backendor/frontend).
CI/CD Automation & Keyless AWS Auth via GitHub OIDC#
Revision Notes#
Reference files: infra/github-oidc.yaml, .github/workflows/deploy.yml, .github/workflows/destroy.yml, 03-automate-with-github-actions.html
Concept#
Manual deployments don't scale to frequent code changes and risk human error. .github/workflows/deploy.yml automates the entire build → push → SSM sync → CloudFormation deploy → smoke-test pipeline on every push to main, using GitHub OIDC so zero long-lived AWS access keys are ever stored in GitHub.
How Keyless OIDC Authentication Works#
GitHub Actions exchanges a short-lived signed OIDC JWT with AWS STS for 1-hour IAM credentials, deploying commit-SHA container tags with live smoke verification and automatic rollback.
Key Mental Models in deploy.yml#
- Path-filtered triggers + concurrency locking:
- Triggers on pushes to
mainonly when app/infra files change (backend/**,frontend/**,db/**,infra/inventory-stack.yaml,deploy.yml), plus manualworkflow_dispatch. concurrency: group: deploy-<version>withcancel-in-progress: falsequeues overlapping pushes so two runs never mutate the same CloudFormation stack simultaneously.
- Triggers on pushes to
- Fail-fast configuration check: Validates
AWS_ROLE_ARN(variable) andOPENAI_API_KEY/API_KEY(secrets) in step 1 instead of failing 10 minutes into a build. - Immutable commit-SHA image tags ("medicine batch numbers"):
- Images are tagged with both the 7-char commit SHA (
${GITHUB_SHA::7}) and$VERSION, and CloudFormation deploys the commit-SHA tag. - Every deployment is traceable to an exact commit, forces ECS to roll out new task definitions cleanly, and makes rollbacks trivial (
git revert+ push, or re-run an earlier green workflow).
- Images are tagged with both the 7-char commit SHA (
- Smart rollback behavior (First Creation vs. Updates):
- No stack yet: Uses
--disable-rollbackso failed resources stay intact for theif: failure()diagnostics step. - Previous first creation failed (
CREATE_FAILED/ROLLBACK_COMPLETE): Automatically deletes the broken stack and starts clean. - Healthy stack exists: Updates with normal rollback enabled + ECS circuit breaker, so a bad commit never takes down the live app.
- No stack yet: Uses
- Automated smoke test & failure diagnostics: Polls the ALB
FrontendURLfor HTTP200(up to 5 minutes), publishes a run summary, and on any failure automatically runs the four-question troubleshooting method in collapsible log groups.
Safe Teardown (destroy.yml) & Deletion Order#
- Manual-only with safety catch:
destroy.ymlruns only viaworkflow_dispatchand aborts unless the operator typesDELETEin the confirmation box. - Retry loop + verification report: Retries
delete-stackup to 3 times (60s apart) to handle AWS releasing ENIs/Cloud Map registrations, optionally deletes shared ECR repos and SSM secrets (delete_shared), and prints a verification audit of remaining resources. - Order matters when tearing everything down: Always run
destroy.ymlfirst, and delete thegithub-oidc-inventory-agentrole stack from your laptop last — deleting the IAM role first cuts off the workflow's ability to authenticate to AWS.
Code Reference#
AWSTemplateFormatVersion: "2010-09-09"
Description: >
One-time setup for GitHub Actions -> AWS (OIDC). Creates the GitHub OIDC
identity provider (optional, one per account) and an IAM role that ONLY
workflows from the named GitHub repository can assume. No long-lived AWS
access keys are stored in GitHub. Delete this stack to remove both.
Parameters:
# Restricts the IAM trust policy to this exact owner/repo so no other GitHub repo can assume the role
GitHubRepo:
Type: String
Description: GitHub repository allowed to deploy, as owner/name (e.g. shivank101/inventory-agent-aws)
AllowedPattern: "^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$"
ConstraintDescription: must be owner/name
# Toggle handles AWS's limit of one OIDC provider per issuer URL per account
CreateOidcProvider:
Type: String
Default: "true"
AllowedValues: ["true", "false"]
Description: >
An AWS account can hold only ONE provider for token.actions.githubusercontent.com.
Set to "false" if the first deploy fails with EntityAlreadyExists (the provider is
already there from another project) - the role will reuse the existing provider.
RoleName:
Type: String
Default: github-actions-inventory-agent-deploy
Description: Name of the IAM role GitHub Actions will assume
Conditions:
MakeProvider: !Equals [!Ref CreateOidcProvider, "true"]
Resources:
GitHubOidcProvider:
Type: AWS::IAM::OIDCProvider
Condition: MakeProvider
Properties:
Url: https://token.actions.githubusercontent.com
# Audience must match what aws-actions/configure-aws-credentials requests from GitHub
ClientIdList:
- sts.amazonaws.com
# AWS validates GitHub's certificate chain itself; these thumbprints are
# the documented placeholders and are accepted as-is.
ThumbprintList:
- 6938fd4d98bab03faadb97b34396831e3780aea1
- 1c58a3a8518e8759bf075b76b750d4f2df264fcd
DeployRole:
Type: AWS::IAM::Role
Properties:
RoleName: !Ref RoleName
Description: !Sub Assumed by GitHub Actions workflows of ${GitHubRepo} to deploy the inventory agent
# Caps temporary STS credentials to 1 hour to limit blast radius
MaxSessionDuration: 3600
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
# Uses the newly created provider or references the existing account-level provider ARN
Federated: !If
- MakeProvider
# ... (see full file: github-oidc.yaml)
$ aws cloudformation deploy \
--template-file infra/github-oidc.yaml \
--stack-name inventory-github-oidc \
--capabilities CAPABILITY_NAMED_IAM \
--parameter-overrides GitHubRepo=myorg/inventory-agent-aws
Waiting for stack create/update to complete
Successfully created/updated stack - inventory-github-oidc
$ aws cloudformation describe-stacks --stack-name inventory-github-oidc \
--query "Stacks[0].Outputs" --output table
--------------------------------------------------------------------------------------
| DescribeStacks |
+---------------+--------------------------------------------------------------------+
| OutputKey | OutputValue |
+---------------+--------------------------------------------------------------------+
| DeployRoleArn| arn:aws:iam::123456789012:role/github-actions-inventory-agent-deploy|
+---------------+--------------------------------------------------------------------+
# =============================================================================
# Deploy to AWS — the CI/CD version of docs/02-deploy-by-hand.html
#
# push to main ──▶ build images ──▶ push to ECR ──▶ secrets to SSM
# ──▶ aws cloudformation deploy (network, EFS, ECS, ALB, services)
# ──▶ print the public URL in the job summary
#
# Authentication: GitHub OIDC -> IAM role (infra/github-oidc.yaml). No AWS keys
# are stored in GitHub.
#
# Repository configuration (Settings -> Secrets and variables -> Actions):
# variables: AWS_ROLE_ARN (required) AWS_REGION (default us-east-1)
# DEPLOY_VERSION (default v1) OPENAI_MODEL (default gpt-4o-mini)
# secrets: OPENAI_API_KEY (required) API_KEY (required)
# =============================================================================
name: Deploy to AWS
on:
push:
branches: [main]
# Path filter skips expensive Docker builds & deploys on docs-only commits
paths:
- "backend/**"
- "frontend/**"
- "db/**"
- "infra/inventory-stack.yaml"
- ".github/workflows/deploy.yml"
# Allows triggering a manual redeploy from the GitHub Actions UI
workflow_dispatch:
permissions:
id-token: write # needed to request the OIDC token for AWS
contents: read
# Queue overlapping pushes instead of cancelling mid-flight CloudFormation updates
concurrency:
group: deploy-${{ vars.DEPLOY_VERSION || 'v1' }}
cancel-in-progress: false
env:
AWS_REGION: ${{ vars.AWS_REGION || 'us-east-1' }}
VERSION: ${{ vars.DEPLOY_VERSION || 'v1' }}
OPENAI_MODEL: ${{ vars.OPENAI_MODEL || 'gpt-4o-mini' }}
jobs:
deploy:
name: Build, push and deploy
runs-on: ubuntu-latest
# Failsafe timeout prevents a stalled ECS stabilization from burning runner minutes
timeout-minutes: 40
steps:
# Fail fast before building images if required repo variables or secrets are missing
- name: Check repository configuration
env:
AWS_ROLE_ARN: ${{ vars.AWS_ROLE_ARN }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
API_KEY: ${{ secrets.API_KEY }}
run: |
missing=""
[ -z "$AWS_ROLE_ARN" ] && missing="$missing AWS_ROLE_ARN(variable)"
[ -z "$OPENAI_API_KEY" ] && missing="$missing OPENAI_API_KEY(secret)"
# ... (see full file: deploy.yml)
GitHub Actions — Workflow: Deploy to AWS (main)
✓ Check repository configuration (1s)
✓ Configure AWS credentials via OIDC (2s)
✓ Build and push backend & frontend images to ECR (1m 42s)
✓ Sync secrets to SSM Parameter Store (3s)
✓ Deploy CloudFormation stack inventory-agent-v1 (4m 18s)
Job Summary:
Stack: inventory-agent-v1 (us-east-1)
App URL: http://inventory-alb-v1-984312045.us-east-1.elb.amazonaws.com
How All Building Blocks Connect#
Revision Notes#
This module progresses through three cohesive layers from code to cloud automation:
- Application Layer (
backend/,frontend/,db/): Separates a Gradio chat UI from a stateless FastAPI backend running a deterministic two-tool LangChain agent (lookup_inventory+calculate_reorder) backed by SQLite, protected byX-API-Keyand agent guardrails (temperature=0,max_iterations=6). - Packaging & Infrastructure Layer (
Dockerfiles,docker-compose.yaml,infra/inventory-stack.yaml): Packages both services aslinux/amd64containers with/app/dataseparated from/app/db/schema.sql, then maps the exact same architecture onto AWS via one versioned CloudFormation stack (VPC, chained Security Groups, ALB, Cloud Map, ECS Fargate, EFS, SSM, IAM, CloudWatch). - Automation & Operations Layer (
infra/github-oidc.yaml,.github/workflows/deploy.yml,destroy.yml): Replaces manual CLI steps with keyless OIDC CI/CD, commit-SHA image tagging, safe rolling updates with circuit-breaker rollback, automated smoke testing/diagnostics, and guarded teardown.
Code Reference#
# Slim base image keeps ECR pulls and ECS Fargate cold starts fast
FROM python:3.11-slim
# Set working directory to app root so relative paths (../db/) work correctly
WORKDIR /app
# Copy backend source and db schema
COPY backend/ ./backend/
COPY db/schema.sql ./db/schema.sql
WORKDIR /app/backend
# --no-cache-dir omits pip's download cache to shrink the final container image
RUN pip install --no-cache-dir -r requirements.txt
# The SQLite file lives on a persistent volume mounted at /app/data (EFS on AWS).
# NOTE: this is deliberately NOT /app/db — mounting there would hide schema.sql.
ENV DB_PATH=/app/data/inventory.db
ENV PORT=8000
EXPOSE 8000
# Health check uses stdlib urllib so we don't have to install curl in python:slim
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
CMD python -c "import urllib.request,os; urllib.request.urlopen('http://127.0.0.1:' + os.environ.get('PORT','8000') + '/health', timeout=4)" || exit 1
# init_db.py is idempotent: creates schema + seeds sample data if not present before Uvicorn binds 0.0.0.0
CMD ["sh", "-c", "python init_db.py && uvicorn api:app --host 0.0.0.0 --port ${PORT:-8000} --workers 2"]
$ docker build -f backend/Dockerfile -t inventory-backend:v1 .
[+] Building 18.4s (10/10) FINISHED
=> exporting to image inventory-backend:v1
$ docker run -p 8000:8000 -e OPENAI_API_KEY=sk-... inventory-backend:v1
Database initialized and seeded at: /app/data/inventory.db
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO: Started parent process [7]
INFO: Started server process [9]
INFO: Started server process [10]
services:
backend:
# Build context is repo root so backend/Dockerfile can COPY both backend/ and db/schema.sql
build:
context: .
dockerfile: backend/Dockerfile
ports:
- "8000:8000"
volumes:
- db_data:/app/data # Persist SQLite db across restarts (same path as EFS on AWS)
env_file:
- .env
environment:
- DB_PATH=/app/data/inventory.db
# Mirrors the Dockerfile probe so Compose knows when /health is ready for frontend traffic
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=4)"]
interval: 30s
timeout: 10s
retries: 3
start_period: 20s
frontend:
build:
context: .
dockerfile: frontend/Dockerfile
ports:
- "7860:7860"
env_file:
- .env
environment:
- BACKEND_URL=http://backend:8000 # Overrides .env — uses Docker network name
- PORT=7860
# Wait for backend's healthcheck to pass so Gradio doesn't serve requests before the API is up
depends_on:
backend:
condition: service_healthy
# Named volume managed by Docker; survives `docker compose down` unless `-v` is passed
volumes:
db_data:
$ docker compose up --build
[+] Running 3/3
✔ Network inventory-agent_default Created
✔ Container inventory-agent-backend-1 Healthy
✔ Container inventory-agent-frontend-1 Started
backend-1 | Database initialized and seeded at: /app/data/inventory.db
backend-1 | INFO: Uvicorn running on http://0.0.0.0:8000
frontend-1 | * Running on local URL: http://0.0.0.0:7860
Quick Self-Check Questions#
Self-Check Questions#
Why is the persistent volume mounted at /app/data instead of /app/db?
Because db/schema.sql is baked into the Docker image at /app/db/schema.sql. Mounting an empty EFS volume onto /app/db would hide schema.sql and crash init_db() on startup.
Why does the backend have two different IAM roles (TaskExecutionRole vs. TaskRole)?
TaskExecutionRole is used by the ECS platform before/around the container (pulling ECR images, writing CloudWatch logs, reading/decrypting SSM secrets). TaskRole is assumed by the application inside the container (EFS mount/write and ECS Exec ssmmessages).
If the backend is private (no public ALB), why does it still enforce X-API-Key?
Defence in depth: relying solely on network boundaries means a single misconfigured security group or load balancer rule would expose the API and OpenAI bill. Checking X-API-Key adds an independent application-layer lock.
Why do Fargate tasks in this stack sit in public subnets with public IPs instead of private subnets?
So tasks can make outbound calls (ECR image pulls, OpenAI API) through the Internet Gateway without paying ~\$32/month for a NAT Gateway, while Security Groups still block all unauthorized inbound traffic.
What is the difference between pausing ECS services (--desired-count 0) and deleting the CloudFormation stack?
Pausing stops Fargate compute charges, but you still pay ~\$1/day for the ALB, public IPs, and DNS (and ECS will not auto-wake on traffic). Deleting the stack removes all versioned resources and drops ongoing cost to nearly \$0.
Why does deploy.yml tag and deploy images with the 7-character commit SHA instead of reusing :v1?
Commit-SHA tags make every deployment immutable and traceable to an exact git commit, force ECS to register a new task definition revision on every push, and allow exact rollbacks without overwriting previous images.
Why must you run destroy.yml before deleting the github-oidc-inventory-agent CloudFormation stack?
Because destroy.yml assumes the IAM role created by github-oidc-inventory-agent via OIDC. Deleting that role stack first locks GitHub Actions out of AWS before it can delete the application stack.