How do Lambda and Fargate bill for backend API compute?

AWS Lambda runs your handler in a managed execution environment that AWS creates when requests arrive and reclaims when they stop. Teams pick it for APIs because there is no fleet to size, scaling follows request volume, and idle time costs nothing. AWS Fargate runs containers as ECS tasks without EC2 instances to manage. Teams pick it for APIs when they want a long-lived process with connection pools, in-memory caches, and a standard HTTP server they can also run locally or elsewhere.

The billing units differ, and that difference drives the rest of this analysis:

Dimension Lambda ECS Fargate
What you pay for Per-request fee plus GB-seconds (configured memory × execution duration) vCPU-seconds plus GB-seconds for the resources each task requests
When the meter runs Only while an invocation executes The whole time a task runs, whether or not it serves traffic
How CPU is set Indirectly: CPU allocation scales with configured memory Explicitly: you choose a vCPU and memory combination
Idle cost None for on-demand functions Full price for every running task

The memory-to-CPU link on Lambda matters for cost. A CPU-bound handler can get faster when you raise memory, so a higher per-millisecond rate can sometimes lower the total bill. On Fargate, CPU and memory are separate line items, so you pay for what you reserve rather than what you use.

Prices vary by region, CPU architecture, and over time. Take current figures from the AWS pricing pages for Lambda and Fargate in your target region, and don't rely on any numbers you find in articles, including this one.

Why does concurrency per container matter more than request count?

Request count matters less than how many requests are in flight at once and what each one is doing while it waits. In the standard model, a Lambda execution environment handles one request at a time. If a handler spends 15 ms on CPU and 185 ms waiting on a database query and a downstream HTTP call, you are billed for 200 ms of the configured memory. The environment is idle for most of that time, but it is reserved for that one request, so the idle time is billed.

A Fargate task bills for its vCPU and memory allocation per second, whether it is busy or not. An async or multithreaded server, such as an event-loop runtime or a thread pool, can keep dozens or hundreds of requests in flight on that one allocation. While one request waits on I/O, the CPU serves another. The waiting time is spread across many requests instead of being paid for once per request.

Lambda: one in-flight request per environment

  req1 ──► [env 1]   billed 200 ms
  req2 ──► [env 2]   billed 200 ms
  req3 ──► [env 3]   billed 200 ms
  ...
  reqN ──► [env N]   billed 200 ms

Fargate: many in-flight requests per task

  req1 ┐
  req2 ┤            ┌─► [task A]  billed per second,
  req3 ┼──► [ALB] ──┤             shared by all
  ...  │            └─► [task B]  in-flight requests
  reqN ┘

The comparison therefore depends on how I/O-bound your handlers are. A CPU-bound handler gains little from multiplexing, so the two models end up closer in cost. A handler that mostly waits gives Fargate a structural advantage that grows with concurrency per task.

 LAMBDA: one in-flight request per execution environment

 req 1 ──►┌─────────┐  [CPU 15ms][ wait on DB/API 185ms ]
          │  env 1  │  billed: 200 ms x configured memory
          └─────────┘
 req 2 ──►┌─────────┐  [CPU 15ms][ wait on DB/API 185ms ]
          │  env 2  │  billed: 200 ms x configured memory
          └─────────┘
   ...        ...
 req N ──►┌─────────┐  [CPU 15ms][ wait on DB/API 185ms ]
          │  env N  │  billed: 200 ms x configured memory
          └─────────┘
   N in flight = N environments; idle wait is billed N times

 FARGATE: many in-flight requests multiplexed per task

 req 1 ──┐                  ┌──────────────────────────┐
 req 2 ──┤   ┌─────────┐    │ task A (event loop/pool) │
 req 3 ──┤   │         │ ┌─►│ reqs 1..k in flight      │
  ...    ├──►│   ALB   ├─┤  └──────────────────────────┘
 req N ──┘   │         │ │  ┌──────────────────────────┐
             └─────────┘ └─►│ task B (event loop/pool) │
                            │ reqs k+1..N in flight    │
                            └──────────────────────────┘
   Billed per second for task vCPU + memory, busy or idle;
   while one request waits on I/O, the CPU serves another.

With Lambda, each in-flight request occupies its own execution environment and its I/O wait time is billed per request. With Fargate, an ALB spreads requests across a few tasks whose per-second vCPU and memory allocation is shared by every request in flight.

How do you calculate the Lambda vs Fargate break-even point?

Turning that advantage into a number means pricing both models per request and finding where Lambda's bill crosses Fargate's fixed floor.

Lambda is linear in traffic. Per request, cost is c_L = P_req + D × M × P_gbs, where D is average billed duration in seconds, M is memory in GB, and P_gbs is the GB-second price. Monthly cost is R × 2,592,000 × c_L for R requests per second over a 30-day month.

