What the Architecture Covers
Network
A VPC with public and private subnets across two availability zones; only the load balancer is public.
Compute
Docker containers on ECS or EC2 behind an Application Load Balancer, with health checks and auto scaling.
Data
RDS PostgreSQL with automated backups and a read replica, plus ElastiCache Redis for caching and queues.
Storage and delivery
S3 for files and exports, CloudFront for static assets, Route 53 for DNS and HTTPS everywhere.
Security
Least-privilege IAM roles, secrets in a managed secrets store and security groups that only open what is needed.
Visibility
CloudWatch logs, metrics and alarms, so problems surface before users notice them.
How the pieces fit
The layout is one VPC spread across two availability zones. Each zone has a public subnet for the load balancer and a NAT gateway, a private subnet for the application containers and a private data subnet for RDS and ElastiCache. Only the Application Load Balancer accepts traffic from the internet. A request flows like this:
- 1DNS and TLS. Route 53 points the API domain at the ALB with an alias record. The ALB terminates HTTPS with a certificate from AWS Certificate Manager, and port 80 only redirects to 443.
- 2Static assets. CloudFront serves static files from a private S3 bucket through Origin Access Control, so the bucket itself is never public.
- 3Routing. The ALB forwards requests to a target group of ECS tasks on Fargate in the private subnets, and only to targets that pass the health check.
- 4Secrets. When a task starts, ECS reads the database URL and API keys from Secrets Manager and injects them as environment variables. Nothing secret is baked into the image.
- 5Data. The application talks to RDS PostgreSQL and ElastiCache in the data subnets. Security groups allow ports 5432 and 6379 only from the application's security group.
- 6Files. Uploads and exports go to S3 using the task's IAM role, and users download them through short-lived presigned URLs.
- 7Outbound traffic. Calls to third-party APIs leave through the NAT gateway in the task's zone. VPC endpoints for S3, ECR, Secrets Manager and CloudWatch Logs keep AWS API traffic off the NAT gateway.
- 8Visibility. Container logs go to CloudWatch Logs through the
awslogsdriver, and CloudWatch alarms watch the load balancer, the service and the database.
The same layout works with EC2 instances in an Auto Scaling group instead of Fargate. EC2 gives more control over the hosts, at the cost of patching and sizing them yourself.
The container image
FROM python:3.12-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app
RUN useradd --create-home --uid 10001 appuser
USER appuser
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "2", "--proxy-headers", "--forwarded-allow-ips", "*"]Dependencies install before the code is copied, so Docker reuses that layer when only application code changes. The process runs as a non-root user and logs to stdout. Trusting forwarded headers from any address lets Uvicorn see the original HTTPS scheme and client IP from the ALB, which is safe here only because the security group admits traffic from the load balancer and nothing else. Each task runs a couple of workers, and capacity grows by adding tasks.
Health checks that do not cause outages
from fastapi import FastAPI, Response, status
from sqlalchemy import text
from app.cache import redis_client # redis.asyncio.Redis
from app.db import engine # SQLAlchemy AsyncEngine
app = FastAPI()
@app.get("/health/live")
async def live() -> dict:
return {"status": "ok"}
@app.get("/health/ready")
async def ready(response: Response) -> dict:
checks = {}
try:
async with engine.connect() as conn:
await conn.execute(text("SELECT 1"))
checks["postgres"] = "ok"
except Exception:
checks["postgres"] = "error"
try:
await redis_client.ping()
checks["redis"] = "ok"
except Exception:
checks["redis"] = "error"
if "error" in checks.values():
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
return checksThe ALB health check points at /health/live, which only proves the process can answer. If it checked the database too, a short RDS failover would mark every task unhealthy at once, and ECS would start replacing containers that were fine. /health/ready is for deploy smoke tests and monitoring, where a failing dependency should be visible.
Task definition and least-privilege IAM
{
"family": "api",
"requiresCompatibilities": ["FARGATE"],
"networkMode": "awsvpc",
"cpu": "512",
"memory": "1024",
"executionRoleArn": "arn:aws:iam::123456789012:role/api-execution",
"taskRoleArn": "arn:aws:iam::123456789012:role/api-task",
"containerDefinitions": [
{
"name": "api",
"image": "123456789012.dkr.ecr.us-east-1.amazonaws.com/api:3f9c2e1",
"essential": true,
"portMappings": [{ "containerPort": 8000 }],
"secrets": [
{
"name": "DATABASE_URL",
"valueFrom": "arn:aws:secretsmanager:us-east-1:123456789012:secret:prod/api/database-url-a1B2c3"
}
],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/api",
"awslogs-region": "us-east-1",
"awslogs-stream-prefix": "api"
}
}
}
]
}The image tag is the Git commit, so every running task can be traced to its code. The two roles have different jobs. The execution role is used by ECS itself to pull the image, write logs and read the listed secrets, so it gets the AWS managed AmazonECSTaskExecutionRolePolicy plus secretsmanager:GetSecretValue on those specific secret ARNs (and kms:Decrypt if the secret uses a customer managed key). The task role is what the application code runs as, and it gets only what the code needs:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject"],
"Resource": "arn:aws:s3:::example-app-files/uploads/*"
}
]
}The ECS service runs at least two tasks spread across both zones, scales with target tracking on CPU or requests per target, and deploys with the deployment circuit breaker and rollback enabled.
Data, backups and failover
RDS PostgreSQL runs as a Multi-AZ deployment: a synchronous standby in the second zone takes over automatically if the primary fails, and the endpoint name stays the same. The standby does not serve reads, so a separate read replica takes reporting and other read-heavy queries away from the primary. Automated backups, with a retention period of up to 35 days, allow point-in-time recovery. Storage is encrypted, deletion protection is on, and I take a manual snapshot before risky migrations. The schema itself follows the PostgreSQL design blueprint.
ElastiCache runs with a replica in the other zone and automatic failover, but the design treats Redis as rebuildable: losing it costs speed, not data. S3 buckets keep Block Public Access on and versioning enabled for user files.
CloudWatch alarms cover ALB HTTPCode_Target_5XX_Count, TargetResponseTime and UnHealthyHostCount, ECS CPU and memory, and RDS FreeStorageSpace and DatabaseConnections. Request-level metrics and dashboards are covered in the monitoring and observability blueprint.
Failure modes and how the design handles them
- A container crashes or hangs. The ALB stops routing to it after failed health checks, and ECS replaces it while the other tasks keep serving.
- An availability zone fails. Tasks in the other zone keep serving, RDS fails over to its standby, ElastiCache promotes its replica and ECS places replacement tasks in the healthy zone.
- The database fails over. Open connections drop briefly. SQLAlchemy's
pool_pre_pingdiscards dead connections, so requests recover instead of hanging. - A bad release goes out. New tasks fail their health checks, the circuit breaker rolls back, and the previous image is still in ECR under its commit tag.
- A secret is rotated or leaked. Secrets live only in Secrets Manager. Tasks read them at startup, so a new deployment picks up a rotated value.
- Traffic spikes. Target tracking adds tasks, while the
DatabaseConnectionsalarm warns before new tasks exhaustmax_connections. RDS Proxy is an option when that limit gets close. - Someone deletes data. Point-in-time recovery restores the database to a new instance from just before the mistake, and S3 versioning recovers overwritten files.
Checklist
- Two availability zones, with only the ALB in public subnets.
- Security groups reference each other instead of opening address ranges.
- HTTPS everywhere, with an ACM certificate on the ALB.
- Containers run as non-root, log to stdout and are tagged by commit.
- The ALB health check is shallow; deep checks serve smoke tests and monitoring.
- Separate execution and task roles, each scoped to specific resources.
- Secrets in Secrets Manager, never in images, task definition environment values or Git.
- RDS Multi-AZ, encrypted, with deletion protection and automated backups.
- A restore from backup has been tested, not just configured.
- CloudWatch alarms on errors, latency, unhealthy hosts and database storage.
- Deployments run through the CI/CD pipeline, never by hand.
Tools & Stack
- AWS
- VPC
- ECS / EC2
- ALB
- RDS PostgreSQL
- ElastiCache Redis
- S3
- CloudWatch
- Docker
In Practice
Applied in the Mobileriz multi-marketplace backend: The FastAPI backend runs on AWS in Docker containers with Prometheus monitoring.
This blueprint is part of my Python backend & API development service. Tell me about your system on Upwork and I'll propose the right setup, timeline and cost.
Hire Me on Upwork


