Inventory Agent on AWS

Part 1 of 3

Understand the system before you deploy it

What the inventory agent does, how an AI agent uses tools, and what every AWS service in the diagram is doing for us. Each idea comes with an everyday analogy, real numbers and a real-world example.

The problem we are solving

Meet Priya. She manages stock for a chain of phone-accessory shops in Bangalore. Every morning she asks the same question for hundreds of products: do I need to order more of this today?

Getting it wrong hurts in two directions:

  • Order too late and the shelf goes empty. A customer who wanted a USB-C charger walks to the shop next door. That sale is gone, and maybe the customer too. Retailers call this a stock-out.
  • Order too early or too much and money sits in cardboard boxes in the back room. That cash could have paid salaries or rent.

Warehouses have used a simple rule for decades to steer between those two mistakes. It is called the reorder point, and it fits in one sentence:

Our app wraps that rule in a chat window. Priya types a question in plain English. An AI agent decides which numbers it needs, fetches them from a live database, does the maths with a real calculator (not a guess), and explains the answer like a colleague would.

What the app looks like to a user

The screen has two halves. On the left, a small panel where you can type a product code (a SKU, short for stock-keeping unit, like SKU001) and click Lookup SKU to see its numbers. On the right, a chat box.

The database starts with three sample products:

SKUNameIn stockSells per daySupplier takesSafety cushion
SKU001Widget A100107 days20
SKU002Widget B4085 days15
SKU003Gadget X200510 days10

Three conversations show what the agent does. The wording of real replies varies a little each time (it is a language model), but the numbers come from the database and the calculator, so they are always the same.

“Should I reorder SKU001?”

The agent looks up SKU001, runs the calculator, and replies roughly: “Not yet. Widget A has 100 units and its reorder point is 90 (10 a day × 7 days + 20 safety stock). At current sales you will reach 90 in about a day, so plan to place the order tomorrow.”

“How much should I order for SKU002?”

Widget B has 40 units, below its reorder point of 55. The agent replies: “Yes, reorder now. Recommended quantity: 55 units.”

“Inventory is 50, demand is 8 a day, lead time is 5 days. What do I do?”

No SKU is mentioned, so the agent skips the database and goes straight to the calculator with the numbers you gave it: reorder point 40, you have 50, so “no reorder yet, about 1.2 days to go.” The agent chose which tools to use based on the question. That choice is what makes it an agent rather than a script.

The four parts of the app

Before any cloud, the app itself has four parts. A restaurant is a good way to picture them.

PartBuilt withIts jobListens on
FrontendGradio (Python)Draws the chat page, sends your message to the backend, shows the replyport 7860
BackendFastAPI (Python)Checks the API key, runs the agent, saves each conversationport 8000
AgentLangChain + OpenAIDecides which tools to call, combines the results into an answerruns inside the backend
DatabaseSQLite (a single file)Stores products and a log of every question and answera file: inventory.db

Why split the frontend from the backend?

It would be simpler to put everything in one program. We split it for three practical reasons:

  1. Security. The backend holds the OpenAI key and the database. Keeping it off the public internet means an attacker can only reach the chat page, never the API behind it.
  2. Replaceable front doors. Tomorrow you could add a WhatsApp bot or a mobile app that talks to the same backend. The agent and database stay untouched.
  3. Independent sizing. The agent needs more memory than the chat page. Splitting lets us give each exactly what it needs (and pay only for that).

How the agent thinks: tool calling

A large language model is a brilliant talker with no hands. It cannot open your database, and it is unreliable at arithmetic on numbers it has never seen. Tool calling gives it hands.

We describe our tools to the model: their names, what they do, and what inputs they take. When the model needs one, it does not run it. It replies with a structured request, something like “please run lookup_inventory with sku_id = "SKU001"”. Our Python code runs the tool, sends the result back, and the model continues. This repeats until the model has enough to answer.

The agent loop Your question goes to the OpenAI model. The model either asks for a tool, which our code runs and returns, or gives the final answer. Your question Should I reorder SKU001? OpenAI model reads the question and the tool list, decides the next move Our code runs the tool lookup_inventory calculate_reorder Final answer in plain English 1 2 3 1 model asks for a tool (JSON) 2 our code sends the result back as text 3 no tool needed any more: final answer
LangChain's AgentExecutor runs this loop. It stops when the model gives a final answer, or after 6 rounds (max_iterations=6) so a confused model cannot loop forever and run up a bill.

