Who it is for: data and ML engineers who want to take one AI agent from notebooks to a deployed, tested service on AWS.
Part 1 · A Cost-Safe Plan, Cleansing Rules as Data and Event-Driven Glue
Chapter 1
Project Design and a Cost-Safe Plan
What you will learn
- How to pick a project that exercises every layer of a real AI system.
- How to split the AWS work into parts you can build, prove and remove one at a time.
- How to keep a personal AWS account safe and cheap before you write a single resource.
- How to set up Terraform state, budgets and a local lab that mirrors "on-premise".
The project: NovaNutri
NovaNutri turns one photo of a meal into:
- The foods on the plate and their grams (a vision model).
- A corrected plate (a person, or measured data, fixes the model's guess).
- Nutrition totals, calculated by code from reference tables, never by a language model.
- An idea for the next meal from two language models side by side, each sentence checked against the plate's numbers and cited guideline passages.
Why this project works as a teaching example: it needs a data pipeline, a trained model, retrieval, an agent with tools, a web service and a public demo. Each of those maps to a family of AWS services, so one project walks you through the whole cloud lifecycle in the order a real company follows.
Data used:
| Source | Use | License |
|---|---|---|
| Nutrition5k (Google Research) | Overhead plate photos, ingredients and weighed grams | CC BY 4.0 |
| USDA FoodData Central | Sodium, sugars, saturated fat and fiber per food | CC0 |
| Dietary Guidelines for Americans 2025-2030, FDA label pages | 42 passages for guideline retrieval | U.S. government works |
The scenario
Tell a story your architecture can follow. NovaNutri plays a company that keeps plate photos in its own on-premise storage and moves to the cloud:
- An on-premise image repository receives new photos and records every day (the downloaded dataset, replayed day by day).
- Apache Airflow on an on-premise server (a VM) cleans each day and lands it in Amazon S3.
- The cloud data platform turns each day into query-ready tables.
- Model development trains, evaluates and registers the vision model.
- The agent answers requests using its own tools.
- A service and a web demo make it usable.
Split the AWS work into five parts
| Part | Goal | Main AWS services |
|---|---|---|
| 1. Foundation | A safe account and Terraform base | IAM, Budgets, Cost Anomaly Detection, S3 (state) |
| 2. Data pipeline | Daily data into query-ready tables | S3, EventBridge, Step Functions, Glue (Iceberg, Data Quality), Athena |
| 3. Model development | Reproduce and register the model | SageMaker Pipelines, Processing, Training, Model Registry |
| 4. Agent | Tools, retrieval and grounding | Bedrock (two models, Knowledge Base, Guardrail), Aurora PostgreSQL Serverless v2 |
| 5. Deployment and demo | A service and a public page | ECR, ECS Fargate, API Gateway, Cognito, CloudFront, WAF, EKS, GitHub Actions |
Rule for every part: build and test it locally first, then build it in AWS with Terraform, run it, capture screenshots as proof, and destroy what you no longer need. This is "local first, cloud as proof". It keeps the bill tiny and forces every part to be reproducible from code.
Decide the honest labels up front
Write down, before you build, what you will and will not claim. In NovaNutri:
- The final vision model was trained locally on CPU. SageMaker reproduces it at small scale and registers it. Do not call it "trained on SageMaker".
- The agent is a workflow whose order is set by code, with one agentic step (the models choose their tools). Do not call it fully autonomous.
- The model is evaluated once on an untouched test split and that error is published, even though the demo shows chosen samples.
These labels end up on the demo page, in the reports and in interviews. Deciding them first avoids rewriting later.
Make the account safe before anything else
Step by step:
- Turn on MFA for the root user and stop using root for daily work.
- Create an admin IAM user (or Identity Center user) with MFA for console work.
- Use short-lived CLI credentials. With AWS CLI 2.32 or later,
aws loginsigns in through the console and gives temporary credentials (up to 12 hours), so no access keys live on your disk. On a VM without a browser useaws login --remote. - Create a monthly budget with an email alert (NovaNutri used 10 dollars) and turn on Cost Anomaly Detection.
- Pick one region for everything (NovaNutri used us-east-2) and check the price list for every service before you write it.
Terraform layout and state
Keep one Terraform folder per part so each can be applied and destroyed on its own:
infra/terraform/
base/ # nothing but the backend check
part2/ part3/ part4/ part5/ part5_eks/ web/
Store state in an S3 bucket created outside Terraform, with versioning on and public access blocked. Each part uses its own key:
terraform {
backend "s3" {
bucket = "your-state-bucket"
key = "terraform/part2/terraform.tfstate"
region = "us-east-2"
use_lockfile = true # S3 native locking, no DynamoDB table needed
}
}
Tip from the project: if your repository sits in a folder shared with a VM (VirtualBox shared folders have no execute bit), put Terraform's working data on the VM disk with TF_DATA_DIR=~/.tfdata/<part>. Otherwise provider binaries fail to run.
Parts that depend on another read its outputs with terraform_remote_state (the deployment stack reads the agent stack), so you apply in order and destroy in reverse.
A local lab that plays "on-premise"
NovaNutri used a Vagrant VM (Ubuntu) with Docker, Terraform and the AWS CLI. On it:
- PostgreSQL 17 with pgvector for local development.
- Apache Airflow 3 as systemd services (no Docker needed).
- The official AWS Glue Docker image to test Spark jobs before paying for Glue.
The laptop runs notebooks and the web front end. Everything the cloud does is first proven here.
A cost check habit
Before every part, write a short table: service, unit price, expected usage, expected cost. After the part, record the estimate again from what actually ran. NovaNutri's parts each stayed under about one to two dollars:
| Part | Estimate |
|---|---|
| 2. Data pipeline | about $0.12 |
| 3. Model development | about $0.45 |
| 4. Agent | under $1 |
| 5. Deployment and demo | about $1 to $2 |
The bill is the final record; the estimates keep you honest while you build.
Checklist for the foundation
- ☐ Root MFA on, daily admin user with MFA.
- ☐
aws loginworks on your laptop and VM; no access keys on disk. - ☐ Budget alert and Cost Anomaly Detection on.
- ☐ State bucket with versioning and blocked public access.
- ☐ One Terraform folder per part, each with its own state key.
- ☐ Honest labels written down.
Chapter 2
From On-Premise Airflow to Iceberg Tables
What you will build
ON-PREMISE (VM) AWS
Image repository S3 raw zone raw/<source>/dt=YYYY-MM-DD/
-> Airflow DAG (daily, 00:00 UTC) -> _SUCCESS written last
extract -> SQL transform + cleansing -> EventBridge rule (Object Created, key ends in _SUCCESS)
-> 9 quality checks -> export + manifest -> Step Functions parent -> child (per source)
-> upload, check sizes, write _SUCCESS -> Glue 6.0 job: Iceberg tables + Data Quality
-> Athena count check against the manifest
You will learn: a SQL ETL with versioned cleansing rules, a completion marker pattern, event-driven orchestration with Step Functions (JSONata, no Lambda), Glue writing Apache Iceberg, and how to make every step safe to rerun.
The on-premise side: Airflow plus SQL
Airflow 3.3 runs on the VM as systemd services. The DAG nutrition5k_daily_ingest replays one capture day per run:
@dag(schedule=CronTriggerTimetable("0 0 * * *", timezone="UTC", interval=timedelta(days=1)),
catchup=False, max_active_runs=1, ...)
def nutrition5k_daily_ingest():
create_schema = SQLExecuteQueryOperator(task_id="create_schema", conn_id=CONN_ID,
sql=["00_schema.sql", "05_dq_rules.sql", "06_amount_baseline.sql"])
# find_batch -> extract_to_staging -> transform_sql -> quality_checks
# -> export_tables -> collect_photos -> land_partition -> upload_to_s3 -> mark_success
The cleaning logic lives in PostgreSQL, in three schemas:
| Schema | Holds |
|---|---|
| staging | the day's lines exactly as extracted (never changed) |
| curated | typed, checked dishes and ingredients |
| ops | quarantine, load audit, cleansing rules, fix log |
The transform runs in one transaction: de-duplicate with ROW_NUMBER(), turn wide lines into rows with CROSS JOIN LATERAL, apply structure checks and the cleansing rules, then MERGE into curated (insert, update and delete in one statement). Nine SQL quality checks must return zero failures, or the run stops before anything leaves the database.
Cleansing is a decision, not a filter
While checking the cloud tables, the highest-calorie dishes were impossible (9,170 kcal from 7,974 g of olives). Instead of adding one rule for one outlier, profile the raw data first (completeness, validity, consistency, plausibility, uniqueness) and let a person decide an action per problem. Store the decisions as data:
INSERT INTO ops.dq_rule (rule_id, priority, dimension, description, action, allowed_actions, threshold,
decided_by, decided_on, reason)
VALUES
('R2_huge_ingredient', 10, 'Plausibility', 'Ingredient grams or scale total above the threshold (g)',
'quarantine', ARRAY['quarantine','flag','keep'], 2000, 'sungwon', DATE '2026-11-10',
'7,974 g is an error value of the recording system ...'),
('R4_empty_name', 40, 'Completeness', 'Ingredient name empty; fill it from the reference table by id',
'fix', ARRAY['fix','quarantine'], NULL, 'sungwon', DATE '2026-11-10', '...'),
('R6_fish_reference', 60, 'Consistency', 'Reference kcal per gram below half of its own Atwater value (fish)',
'flag', ARRAY['flag','keep'], 0.5, 'sungwon', DATE '2026-11-10', '...')
ON CONFLICT (rule_id) DO UPDATE SET action = EXCLUDED.action, threshold = EXCLUDED.threshold, reason = EXCLUDED.reason;
The final rule set:
| Rule | Problem | Action |
|---|---|---|
| R1 | Scale total and ingredient sum differ | Quarantine |
| R2 | Any value above 2,000 g | Quarantine |
| R3 | Ingredient named "deprecated" | Quarantine |
| R4 | Empty ingredient name with a valid id | Fix (logged before and after) |
| R5 | Empty plate | Quarantine |
| R6 | Reference kcal far below its own macros (fish) | Flag |
| R7 | Grams far from the usual amount (robust z above 5) | Flag |
Why it matters: a pure statistical outlier rule would have deleted believable portions (a 136 g waffle) and about 6 percent of the training photos. Because the SQL reads the rule table, changing a decision changes the pipeline without a code change, and a CHECK constraint refuses an action the SQL cannot carry out. Every fix is logged; flags travel with the dish to S3 and Iceberg.
Landing: write the completion marker last
The load task copies CSV exports and photos (checksums verified), writes a manifest.json with counts and SHA-256 values, uploads everything, checks every size, and only then writes _SUCCESS:
@task
def mark_success(landed: dict) -> None:
"""Write _SUCCESS last (downstream starts only when it exists) and record the run in ops.load_audit."""
(Path(landed["target"]) / "_SUCCESS").touch()
S3Hook(aws_conn_id=AWS_CONN_ID).load_bytes(b"", key=prefix + "_SUCCESS", bucket_name=bucket, replace=True)
A half-loaded day can never start the cloud side. Airflow reaches AWS with an IAM user allowed to write only the raw prefix of the lake bucket, stored as an Airflow connection, never in code. (IAM Roles Anywhere is the stronger option for a real on-premise server.)
EventBridge starts the workflow only for complete days
Turn on EventBridge notifications for the bucket, then match only the marker:
resource "aws_cloudwatch_event_rule" "raw_success" {
name = "novanutri-raw-success"
event_pattern = jsonencode({
source = ["aws.s3"]
detail-type = ["Object Created"]
detail = {
bucket = { name = [aws_s3_bucket.lake.bucket] }
object = { key = [{ wildcard = "raw/*/dt=*/_SUCCESS" }] }
}
})
}
Step Functions with JSONata, no Lambda
A parent state machine routes each source to its own child (so a second source is a new child, not a bigger workflow). The Nutrition5k child: check the input, read the manifest with an AWS SDK integration, run the Glue job and wait, count rows with Athena, compare with the manifest, and fail by name if anything differs.
"RunGlueJob": {
"Type": "Task",
"Resource": "arn:aws:states:::glue:startJobRun.sync",
"Arguments": { "JobName": "${glue_job}", "Arguments": { "--dt": "{% $dt %}" } },
"Retry": [{ "ErrorEquals": ["Glue.ConcurrentRunsExceededException"],
"IntervalSeconds": 60, "MaxAttempts": 5, "BackoffRate": 2 }],
"Catch": [{ "ErrorEquals": ["States.ALL"], "Next": "GlueFailed" }],
"Next": "CountRows"
},
"CompareWithManifest": {
"Type": "Choice",
"Choices": [{ "Condition": "{% $actual.clean = $expected.clean and $actual.quarantined = $expected.quarantined and $actual.photos = $expected.photos %}",
"Next": "Loaded" }],
"Default": "CountMismatch"
}
The retry on ConcurrentRunsExceededException lets several days arrive at once: each Glue run waits its turn.
Glue 6.0 writes Iceberg, safely rerunnable
Build the job in the official Glue 6.0 Docker image on your VM first (free), then deploy the same script. Key choices:
spark.sql(f"""CREATE TABLE IF NOT EXISTS {CATALOG}.{DATABASE}.{table} (...)
USING iceberg PARTITIONED BY (dt)
TBLPROPERTIES ('format-version' = '2', 'write.format.default' = 'parquet')""")
...
df.select(*columns).writeTo(f"{CATALOG}.{DATABASE}.{table}").overwritePartitions()
- Eight Spark checks compare every count with the day's manifest before any write.
- Glue Data Quality evaluates a ruleset (including the 2,000 g limit again) and publishes results.
overwritePartitions()replaces only the days it reads, so running a day again changes nothing.- Athena needs Iceberg format version 2; set it explicitly.
- An Athena workgroup stops any query above 100 MB scanned.
Results
| Check | Result |
|---|---|
| History load (35 days) and daily runs (5 days) | all succeeded, about 25 s each |
| Glue history load (36 days, one run) | 1 min 29 s; Data Quality 6 of 6 |
| Event-driven runs (one day, then three at once) | 4 of 4; counts equal every manifest |
| Cleansing over all 94 days | 4,665 kept (254 flagged, 1 fixed), 103 quarantined |
| Cost of the part | about $0.12 |
Lessons
- Write the completion marker last; downstream never sees a half day.
- Make every step rerunnable:
MERGEin SQL, partition overwrite in Glue, replace-the-day uploads. - Develop cloud jobs locally first; the Glue Docker image finds problems for free.
- Keep least privilege per role: EventBridge may start only the parent, the parent only the child, the child only this Glue job and workgroup.
Next: Part 2 trains the model on this data and reproduces it with SageMaker Pipelines.
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.