From One Hand-Built EC2 Box to Containers, Terraform and Autoscaling: What Each Fix Replaces
A server set up by hand works until you need a second one, a changed one, or a busy hour. Three fixes: a container image (214 MB, runs the same anywhere), a Terraform file that writes the setup down (24 waiting jobs: 6 workers; 80: capped at 8; 0: floor of 1), and a scaling rule on backlog per worker that needs a shared queue.
What you will learn
- Name the three gaps in a server set up by hand
- Build a small job API into a container image and run it
- Write worker capacity as a Terraform plan: waiting jobs over a target backlog, between a floor and a ceiling
- Explain why autoscaling workers needs a shared queue first
Before you start
- Running a Docker Compose app on one EC2 instance
- Docker basics
The EC2 deployment was built by hand: create the instance, install the app, run it. That leaves three questions. Is the app the same on every machine? Is the machine written down anywhere? Does it grow when the work grows? Each question has a fix, and each fix replaces something you typed by hand.
A small kitchen
One cook, one counter, and the orders pile up. That's the one EC2 box. First, a sealed kit with the recipe and ingredients inside: any kitchen that opens it cooks the same dish. That's a container. Second, the plan of the kitchen on paper, so opening another one is a copy. That's Terraform. Third, when the queue gets long more cooks join, and when it's quiet they go home. That's autoscaling.
The little app we move
A stand-in for the subtitle generator: jobs wait in a list in memory, nothing is transcribed. What matters is the container and the number of waiting jobs.
from fastapi import FastAPI
app = FastAPI(title="subtitle-api")
JOBS: list[dict] = []
@app.get("/health")
def health():
return {"status": "ok"}
@app.post("/jobs")
def submit(file: str):
job = {"id": len(JOBS) + 1, "file": file, "status": "waiting"}
JOBS.append(job)
return job
@app.get("/metrics")
def metrics():
waiting = sum(1 for j in JOBS if j["status"] == "waiting")
return {"waiting_jobs": waiting}
/metrics counts the jobs still waiting. A scaler can watch that number.
Fix 1: a container
FROM python:3.13-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py .
EXPOSE 8000
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
It starts from a base image that already has Python 3.13, so you don't install Python by hand like on EC2. pip install becomes a layer Docker keeps, so it runs once. The code is copied last: when only app.py changes, only the top layer is rebuilt. The build took 10.5 seconds here:
IMAGE ID DISK USAGE CONTENT SIZE
subtitle-api:s03l03-1 037dd1d4015b 214MB 52.2MB
About 214 MB, with Python, the packages and the code inside. docker run maps port 8000 on the machine to port 8000 inside. Then three jobs and a metrics call:
{"status":"ok"}
{"id":1,"file":"lecture1.mp4","status":"waiting"}
{"id":2,"file":"lecture2.mp4","status":"waiting"}
{"id":3,"file":"lecture3.mp4","status":"waiting"}
{"waiting_jobs":3}
Any machine with Docker runs this image the same way, cloud included. More on images and layers is in containerising a model API.
Fix 2: Terraform writes it down
Terraform writes a setup down in a file. This one has no cloud in it, so it only does the arithmetic for the workers:
locals {
# Teaching inputs, not observed service times or production settings.
average_job_seconds = 30
waiting_budget = 120
target_backlog = local.waiting_budget / local.average_job_seconds
worker_floor = 1
worker_ceiling = 8
recommended_workers = min(
local.worker_ceiling,
max(local.worker_floor, ceil(var.waiting_jobs / local.target_backlog)),
)
}
A job takes about 30 seconds and nobody should wait more than 120. Both are teaching numbers, not measurements. 120 over 30 is 4, so each worker holds at most 4 waiting jobs. Waiting jobs over 4 gives the worker count, kept between a floor of 1 and a ceiling of 8. The variable also has a validation rule, so 2.5 waiting jobs fails with "Use a nonnegative whole number of waiting jobs."
With Terraform v1.17.2, fmt passed and validate said "Success! The configuration is valid." Then three plans:
Changes to Outputs:
+ capacity_review = {
+ backlog_per_worker = 12
+ recommended_workers = 6
+ running_workers = 2
+ target_backlog = 4
+ waiting_jobs = 24
}
Eighty jobs over 4 is 20, but the ceiling stops it at 8. Zero jobs over 4 is 0, but the floor keeps 1 warm worker. Compare two workers holding twelve jobs each, about 360 seconds of waiting, with six workers holding four each, 120. These plans only print outputs; nothing is created anywhere. A full module with providers is in Terraform: one module, two providers.
Fix 3: autoscaling on the backlog
On AWS the same idea looks like this. It was written for the lecture but not applied or validated, because it needs an AWS account, a cluster, a task definition and a network. It shows the shape only:
resource "aws_appautoscaling_target" "worker" {
service_namespace = "ecs"
scalable_dimension = "ecs:service:DesiredCount"
resource_id = "service/main/subtitle-worker"
min_capacity = 1
max_capacity = 8
}
resource "aws_appautoscaling_policy" "backlog" {
name = "backlog-per-worker"
policy_type = "TargetTrackingScaling"
...
target_tracking_scaling_policy_configuration {
target_value = 4
customized_metric_specification {
namespace = "SubtitleApp"
metric_name = "BacklogPerWorker"
statistic = "Average"
}
}
}
The worker service gets a minimum of 1 and a maximum of 8, and the policy keeps 4 waiting jobs per worker, the same 4 calculated above. That metric isn't built in: the app has to publish it from its waiting jobs number. Why scaling on the queue beats scaling on CPU is in sizing and autoscaling an inference service, and the full route onto ECS is in deploying a model API to AWS Fargate.
What this doesn't do
- The jobs live in memory. A second container has its own list. Three jobs went to the first container, and the second one, on port 8001, said
{"waiting_jobs":0}. Scaling out needs a shared queue first, like the Redis broker used with Celery. - The backlog metric is yours to publish.
- Thirty seconds a job is a guess. Measure real media durations first.
Quick recap
| Question | Fix | Replaces |
|---|---|---|
| Same on every machine? | A container image | Installing Python and packages by hand |
| Written down? | A Terraform file, checked with plan | Clicking through the console |
| Grows with the work? | Waiting jobs over 4, between 1 and 8 | Guessing the server size |
And before you scale out, give the jobs a shared home.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
The Python Architect Masterclass: Full Stack to AI Engineer
Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)Related posts
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.