Watch one question, round by round

Here is exactly what travels between our backend and OpenAI when you ask about SKU001 with SKU001 typed in the side panel. The backend first adds the SKU to your message, so the model receives [SKU: SKU001] Should I reorder SKU001?

RoundModel saysOur code does
1Call lookup_inventory with {"sku_id": "SKU001"}Reads the row from SQLite and returns:
SKU: SKU001 | Name: Widget A | Current Inventory: 100 units | Avg Demand: 10.0 units/day | Lead Time: 7 days | Safety Stock: 20 units
2Call calculate_reorder with {"current_inventory": 100, "avg_demand": 10.0, "lead_time": 7, "safety_stock": 20}Runs the formula and returns:
Reorder point: 90.0 units. Current inventory (100) is ABOVE the reorder point. No immediate reorder needed. Estimated 1.0 days until reorder point is reached.
3Writes the final answer in plain EnglishSaves question and answer in the sessions table, sends the reply to the frontend

So one question costs three calls to OpenAI. Remember that number; it matters in the cost section.

How does the model know our tools exist?

Look at the top of backend/tools/reorder_calculator.py:

@tool
def calculate_reorder(
    current_inventory: int,
    avg_demand: float,
    lead_time: int,
    safety_stock: int = 0,
) -> str:
    """
    Calculate whether a reorder is needed and how much to order.
    ...
    """

The @tool decorator reads the function's name, parameter types and docstring, and turns them into a description that is sent to OpenAI with every request. The model never sees our Python code, only that description.

Four guard rails in agent.py

temperature=0
Makes the model choose its most likely words, so the same question gets nearly the same answer. Good for business decisions, bad for poetry.
max_iterations=6
Hard stop after six rounds. Protects against loops and surprise bills.
timeout=45, max_retries=2
If OpenAI is slow or has a hiccup, wait up to 45 seconds and retry twice before giving up with a clear error.
OPENAI_MODEL
The model name comes from an environment variable (default gpt-4o-mini, the cheapest model with reliable tool calling). Switch to gpt-4.1-mini for better answers without touching code.

Where does the conversation memory live?

The backend remembers nothing between requests. Each time you press Send, the frontend sends the whole conversation so far along with the new message. This is called being stateless.

The reorder maths, with every number shown

The calculator tool uses three small formulas. Here they are in words first, then with numbers.

Reorder point
daily demand × lead time + safety stock. How much stock you need to survive until a new delivery arrives, plus a cushion.
Should I reorder?
Yes if current stock ≤ reorder point.
How much?
reorder point + daily demand × lead time − current stock. Enough to cover the waiting period, the cushion, and one more delivery cycle.
Days left
(current stock − reorder point) ÷ daily demand, when no reorder is needed yet.
SKUReorder pointDecisionResult
SKU00110 × 7 + 20 = 90100 > 90, wait(100 − 90) ÷ 10 = 1.0 day to go
SKU0028 × 5 + 15 = 5540 ≤ 55, reorder55 + 40 − 40 = 55 units
SKU0035 × 10 + 10 = 60200 > 60, wait(200 − 60) ÷ 5 = 28.0 days to go

Try the calculator tool yourself

This runs the exact same formula as calculate_reorder, and shows the exact text the tool hands back to the model.

The tool returns this text to the model:

Code tour: every file and what it does

The code is small enough to read in one sitting. Here is the map.

inventory-agent-aws/
├── backend/
│   ├── api.py                 the web API (FastAPI): routes, API-key check, logging
│   ├── agent.py               builds the LangChain agent on OpenAI
│   ├── tools/
│   │   ├── inventory_lookup.py    tool 1: read a product from SQLite
│   │   └── reorder_calculator.py  tool 2: the reorder maths
│   ├── db_client.py           all SQLite reads and writes in one place
│   ├── init_db.py             creates tables + sample data at start-up
│   ├── Dockerfile             how to package the backend
│   └── requirements.txt       exact library versions
├── frontend/
│   ├── app.py                 the Gradio chat page
│   ├── Dockerfile
│   └── requirements.txt
├── db/schema.sql              the two tables: inventory, sessions
├── docker-compose.yaml        run both containers on your laptop
├── infra/
│   ├── inventory-stack.yaml   the whole AWS setup (Part 2)
│   └── github-oidc.yaml       lets GitHub deploy without passwords (Part 3)
└── .github/workflows/         deploy.yml and destroy.yml (Part 3)