Fargate is a step function. Task count is N = max(N_min, ceil(R / (r × u))), where r is sustainable RPS per task from load testing and u is target utilization (1 − headroom). Monthly cost is N × 720 × task_hourly, and task_hourly is vCPU × P_vcpu + GB × P_mem.

At low traffic Fargate's cost is just the N_min floor. Break-even is therefore R* = (N_min × 720 × task_hourly) / (2,592,000 × c_L). Above R*, Fargate's per-request cost (task_hourly / (3600 × r × u)) is usually far below c_L, so the gap widens as traffic grows.

Illustrative estimate. All prices are placeholders, not current AWS rates. Assume P_req = $0.20/M, P_gbs = $0.0000167, a 0.5 vCPU / 1 GB task at $0.03/hour, r = 150, u = 0.6, and N_min = 2. That gives a Fargate floor of $43.20/month.

Scenario D M Lambda $/M req Break-even RPS
Baseline 100 ms 0.5 GB 1.04 ~16
I/O-bound 300 ms 0.5 GB 2.71 ~6
Doubled memory 100 ms 1 GB 1.87 ~9
Halved memory, slower 200 ms 0.25 GB 1.04 ~16

The last row shows why cutting memory is not automatically a saving. Lambda allocates CPU in proportion to memory, so halving memory can double duration. The GB-seconds stay the same and the saving disappears.

import math

SECONDS_PER_MONTH = 2_592_000  # 30 days
HOURS_PER_MONTH = 720

def lambda_cost_per_req(p_req, p_gbs, duration_s, memory_gb):
    # Per-request fee plus billed compute (GB-seconds)
    return p_req + duration_s * memory_gb * p_gbs

def fargate_monthly(rps, task_hourly, r_per_task, util, n_min):
    # Step function: enough tasks for load at target utilization, never below n_min
    n = max(n_min, math.ceil(rps / (r_per_task * util)))
    return n * HOURS_PER_MONTH * task_hourly

def break_even_rps(c_l, task_hourly, r_per_task, util, n_min):
    floor = n_min * HOURS_PER_MONTH * task_hourly
    r_star = floor / (SECONDS_PER_MONTH * c_l)
    # Formula assumes the floor still covers R*; flag it if it does not
    if r_star > n_min * r_per_task * util:
        print("  warning: R* is above floor capacity; check the step function")
    return r_star

# Illustrative estimate: placeholder prices, not current AWS rates
P_REQ, P_GBS = 0.20 / 1_000_000, 0.0000167
TASK_HOURLY, R_TASK, UTIL, N_MIN = 0.03, 150, 0.6, 2

scenarios = {  # name: (avg billed duration s, memory GB)
    "baseline": (0.100, 0.5),
    "io_bound": (0.300, 0.5),
    "doubled_memory": (0.100, 1.0),
    "halved_memory_slower": (0.200, 0.25),
}

for name, (d, m) in scenarios.items():
    c_l = lambda_cost_per_req(P_REQ, P_GBS, d, m)
    r_star = break_even_rps(c_l, TASK_HOURLY, R_TASK, UTIL, N_MIN)
    print(f"{name:22s} ${c_l * 1e6:.2f}/M req  break-even ~{r_star:.1f} RPS")

print(f"Fargate at 50 RPS: ${fargate_monthly(50, TASK_HOURLY, R_TASK, UTIL, N_MIN):.2f}/month")

A plug-in Python model of Lambda's linear cost and Fargate's step-function cost that reproduces the illustrative break-even table and warns when the minimum-task floor no longer covers the computed break-even rate.

What costs outside compute change the comparison?

Compute is only part of the bill. The services around each platform can shift the break-even point, sometimes enough to reverse it.

Cost item Lambda Fargate Why it matters
Load balancer Optional. An ALB can front Lambda instead of API Gateway Effectively required. Hourly charge plus capacity units The ALB is a fixed floor on Fargate cost that exists even at zero traffic
API Gateway Per-request charge if used Usually not needed The charge scales linearly with volume, just like Lambda compute
Function URL No added request charge Not applicable Cheapest entry point, but you lose gateway features such as throttling and request validation
NAT gateway Applies when the function runs in private subnets and calls out Same for tasks in private subnets Charged per GB processed plus hourly. VPC endpoints can bypass NAT for some AWS services
CloudWatch Logs ingestion Per GB ingested Per GB ingested Verbose per-request logging can cost more than the compute it describes
Connection-pooling proxy Often required for relational databases Rarely needed, because tasks pool connections in-process Each concurrent Lambda environment opens its own connections, which can exhaust database limits

Illustrative estimate (assumed numbers, not a benchmark). These inputs are assumed:

  • Each request runs for 100 ms at 512 MB.
  • Compute costs $0.0000167 per GB-second.
  • API Gateway costs $1.00 per million requests.

