How Fargate works with ECS and EKS, what it costs, and when serverless containers are the right tradeoff.
AWS Fargate runs containers for ECS or EKS without requiring you to provision and patch the worker instances underneath them. AWS manages the compute, while ECS or EKS still handles orchestration and leaves the application team responsible for the service configuration around each workload.
This guide follows an orders API from its container image to a reachable, secure, scalable Fargate service, then works through the full cost and the cases where another compute option makes more sense.
The final section introduces Encore as an alternative way to deploy the application into AWS without configuring ECS and Fargate directly.
For the orders API, ECS describes the workload and keeps the requested number of copies running, while Fargate supplies the machines they run on. Start by building the container image and pushing it to a registry such as Amazon ECR, then create a task definition that tells ECS how to run it.
The task definition is the contract between the orders API and ECS. It identifies the image, exposed port, requested CPU and memory, IAM roles, and log destination:
{
"family": "orders-api",
"requiresCompatibilities": ["FARGATE"],
"networkMode": "awsvpc",
"cpu": "512",
"memory": "1024",
"executionRoleArn": "arn:aws:iam::123456789012:role/ecsTaskExecutionRole",
"taskRoleArn": "arn:aws:iam::123456789012:role/ordersTaskRole",
"containerDefinitions": [
{
"name": "api",
"image": "123456789012.dkr.ecr.eu-west-1.amazonaws.com/orders:abc123",
"essential": true,
"portMappings": [{ "containerPort": 8080, "protocol": "tcp" }],
"logConfiguration": {
"logDriver": "awslogs",
"options": {
"awslogs-group": "/ecs/orders-api",
"awslogs-region": "eu-west-1",
"awslogs-stream-prefix": "api"
}
}
}
]
}
This example assumes the ECR repository, CloudWatch log group, and both IAM roles already exist. If /ecs/orders-api has not been created, the task will stop before the application starts unless the execution role is also allowed to create the log group and awslogs-create-group is enabled.
Register the task definition, then select or create an ECS cluster and either run the task once or create an ECS service that keeps the requested number running. Selecting the Fargate launch type or a Fargate capacity provider tells ECS to place those tasks on compute managed by AWS.
Fargate can also run eligible Kubernetes pods through EKS Fargate profiles. Kubernetes still supplies the workload objects and control plane in that model; Fargate replaces the worker nodes selected by the profile.
Registering a task definition makes it available to RunTask or an ECS service; registration does not start a container on its own. Running one task is still not enough for a public API, which needs four parts around it:
The databases, queues, caches, buckets, and secrets used by the application remain separate resources that must be provisioned and connected to the task.
Compared with ECS on EC2, the setup no longer needs an EC2 autoscaling group, AMI updates, node patching, or task bin-packing.
ECS tasks on Fargate use awsvpc networking, which gives each task an elastic network interface and private IP address in one of the selected subnets and applies security groups directly to the task.
Because every task is an endpoint in the VPC, the orders API still needs decisions about where traffic enters and how the task reaches AWS services and external APIs. Production services commonly place tasks in private subnets behind a load balancer, which means they need a NAT gateway or VPC endpoints for outbound access.
Security groups can admit traffic from the load balancer or known callers and restrict egress where practical. Each task also consumes an IP address, so subnet sizing can become a scaling limit, and private service-to-service calls need DNS or a service-connectivity layer.
For a small service, NAT gateways and load balancers can cost more than the Fargate tasks. We will include them when estimating the service in Step 5.
AWS manages the host, while IAM, container configuration, and network policy control what the application can do.
The orders API uses two ECS roles for different parts of its lifecycle. The task execution role lets ECS pull the image, send logs, and retrieve only the secrets referenced by the task definition, while the task role supplies AWS credentials to the application inside the container. Keeping them separate means the orders service can read its S3 bucket without inheriting the permissions used to start the task, but the execution role can still read every referenced secret, so that list should remain narrow. Neither role needs permission to edit the task definition.
Because Fargate manages the host rather than the application inside the container, the task should still run as a non-root user where possible and use a read-only filesystem when the application supports it. Images can be scanned and signed before deployment, and secrets should come from Secrets Manager or Parameter Store instead of being baked into the image.
Restricting security-group ingress and egress limits the network path around the task, while logs, health checks, and a reasonable stop timeout make failures visible and give deployments time to drain. Separate AWS accounts or roles keep development access away from production.
Fargate's compute isolation works together with the task role and security groups, which determine which AWS resources and network destinations a compromised task could reach.
Scaling still starts with an ECS desired task count even though there is no EC2 fleet to manage.
For a long-running API, Application Auto Scaling adjusts the desired task count from signals such as CPU, memory, request count, or a custom CloudWatch metric. The policy sets the minimum and maximum number of tasks and chooses between target tracking and step scaling. Deployment percentages determine how much capacity ECS may add or remove during a rollout, and health-check grace periods and scaling cooldowns need to reflect how long the application takes to start serving traffic.
For batch and event-driven work, EventBridge, Step Functions, a queue consumer, or application code can call RunTask, avoiding an idle service at the cost of startup latency; latency-sensitive work therefore often keeps at least one task running.
Fargate Spot provides discounted, interruptible capacity for workers, builds, and batch jobs that can retry or checkpoint, while workloads that cannot tolerate interruption should retain an on-demand path.
When estimating the orders API, start with the resources requested by each task rather than its observed average usage, because Fargate bills the reservation. The vCPU and memory allocation provide the base, with rates varying by operating system, CPU architecture, and region. Runtime is measured from image download until the task terminates and is subject to a minimum billing period, while ephemeral storage above the included 20 GiB adds another charge. Tasks that can tolerate interruption can use Fargate Spot instead of standard Fargate pricing.
Those inputs produce the compute portion of the estimate:
monthly task cost = (vCPU price × requested vCPU + memory price × requested GB) × runtime + max(0, configured storage - 20 GiB) × storage price per GB-hour × runtime
Add load balancers, NAT gateways, public IPv4 addresses, logs, metrics, data transfer, ECR storage, and attached databases or queues. The official Fargate pricing page lists current rates by region, operating system, and architecture.
Fargate tends to fit variable workloads, small teams that do not want to operate nodes, services with different CPU and memory shapes, and short-lived or scheduled tasks. A large fleet with steady utilization can have a lower compute bill on ECS with EC2, particularly with Savings Plans, Reserved Instances, or Spot capacity, although that comparison also has to include the engineering work required to operate the fleet.
Once the full service cost is understood, the wider compute choice comes down to how much the team values host control, Kubernetes compatibility, an event-driven execution model, or the lower operational surface of Fargate:
Because Fargate is one of the compute options behind ECS, the direct comparison for an ECS service is usually Fargate versus an EC2 capacity provider; whether the application team should manage ECS itself is a separate decision.
Some requirements rule Fargate out before cost becomes relevant. A service that needs SSH access to the host, privileged containers, host-level agents, GPUs, custom AMIs, kernel modules, or specialized networking needs EC2-backed capacity. The same applies when the workload falls outside Fargate's supported compute and storage combinations or needs a daemon to run once on every node. For a large fleet with steady utilization, EC2 may also offer a lower unit cost in exchange for operating the instances and their capacity.
Support differs by operating system, architecture, region, and orchestrator, so check the current ECS or EKS documentation for the target region.
If you are researching Fargate for a new backend, you do not necessarily need to assemble the ECS service, task definition, load balancer, IAM roles, networking, scaling policy, and deployment pipeline yourself. Encore provides another path: keep using your application framework, declare the services and infrastructure in code, and let Encore provision and manage the corresponding resources in your AWS account.
import { SQLDatabase } from "encore.dev/storage/sqldb";
const db = new SQLDatabase("todo", {
migrations: "./migrations",
});Managed PostgreSQL with migrations, pooling and IAM auth
Encore maps the resources declared by the application to the managed AWS services used in each environment.
Learn more about how Encore automates infrastructure →
For the orders API, Encore can select ECS Fargate as the compute and manage its task definition, target group, IAM policies, networking, and deployment configuration. The application team works with the service and its database, Pub/Sub topics, buckets, caches, secrets, and cron jobs in code, while environment configuration controls regions, sizing, scaling, and networking.
Direct Fargate remains the better fit when the team wants to own the ECS, VPC, IAM, and deployment configuration. Encore fits when the team wants to deploy into its own AWS account without maintaining that per-service wiring, and any existing shared AWS foundations can remain in Terraform.
Run in your terminal to get started locally.
AWS Fargate is a serverless compute engine for containers. You define an ECS task or schedule an eligible EKS pod, and AWS supplies and manages the underlying compute instead of requiring you to operate EC2 worker instances.
No. ECS is a container orchestrator. Fargate is a compute option that ECS can use to run tasks. ECS can also place tasks on EC2 capacity, and Fargate can be used with EKS for eligible Kubernetes pods.
It depends on utilization and operational cost. Fargate charges for the CPU, memory, operating system, architecture, storage, and runtime requested by each task. Well-utilized EC2 fleets can have a lower compute cost, while Fargate avoids paying for idle cluster capacity and removes node management.
An ECS service can set its desired task count to zero, and event-driven systems can start tasks on demand. Fargate itself does not decide when an application should scale; ECS Service Auto Scaling, a scheduler, an event target, or your own control plane changes the number of tasks.
Fargate is a poor fit when you need host access, specialized instances or accelerators, privileged containers, unusually high compute sizes, or the lowest cost for a large steady fleet. EC2-backed ECS or EKS gives more control in those cases.
Yes. Encore can provision and manage application compute on AWS, including ECS Fargate where appropriate, from services and infrastructure declared with its open source Infra SDK. You keep using your application framework while Encore handles task definitions, networking, IAM, deployment, and the supported resources around the service.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.