The backend's four doors

RequestNeeds API key?What it does
GET /healthNoReturns {"status": "ok"}. Used by health checks to ask “are you alive?”
POST /chatYesRuns the agent on your message (plus history), logs it, returns the reply
GET /inventory/SKU001YesReturns one product's numbers (used by the Lookup SKU button)
POST /inventoryYesAdds or updates a product (“upsert” = update if it exists, insert if not)

Wrong or missing key gets 403 Forbidden. If OpenAI fails (wrong key, no credit), /chat returns 502 with the real reason in the message, so you see “Agent error (AuthenticationError…)” in the chat instead of a mysterious crash.

Settings come from environment variables

No setting is hard-coded. Each program reads its settings from environment variables, so the same image runs on your laptop and on AWS with different values.

VariableUsed byOn your laptopOn AWS it comes from
OPENAI_API_KEYbackend.env fileSSM Parameter Store, as a secret
API_KEYbackend and frontend.env fileSSM Parameter Store, as a secret (same value given to both)
OPENAI_MODELbackend.env filestack setting OpenAIModel
DB_PATHbackend/app/data/inventory.dbsame path, which sits on EFS
BACKEND_URLfrontendhttp://backend:8000http://backend.inventory-v1.local:8000

Why containers, and why the cloud

The “works on my machine” problem

Your laptop has Python 3.12, your friend's has 3.9, the server has something else, and one library behaves differently on each. A container image solves this by packing the app together with the exact Python version and libraries it needs into one sealed bundle.

On your laptop, docker compose up starts both containers and a named volume for the database. That already works. So why do we need AWS?

What changes when other people need to use it

Your laptop is closed at night, has no public address, and if it dies the database dies with it. To serve real users we need eight things. Each maps to one AWS service:

We need…On a laptopOn AWS
A place to store our imageslocal DockerECR (Elastic Container Registry)
Computers that run the containers 24/7your laptopECS on Fargate
A private network with locked doorsyour home Wi-FiVPC and security groups
One public address for userslocalhost:7860Application Load Balancer
A way for frontend to find backendDocker's name backendCloud Map private DNS
A disk that survives restartsDocker volumeEFS
A safe for passwords and keys.env fileSSM Parameter Store
A record of what happenedyour terminalCloudWatch Logs

Plus two things that tie it together: IAM roles (who is allowed to do what) and CloudFormation (build all of the above from one file, and delete it all in one go). The next section takes them one at a time.

The AWS building blocks, one by one

For every service: what it is, an analogy, exactly what it does in our project, what Azure calls it, and where you meet it in the real world.

Region and Availability Zones

What it is
A region is a geographic area where AWS has data centres, such as us-east-1 (North Virginia) or ap-south-1 (Mumbai). Each region has several Availability Zones (AZs): separate data-centre sites with their own power and networking.
Analogy
A region is a city. AZs are different neighbourhoods in that city, far enough apart that a power cut in one does not reach the other.
In our project
Everything lives in one region (default us-east-1). We use two AZs because the load balancer insists on at least two.
Real world
Payment and banking systems spread across AZs so one data-centre failure does not stop transactions.

VPC, subnets, internet gateway, route table your private network

What it is
A VPC (Virtual Private Cloud) is your own private network inside AWS. You choose its address range and split it into subnets. An internet gateway connects it to the internet, and a route table tells traffic which way to go.
Analogy
A gated housing society. The VPC is the compound wall, subnets are the towers inside, the internet gateway is the main gate, and the route table is the signboard at each junction saying “anything going outside: this way to the main gate”.
In our project
VPC 10.0.0.0/16 (65,536 addresses) split into two subnets, 10.0.1.0/24 and 10.0.2.0/24 (256 each), one per AZ. Both are public subnets: their route table sends 0.0.0.0/0 (everything not local) to the internet gateway.
Azure calls it
Virtual Network (VNet). The Azure guide's Container Apps environment created one for you behind the scenes.
What does 10.0.0.0/16 actually mean?