Compute per million requests = 1,000,000 × 0.1 s × 0.5 GB × $0.0000167 ≈ $0.83.

Under these assumptions, the gateway charge alone exceeds Lambda compute. For short-running functions, the choice of entry point can matter more than memory tuning.

Utilization, diurnal traffic, and pricing modifiers

On Fargate you pay for provisioned vCPU and memory whether requests arrive or not, so utilization is the main lever. A cluster averaging 20% CPU wastes roughly four-fifths of its compute spend. Lambda bills only while code runs, so idle capacity costs it nothing. That asymmetry is why right-sizing matters. Pick task sizes from measured CPU and memory under load, use target-tracking auto scaling on CPU or request count per target, and set headroom from real latency targets rather than habit. Without that work, Fargate's per-unit price advantage may never appear on the bill.

Modeling a diurnal curve

A flat-rate model treats Fargate as if it ran at steady utilization, which flatters it. For a daytime peak and overnight trough, model each band separately. Fargate scales out with lag, so in practice you provision for the peak plus a buffer and keep a minimum task count overnight for availability. Lambda follows the curve closely.

Illustrative estimate: assume load needs 6 tasks for 10 daytime hours and 1 task for 14 overnight hours. With a peak buffer of 8 tasks and a minimum of 2, the cluster pays for 108 task-hours against 74 actually needed. Lambda pays for roughly the 74. The gap is smaller than a flat model suggests.

Pricing modifiers

  • Compute Savings Plans apply to both Fargate and Lambda, so commit against your baseline usage on either service.
  • Fargate Spot cuts cost for interruption-tolerant work, such as async workers. It is risky for latency-sensitive API tasks.
  • ARM/Graviton is cheaper per unit on both services. Benchmark before switching, because throughput per unit can differ from x86.
  • Provisioned concurrency bills Lambda for capacity whether it is used or not. Its economics then resemble an always-on container.

When should you avoid Fargate or Lambda for steady APIs?

The bill omits engineering time, and for a small team that often decides the comparison. Fargate makes you own the container image, base image patching, health check tuning, deployment strategy (rolling or blue/green), and autoscaling thresholds. If a monthly compute saving is smaller than the hours spent maintaining that setup, Fargate costs more. Fargate also adds capacity slowly, because each new task must be scheduled, pull its image and pass health checks. Absorbing sudden spikes means running extra tasks all the time, and that headroom erodes the utilization advantage that made Fargate cheaper.

Lambda has its own costs. Cold starts are rare under steady load, but they appear in p99 latency after deploys and during scale-out. Provisioned concurrency fixes this by billing for idle capacity, which undoes much of the pay-per-use advantage. The account-level concurrency quota for each region is shared by every function, so one noisy workload can throttle your API unless you set reserved concurrency.

Portability is a cost in both directions. Moving from Lambda to containers means adding an HTTP server, connection pooling and graceful shutdown. Moving to Lambda means removing in-process state and background work, and managing database connections, because thousands of short-lived environments can exhaust a database's connection limit.

Avoid When
Fargate Small team, modest saving, spiky traffic needing headroom
Lambda Strict p99 SLOs, high concurrency near quota, connection-heavy backends

Fargate suits teams that already run container platforms. Lambda suits teams that want to minimise operational work.

How should you decide, and what are the alternatives?

Start with measurement, not price sheets. Load-test a single Fargate task and a single Lambda function with production-like payloads, real downstream dependencies, and cold caches. Record p50 and p99 duration, and find the request rate at which one task holds its latency target. Synthetic tests with tiny payloads and warm caches usually overstate per-task throughput, and that pushes the break-even point in Fargate's favor without justification. The I/O profile you measure also matters: a handler that spends most of its time waiting on a database is cheap to pack into a container, but on Lambda you are billed for that same wait on every request.

Put those measurements into the model for both current traffic and your projected traffic over the next year. Then add the surrounding costs: load balancer or API gateway, NAT data processing, logging volume, and the engineering time each platform requires. Treat the break-even figure as a snapshot of your inputs, current prices, and region. Re-run it when traffic shifts substantially, when prices change, or when a code change alters the CPU-to-I/O ratio.

Alternatives and hybrids

  • ECS on EC2 lowers unit cost for large, predictable baselines. In exchange, you manage instance capacity, bin-packing, and patching.
  • Lambda with provisioned concurrency removes cold starts for latency-sensitive paths. You pay for it whether or not it is used, so size it to your baseline.
  • Split by traffic shape. Serve the steady, high-volume endpoints from containers and route bursty or rarely called endpoints to Lambda. Each workload then lands on the billing model that fits it.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to lambda vs fargate cost, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Consumers learn about a breaking change at review time rather than from production errors.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.