Sub topic 5
Choosing task CPU and memory
This chapter assumes you can read a task definition and know what a container's memory limit means. Fargate sizes a task as a whole, and it accepts only certain CPU and memory pairs.
Task-level size is required
A Fargate task definition must set cpu and memory at the task level. Both are strings. CPU is in CPU units, where 1024 units equal one vCPU. Memory is in MiB. Fargate provisions a microVM of exactly that size, and you are billed for that size, not for what the containers use.
{
"family": "web-app",
"requiresCompatibilities": ["FARGATE"],
"networkMode": "awsvpc",
"cpu": "512",
"memory": "1024"
}Valid combinations
Each CPU value allows only a range of memory values. The table lists the common Linux sizes.
| CPU units | vCPU | Allowed memory |
|---|---|---|
| 256 | 0.25 | 512 MiB, 1 GiB, 2 GiB |
| 512 | 0.5 | 1 GiB to 4 GiB, in 1 GiB steps |
| 1024 | 1 | 2 GiB to 8 GiB, in 1 GiB steps |
| 2048 | 2 | 4 GiB to 16 GiB, in 1 GiB steps |
| 4096 | 4 | 8 GiB to 30 GiB, in 1 GiB steps |
| 8192 | 8 | 16 GiB to 60 GiB, in 4 GiB steps |
| 16384 | 16 | 32 GiB to 120 GiB, in 8 GiB steps |
If you register a pair outside these ranges, register-task-definition fails with a client exception about invalid CPU or memory values. Check the current limits in the ECS documentation, because AWS adds sizes over time.
Container-level limits
Containers inside the task may also set cpu, memory, and memoryReservation. Their meanings differ:
memoryis a hard limit. If the container exceeds it, ECS kills the container, and the exit code is usually 137.memoryReservationis a soft limit. The container may use more memory, up to the task's total.- Container
cpuis a relative share. It matters only when containers compete for the task's CPU.
With a single container, you can usually leave all three unset. The container then has access to the whole task allocation.
How to pick a size
Start from a guess, run realistic load, and measure.
ECS publishes CPUUtilization and MemoryUtilization per service in CloudWatch. Container Insights adds per-task detail. Watch the peak values, not the average. A service that averages 30 percent memory but spikes to 95 percent during a batch import will still be killed.
Changing the size means registering a new task definition revision and updating the service, which triggers a deployment.
Exercise
Your task is 256 CPU units and you want 4 GiB of memory. Is that valid? If not, what is the smallest valid change?
Show answer
It is not valid, because 256 CPU units allow only 512 MiB, 1 GiB, or 2 GiB. The smallest change is to raise CPU to 512, which allows up to 4 GiB. This doubles the CPU you pay for. If your workload does not need that CPU, check whether 2 GiB is enough.