An IPv4 address is 32 bits, written as four numbers like 10.0.1.25. The /16 says the first 16 bits (10.0) are fixed and the remaining 16 bits are free, giving 216 = 65,536 addresses. A /24 fixes 24 bits (10.0.1), leaving 8 bits, so 256 addresses. Like a PIN code that narrows a city down to a neighbourhood: the longer the fixed part, the smaller the area. (AWS reserves 5 addresses in every subnet for itself.)

The VPC: two public subnets in two Availability Zones, one internet gateway Region us-east-1 Internet gateway VPC 10.0.0.0/16 AZ a: public subnet 10.0.1.0/24 AZ b: public subnet 10.0.2.0/24 ALB node task(s) EFS mounttarget ALB node task(s) EFS mounttarget Route table for both subnets: 10.0.0.0/16 → stay inside the VPC 0.0.0.0/0 → internet gateway
The load balancer places a node in each AZ. ECS starts tasks in either subnet. EFS has a “door” (mount target) in each AZ so a task can reach the disk wherever it runs.

Security groups the guards on every door

What it is
A firewall attached to each resource. By default nothing gets in. Each rule opens one port to one source. They are stateful: if a request is allowed in, its reply is automatically allowed out.
Analogy
An office building. Visitors may enter the lobby. Reception may call the meeting room. Only staff badges open the server room. Nobody walks from the street straight into the server room.
In our project
Four groups form a chain. Each rule names the previous group, not an IP address, so it stays correct even when tasks restart and get new IPs.
Azure calls it
Network Security Group, plus Container Apps' internal/external ingress setting.
Security group chain: internet to ALB on port 80, ALB to frontend on 7860, frontend to backend on 8000, backend to EFS on 2049 Internet ALB group Frontend group Backend group EFS group :80 :7860 :8000 :2049 allows port 80from anyone allows 7860 onlyfrom the ALB group allows 8000 onlyfrom the frontend group allows 2049from backend
Port 2049 is NFS, the protocol for network file systems. Outbound traffic (to OpenAI, ECR) is allowed by default.

ECR Elastic Container Registry

What it is
A private store for your container images, inside your AWS account.
Analogy
A private godown for your packed boxes. Or a Play Store that only you and your servers can download from.
In our project
Two repositories, inventory-backend and inventory-frontend. Each image has a tag like :v1, a label saying which version is inside. ECS pulls the images from here using an IAM role, not a password.
Azure calls it
Azure Container Registry (ACR). The Azure guide pulled images with ACR's admin password; on AWS no password is involved at all.

ECS and Fargate where the containers run

ECS (Elastic Container Service) has five words that confuse everyone at first. A cloud kitchen makes them stick.

In our project
Two services, each keeping one task running. Backend: 1 vCPU and 2 GB memory (the agent and libraries are heavier). Frontend: 0.5 vCPU and 1 GB.
Safe updates
When you ship a new image, the service starts the new task first, waits until it is healthy, then stops the old one: a rolling update with no downtime. If the new task keeps failing, the circuit breaker gives up and rolls back to the last working version.
Azure calls it
Azure Container Apps (one service that bundles the cluster, the load balancer and auto-scaling).
Real world
Fargate is popular for APIs, background workers and internal tools where teams do not want to manage servers.

Application Load Balancer the public front desk

What it is
A managed entry point with a public web address. A listener waits on port 80, and a target group holds the list of frontend tasks it may send visitors to.
Analogy
A hotel receptionist. Guests only ever meet reception. Reception knows which rooms are ready and checks on each one regularly (a health check). A room that does not answer is skipped.
In our project
Every 30 seconds it requests / from each frontend task. Two good answers in a row mean healthy; five failures mean unhealthy. The idle timeout is raised to 120 seconds because agent answers can take a while. A “sticky” cookie keeps a user on the same frontend copy, which matters once you run more than one.
Azure calls it
Container Apps external ingress.

Cloud Map private DNS the internal phone directory

