Sub topic 16
Mixing Fargate and Fargate Spot
This chapter assumes you can register a Fargate task definition and create a service with the AWS CLI, as covered in the earlier chapters. You should also know how a service keeps a desired count of tasks running. Here you will learn how capacity providers let one service run on both regular Fargate and Fargate Spot, and how to design for the interruptions that Spot brings.
What Fargate Spot is
Fargate Spot runs your tasks on spare AWS capacity at a discount compared with regular Fargate. The discount is large, often up to about 70 percent, but it varies by Region and over time, so check current pricing. The trade-off is that AWS can reclaim the capacity. When that happens, your task receives a two-minute warning and is then stopped.
Fargate Spot uses the same task definitions, networking, and IAM roles as regular Fargate. Only the capacity source changes. That makes it cheap to try, provided your workload tolerates a task disappearing.
| Property | Fargate | Fargate Spot |
|---|---|---|
| Price | Standard on-demand rate | Discounted rate |
| Interruption | Not interrupted for capacity reasons | Can be reclaimed with a two-minute warning |
| Availability | Normally available | Depends on spare capacity, so tasks may wait to launch |
| Task definition | Unchanged | Unchanged |
Capacity providers
A capacity provider tells ECS where to get compute for a task. For Fargate, two capacity providers exist already, named FARGATE and FARGATE_SPOT. A cluster must have them associated before a service can use them. Clusters created in the console usually have this done. For a cluster made with aws ecs create-cluster, you can associate them explicitly:
aws ecs put-cluster-capacity-providers \
--cluster demo \
--capacity-providers FARGATE FARGATE_SPOT \
--default-capacity-provider-strategy capacityProvider=FARGATE,weight=1The default strategy applies to services and standalone tasks that do not specify their own. Here it keeps everything on regular Fargate unless a service opts into Spot.
A service that uses a capacity provider strategy does not use --launch-type. You choose one or the other, and mixing the two in one create-service call is an error.
The capacity provider strategy
A strategy is a list of providers, and each entry has up to three settings:
capacityProvider: the provider name.base: the minimum number of tasks to place on this provider before weights apply. Only one provider in a strategy can have a base.weight: the relative share of the remaining tasks that go to this provider.
ECS places the base tasks first. It then splits the rest according to the weights.
The strategy below keeps one task on regular Fargate and spreads the others across Fargate and Fargate Spot at a 1:3 ratio:
aws ecs create-service \
--cluster demo \
--service-name worker \
--task-definition web-app \
--desired-count 4 \
--capacity-provider-strategy capacityProvider=FARGATE,base=1,weight=1 capacityProvider=FARGATE_SPOT,weight=3 \
--network-configuration "awsvpcConfiguration={subnets=[subnet-aaa111,subnet-bbb222],securityGroups=[sg-0123456789abcdef0],assignPublicIp=DISABLED}"With a desired count of 4, the placement works out like this:
- The base puts 1 task on
FARGATE. - Three tasks remain. The weights are 1 and 3, which gives a quarter and three quarters of the remainder.
- Weighted placement of three tasks yields roughly 1 on
FARGATE(or 0, depending on rounding) and 2 or 3 onFARGATE_SPOT.
Weights are proportions, not exact counts, and small counts round unevenly. Do not rely on an exact split at low task counts. At higher counts the ratio approaches the weights.
Choosing a base and weights
Pick the base from the minimum capacity your service needs to stay useful if every Spot task vanishes at once. For a web service behind a load balancer, a base of 2 on FARGATE keeps a working service during a Spot shortage. The weights then decide how much extra capacity is discounted.
Some common shapes:
- All Spot: a single
FARGATE_SPOTentry. Suitable for batch workers, queue consumers, and dev environments. - Base on Fargate, burst on Spot:
FARGATEwith a base equal to your floor, thenFARGATE_SPOTwith weight 1 andFARGATEwith weight 0. This is the usual pattern for production. - Proportional mix: both providers with nonzero weights, as in the example above.
A weight of 0 means a provider receives no tasks beyond its base. This is how you reserve regular Fargate for the floor only.
Interruptions and how tasks stop
When AWS reclaims Spot capacity, ECS sends the task a SIGTERM signal and an event. Your container then has until its stopTimeout to exit before SIGKILL. Fargate Spot gives two minutes of warning, and the stopTimeout is capped at 120 seconds on Fargate, so a longer timeout cannot extend it.
The task also receives a task state change event in Amazon EventBridge, and the task metadata endpoint reports the pending interruption. Your application can use either to begin draining early.
Design your containers to handle this:
- Handle
SIGTERMexplicitly. Many images run the application as a child of a shell, which does not forward signals. Use the exec form ofCMDorENTRYPOINTso the application is process 1 and receives the signal. - Finish or hand back in-flight work. A queue consumer should stop polling, then let messages it did not finish return to the queue.
- Keep work idempotent. A task can be interrupted partway through, so repeated work must be safe.
- Do not keep state only on the task. Ephemeral storage disappears with the task.
For a web service behind an Application Load Balancer, the load balancer deregisters a stopping task and drains connections for the target group's deregistration delay. If that delay is longer than the time before SIGKILL, in-flight requests can still be cut off. Set the deregistration delay to a value that fits within the stop window, for example 30 seconds.
Replacement behavior
After an interruption, the service scheduler notices the task count is below the desired count and starts a replacement. It follows the same strategy, so a lost Spot task is normally replaced on Spot. If Spot capacity is unavailable, the replacement can sit pending and retry. Your base tasks on regular Fargate keep serving meanwhile, which is the reason to set one.
Note that the scheduler does not move Spot tasks onto regular Fargate on its own to fill a Spot shortage. If you need that fallback, keep a larger base, or use a second service with a different strategy.
Constraints and gotchas
- Linux only, with limits on some features. Fargate Spot supports Linux tasks on both X86_64 and ARM64. Check the current documentation for the platform versions and any task features that are not supported.
- Strategy changes need a deployment. To change a service's strategy, call
update-servicewith the new--capacity-provider-strategyand--force-new-deployment. Existing tasks are replaced by a rolling update. - Not for every workload. Single-task services, stateful tasks, and anything that cannot restart within two minutes should stay on regular Fargate.
- Auto scaling works with it. Target tracking changes the desired count, and the strategy then decides where new tasks land. Scale-in removes tasks without preferring one provider, so the mix can drift from your weights.
- Cost depends on mix. The savings are proportional to the share of tasks on Spot. A base of 2 out of 10 tasks leaves most of the fleet discounted.
Changing a service's strategy
This command moves an existing service to a production-style layout, with a floor of two regular tasks and the rest on Spot:
aws ecs update-service \
--cluster demo \
--service worker \
--capacity-provider-strategy capacityProvider=FARGATE,base=2,weight=0 capacityProvider=FARGATE_SPOT,weight=1 \
--force-new-deploymentVerify where tasks run with describe-tasks, which reports the capacityProviderName for each task:
TASKS=$(aws ecs list-tasks --cluster demo --service-name worker --query 'taskArns' --output text)
aws ecs describe-tasks --cluster demo --tasks $TASKS \
--query 'tasks[].{task:taskArn,provider:capacityProviderName}' --output tableExercise
A service has a desired count of 6 and uses the strategy FARGATE base=2 weight=0, FARGATE_SPOT weight=1. How many tasks run on each provider, and what happens to the service if all Spot tasks are interrupted at once?
Show answer
Two tasks run on FARGATE (the base) and four run on FARGATE_SPOT, because FARGATE has weight 0 and receives nothing beyond its base. If every Spot task is interrupted, the two FARGATE tasks keep serving while the scheduler tries to start four replacements on Spot. The service runs at reduced capacity until Spot capacity is available again.
Exercise
Your container runs CMD "node server.js" in shell form and loses requests when a Spot task is reclaimed. Name one likely cause and one fix.
Show answer
Shell form starts the application as a child of /bin/sh, which does not forward SIGTERM, so the application never gets the chance to drain and is killed by SIGKILL. Switch to exec form, for example CMD ["node", "server.js"], and handle SIGTERM in the application so it stops accepting new work and finishes in-flight requests.