What it is
A private DNS zone (inventory-v1.local) that only resolves inside the VPC. ECS registers every backend task's private IP under the name backend.
Analogy
An office intercom directory. You dial “Accounts”, not the extension of whoever is sitting at that desk today. Task IPs change at every restart; the name stays the same.
In our project
The frontend calls http://backend.inventory-v1.local:8000. From your laptop that name does not exist, which is the point.
Azure calls it
The internal address of a Container App with internal ingress.

EFS and the access point the disk that outlives containers

What it is
EFS (Elastic File System) is a network drive. Any task in the VPC can attach (“mount”) it. An access point pins a fixed folder and a fixed user identity for the app.
Analogy
A locker room outside the kitchen. Cooks come and go; the lockers stay. The access point is one locker with your name on it: it always opens on the same shelf (/inventorydb) and treats whoever opens it as the owner (user 1000), so permission errors never happen.
In our project
The backend mounts it at /app/data, and the database file is /app/data/inventory.db. Data is encrypted while travelling to EFS and while stored. Delete the backend task and the data is untouched.
Azure calls it
Azure Files share, linked to the Container Apps environment.
Real world
Shared storage for uploaded files, machine-learning model files, or content that several servers read.

SSM Parameter Store the safe for secrets

What it is
A key-value store in AWS Systems Manager. A SecureString parameter is encrypted with KMS (AWS's key service).
Analogy
A bank locker. You put the key in once. When a cook starts a shift, the manager (ECS) opens the locker with its own authorised badge and hands the key to the cook. The key is never written on the recipe card.
In our project
/inventory/openai-api-key and /inventory/api-key. ECS reads them at task start and gives them to the containers as environment variables. They never appear in the template, the task definition or the console.
Azure calls it
Container Apps secrets (or Key Vault).
Real world
Database passwords, payment-gateway keys, third-party API tokens.

IAM roles ID badges for software

What it is
IAM (Identity and Access Management) decides who may do what. A role is a set of permissions that a service can temporarily wear, with no password.
Analogy
A hotel key card. It opens your room and the gym, not other guests' rooms. This idea is called least privilege: give exactly the access needed, nothing more.
In our project
Two roles. The execution role is used by ECS itself before your code runs: pull the image from ECR, write logs, read the two secrets. The task role is worn by your running code: mount EFS and allow ECS Exec (a remote shell for debugging).
Azure calls it
Managed identity.

CloudWatch Logs the CCTV recorder

What it is
A store for log lines. Everything a container prints goes here.
Analogy
CCTV for your app. When something goes wrong at 2 a.m., you rewind the tape instead of guessing.
In our project
Two log groups, /ecs/inventory-v1/backend and /ecs/inventory-v1/frontend, kept for 7 days. You read them with aws logs tail.
Azure calls it
Log Analytics, read with az containerapp logs show.

CloudFormation the blueprint that builds and demolishes

What it is
You write a file describing the end result you want (a template). CloudFormation works out the order, creates everything, and records it as a stack. Deleting the stack deletes everything it created.
Analogy
Giving an auto driver every turn (“left here, right after the temple…”) is the Azure guide's approach: one command per resource. Typing the destination into Google Maps is CloudFormation: you say where, it works out how. The first style is called imperative, the second declarative.
In our project
infra/inventory-stack.yaml creates about 35 resources: network, guards, disk, cluster, roles, logs, DNS, load balancer and both services. One stack per version: inventory-stack-v1, -v2…
Azure calls it
A resource group (for grouping and deleting) plus ARM/Bicep templates (for describing).
Real world
This practice is called Infrastructure as Code. Teams keep templates in git, review changes like code, and can rebuild a whole environment for testing in minutes.

Follow one request through the system

Now put every block together. Step through what happens when Priya asks “Should I reorder SKU001?”. The highlighted boxes and wires show where the request is at each moment.

One question, end to end

Architecture of the inventory agent on AWS Browser to load balancer to frontend task to backend task inside a VPC. Backend calls OpenAI and reads SQLite on EFS. ECR, SSM Parameter Store and CloudWatch Logs sit outside the VPC. VPC inventory-v1 BrowserPriya's laptop Load balancerpublic, port 80 Frontend taskGradio, port 7860 Private DNSbackend.inventory-v1.local Backend taskFastAPI, port 8000LangChain agent + tools EFS disk/app/data/inventory.db OpenAI APIgpt-4o-mini AWS services outside your VPC ECRyour images SSM Parameter Storethe two secrets CloudWatch Logseverything printed

Most of the few seconds Priya waits are spent at OpenAI, three times. Everything inside AWS takes milliseconds.

Design decisions and their trade-offs

Every architecture is a set of choices. Being able to say why, and when you would choose differently, is what interviewers and clients actually test.

Public subnets, no NAT gateway

Choice: tasks sit in public subnets with a public IP, so they can reach OpenAI and ECR directly. Why: the usual alternative, a NAT gateway, costs about $1 a day before any traffic, which would double the cost of a classroom demo. Is it safe? Yes for this purpose: having a public IP does not mean anyone can connect, because the security groups allow no inbound traffic except from the previous hop. In production: put tasks in private subnets with a NAT gateway or VPC endpoints, so they have no public address at all. Defence in depth.

SQLite on EFS instead of a database server

Choice: keep the original SQLite file, stored on EFS. Why: zero administration, almost zero cost, and no code changes. Limit: SQLite allows one writer at a time, and network file systems make that slower. Fine for a class, not for 50 people updating stock at once. In production: Amazon RDS (PostgreSQL) or DynamoDB. Only db_client.py would change, because every database call already lives in that one file.

One stack per version

Choice: v1 and v2 are completely separate stacks, each with its own network, disk and URL. Why: you can test v2 while v1 keeps serving users, then delete v1 in one command. If v2 is broken, nothing is lost. This is a simple form of blue/green deployment. Trade-off: each version gets a fresh, empty-ish database (only sample data). For real data you would keep the database outside the versioned stack.

The backend has no public door, and still checks a key

Choice: the backend is unreachable from the internet and requires an API key. Why: two independent locks. If someone misconfigures a security group one day, the key still stops strangers. Security people call this defence in depth.

Health check written in Python, not curl

The original setup checked health with curl, which is not installed in the slim Python image. The check would fail forever, and the platform would keep killing perfectly healthy containers. It is like a security guard whose ID scanner is unplugged: every employee “fails”. We use Python's built-in urllib, which is always there.

Images built for linux/amd64

Apple Silicon Macs (M1 to M4) build ARM images by default. Our Fargate tasks run on x86 processors, and an ARM image there fails with exec format error, much like an Android app refusing to install on an iPhone. The --platform linux/amd64 flag builds for the right processor on any laptop.

HTTP, not HTTPS

Choice: the load balancer serves plain HTTP. Why: HTTPS needs a domain name and a certificate, which learners may not have. Consequence: do not type anything sensitive into the demo. In production: a free certificate from AWS Certificate Manager on the load balancer, and redirect HTTP to HTTPS.

Azure to AWS: what changed and why

Most of the move is renaming. A few differences are real and worth teaching.

IdeaAzure versionAWS version
Group of everything for one versionResource groupCloudFormation stack
Image storeACR, pulled with an admin passwordECR, pulled with an IAM role
Where containers runContainer Apps environmentVPC + ECS cluster on Fargate
Backend reachable only internally--ingress internalCloud Map name + security group
Frontend public--ingress externalApplication Load Balancer
Persistent diskStorage account + file share, linked by a REST callEFS + access point, in the template
SecretsContainer Apps secretsSSM Parameter Store
Language modelGroq, Llama 3.3OpenAI, gpt-4o-mini
Delete everythingaz group deleteaws cloudformation delete-stack

Four differences that are not just new names

  1. Commands versus a blueprint. The Azure guide runs about ten commands in a careful order, including a hand-written REST call to attach the disk. On AWS one template describes the end state and CloudFormation handles the order. Fewer chances to skip a step.
  2. Scale to zero. Azure Container Apps can stop when idle and wake up on the next request. ECS services do not wake on their own: you set the number of running copies yourself (Part 2, Step 10). In exchange, the first request is never slow.
  3. No passwords for image pulls. Azure fetched the registry's admin password and handed it to the app. On AWS, the execution role gives ECS permission directly; there is no password to leak.
  4. Switching AI providers took two lines. Because LangChain hides each provider behind the same interface, moving from Groq to OpenAI was this change in agent.py:
- from langchain_groq import ChatGroq
- llm = ChatGroq(model="llama-3.3-70b-versatile", ...)
+ from langchain_openai import ChatOpenAI
+ llm = ChatOpenAI(model=os.getenv("OPENAI_MODEL", "gpt-4o-mini"), ...)

Security, layer by layer

Airport security is a good model: no single check is perfect, so there are several in a row.

AirportOur system
Only the terminal entrance is open to the publicOnly the load balancer accepts traffic from the internet, only on port 80
Staff-only doorsSecurity groups: each hop accepts traffic only from the hop before it
Boarding pass checkThe backend refuses any request without the right X-API-Key
Passports kept in the safeKeys stored encrypted in SSM, handed over only at start-up
Staff ID cards that open specific doorsIAM roles with only the permissions each part needs
Sealed luggageEFS data encrypted in transit and at rest
CCTVCloudWatch Logs of every container

What it costs, and how to control it

Cloud bills feel mysterious until you see that each line is just rate × time or rate × usage. Here are the meters that run for this project (AWS us-east-1 and OpenAI list prices, November 2026):

MeterRateRuns when
Fargate CPU$0.04048 per vCPU per hourtasks are running
Fargate memory$0.004445 per GB per hourtasks are running
Load balancer$0.0225 per hour, plus a tiny usage chargethe stack exists
Public IPv4 address$0.005 per address per hour2 for the load balancer always, 1 per running task
Private DNS zone$0.50 per month (charged for the month, not by the day)the stack exists
EFS, ECR, logsa few centstiny for this app
OpenAI gpt-4o-mini$0.15 per million input tokens, $0.60 per million outputeach question

Worked example: the backend for three days

Backend = 1 vCPU + 2 GB. Per hour: 1 × $0.04048 + 2 × $0.004445 = $0.04937. For 72 hours: $0.04937 × 72 = $3.55. The frontend (0.5 vCPU, 1 GB) works out to $0.0247 an hour, or $1.78 for three days.

Worked example: one question to the agent

Each question makes about 3 calls to OpenAI (remember the agent loop). Each call sends the system prompt, the tool descriptions, the conversation and the tool results: roughly 800 tokens in, plus a short reply. Call it 2,500 input tokens and 200 output tokens per question:

2,500 × $0.15 ÷ 1,000,000 + 200 × $0.60 ÷ 1,000,000 ≈ $0.0005 per question. A thousand questions cost about 50 cents. The language model is the cheapest part of this project; the always-on infrastructure is what you pay for.

Cost calculator

Move the sliders to see what a class, a workshop or a forgotten stack would cost.

ItemCost (USD)
Total

Three ways to stop paying

From classroom demo to production

The architecture is real; a few demo shortcuts would need upgrading before real users rely on it.

Demo choiceProduction upgradeWhy
HTTP onlyHTTPS with an AWS Certificate Manager certificateNobody can read or alter traffic
No loginAmazon Cognito or your company's sign-in on the load balancerOnly staff can use it; usage is traceable to a person
Public subnetsPrivate subnets with a NAT gateway or VPC endpointsContainers have no public address at all
SQLite on EFSAmazon RDS (PostgreSQL)Many writers, backups, point-in-time restore
One copy of each serviceAuto-scaling on CPU or request count, at least two copiesSurvives a task or AZ failure; handles peaks
Manual commandsCI/CD pipeline (Part 3)Every change deployed the same tested way
Logs onlyMetrics, alarms and agent tracing (Container Insights, LangSmith or OpenTelemetry)Know about problems before users complain; see each tool call
Single shared session ID in the frontendOne session ID per browser userConversations in the log can be told apart

Where this same pattern shows up

“Chat page → API → agent with tools → company data” is one of the most common shapes of AI product being built right now. Swap the tools and you get:

  • An HR policy assistant with a tool that searches the leave policy and another that checks an employee's leave balance.
  • An IT helpdesk agent that looks up ticket status and resets a password after confirmation.
  • A logistics assistant that tracks a shipment and estimates delivery from live traffic data.
  • A sales assistant that pulls a customer's order history from the CRM before a call.
  • A clinic front-desk bot that checks a doctor's free slots and books an appointment.

The AWS part you are about to deploy is identical for all of them. That is why it is worth learning properly once.

Check your understanding

Click an answer. The explanation appears after your first choice.

1. The backend task crashes and ECS starts a new one. What happens to the products in inventory.db?

The database file sits on the EFS network drive mounted at /app/data. Containers come and go; the locker room stays. Only deleting the stack deletes EFS.

2. A learner runs curl http://backend.inventory-v1.local:8000/health from their laptop and it fails. Why?

Two locks at once: private DNS (the name does not resolve outside the VPC) and the backend security group (only the frontend group may connect). /health needs no API key. This is intended behaviour.

3. Which role lets ECS read the OpenAI key from Parameter Store before your Python code even starts?

The execution role is ECS's own badge for setup work: pull the image, write logs, fetch secrets. The task role is what your running code wears.

4. The agent replies “Reorder 55 units of SKU002”. About how many OpenAI calls did that take?

Round 1 asks for lookup_inventory, round 2 asks for calculate_reorder, round 3 writes the answer. Six is only the safety limit.

5. You set both services to zero running tasks overnight. What are you still paying for?

Stopping tasks turns the engine off, but the parking spot (load balancer and friends) still bills, roughly $1 a day. Delete the stack to stop that too.

6. A learner on an M3 MacBook skips --platform linux/amd64. What do they see?

The image builds fine for ARM on the Mac, but Fargate runs our tasks on x86 processors, which cannot execute ARM programs.

7. Fifty store managers will update stock at the same time. What is the first thing you change?

SQLite allows one writer at a time, and it is slower over a network drive. A database server handles many concurrent writers. Only db_client.py changes.

8. Why does the backend check an API key if the internet cannot reach it anyway?

Independent layers mean one mistake does not become a breach.

Glossary

Agent
A program where a language model decides which steps (tools) to take to answer a question.
Tool calling
The model replies with a structured request to run a named function; your code runs it and returns the result.
Token
A piece of text, roughly ¾ of an English word. Models are billed per token.
SKU
Stock-keeping unit: one product code in the inventory.
Lead time
Days between placing an order and receiving it.
Safety stock
Extra units kept as a cushion against surprises.
Reorder point
The stock level at which you should place a new order.
Container image
A sealed package of an app plus everything it needs to run.
Container
A running copy of an image.
Registry
A store for images (ECR on AWS).
Tag
A label on an image version, such as v1 or a commit ID.
Cluster
A named grouping of ECS services.
Task definition
The recipe for running a container: image, CPU, memory, settings, secrets, volumes.
Task
One running instance of a task definition.
Service
Keeps the desired number of tasks running and connects them to the load balancer or DNS.
Desired count
How many tasks a service should keep running.
Fargate
Runs ECS tasks without you managing any servers.
Rolling update
Start new tasks, wait until healthy, then stop old ones.
Circuit breaker
Stops a failing deployment and rolls back automatically.
VPC
Your private network inside AWS.
Subnet
A slice of the VPC's addresses, inside one Availability Zone.
CIDR
Notation for an address range, such as 10.0.0.0/16.
Internet gateway
Connects a VPC to the internet.
Route table
Rules for where network traffic goes.
Security group
A stateful firewall on a resource: which ports, from whom.
Load balancer
A public entry point that forwards requests to healthy targets.
Target group
The list of places a load balancer can send traffic, with health checks.
Health check
A regular “are you alive?” request.
DNS
The system that turns names into IP addresses.
EFS
A managed network file system.
Access point
An EFS entry with a fixed folder and user identity.
Mount
Attaching a disk to a folder path inside a container.
SSM Parameter Store
AWS's store for settings and encrypted secrets.
KMS
AWS Key Management Service, which holds the encryption keys.
IAM role
A set of permissions that a service can assume without a password.
Least privilege
Give only the permissions that are needed.
CloudFormation
AWS's Infrastructure-as-Code service.
Stack
Everything one CloudFormation template created, managed as one unit.
Idempotent
Safe to run twice: the second run changes nothing. Like pressing a lift button again.
Stateless
The server keeps no memory between requests; the client sends what is needed each time.
Defence in depth
Several independent security layers, so one failure is not a breach.

Ready? Part 2 walks you through the deployment, one command at a time.