How do Lambda, Fargate and EC2 bill for an API?
This analysis is for backend and platform engineers who are choosing where to host an HTTP API, or revisiting a choice made when traffic was smaller or burstier. The three options charge for different units, so each one wastes money in a different way.
Lambda charges per request plus duration multiplied by allocated memory, usually expressed as GB-seconds. Duration is measured from when your handler starts until it returns. If the handler spends 80 ms waiting on a database query, you pay for those 80 ms at the full memory allocation. Each execution environment handles one request at a time, so that wait time is not shared with other requests. On Lambda, paid wait time is the unit of waste.
Fargate charges per second for the vCPU and memory you reserve for each task, from the time the task starts until it stops. A short minimum charge applies. The bill does not depend on requests served or CPU actually used. A task sized at 1 vCPU that averages 15% utilisation costs the same as one running at 90%. The waste is idle reserved capacity.
EC2 charges for each instance for as long as it runs, whether it is busy or idle. Linux instances are metered per second after a minimum, but in practice teams think in instance-hours. You choose the instance size, and you pack processes onto it yourself, so the waste is again idle reserved capacity. On EC2 you control how much of that capacity you fill.
| Option | Billing unit | Charged when idle? | Unit of waste |
|---|---|---|---|
| Lambda | Requests + GB-seconds of duration | No | Paid wait time inside each invocation |
| Fargate | vCPU-seconds + GB-seconds per task | Yes, while the task runs | Reserved task capacity left unused |
| EC2 | Instance running time | Yes, while the instance runs | Instance capacity left unused |
Why does steady traffic change the serverless cost math?
Lambda's standard model runs one request per execution environment at a time, and bills each invocation for its full duration at the memory size you configured. A typical API handler spends most of that duration waiting: a database query, a call to another service, a token check. The CPU is idle, but the billing clock keeps running. You pay for that wait on every request, separately, so Lambda compute cost grows roughly linearly with request count × average duration.
A Fargate task or EC2 instance runs a long-lived process with an async runtime or thread pool. While one request waits on the database, the process serves others. The wait overlaps, and you pay for the wall-clock time of the machine once, no matter how many requests share it.
| Time → | t1 | t2 | t3 | t4 | Billed |
|---|---|---|---|---|---|
| Lambda env A (req 1) | CPU | wait DB | wait DB | CPU | 4 units |
| Lambda env B (req 2) | CPU | wait DB | wait DB | CPU | 4 units |
| Lambda env C (req 3) | CPU | wait DB | wait DB | CPU | 4 units |
| Lambda total | 12 units | ||||
| One container process (reqs 1–3) | CPU 1,2,3 | wait (all) | wait (all) | CPU 1,2,3 | 4 units |
The table shows how the cost model works. It does not mean a container is three times cheaper. Per-unit prices differ, and a container needs headroom for peaks.
The comparison flips when traffic is low, bursty or mostly idle. An instance or task bills while it sits empty overnight or between spikes. Lambda bills nothing between requests. When your utilization is low, paying per invocation costs less than paying for capacity that sits unused most of the time.
PER-INVOCATION BILLING (Lambda: one request per environment at a time)
req 1 ──► ┌─ env A ───────────────────┐ ──► DB / downstream
│ CPU │ wait │ wait │ CPU │ billed: 4 units
└───────────────────────────┘
req 2 ──► ┌─ env B ───────────────────┐ ──► DB / downstream
│ CPU │ wait │ wait │ CPU │ billed: 4 units
└───────────────────────────┘
req 3 ──► ┌─ env C ───────────────────┐ ──► DB / downstream
│ CPU │ wait │ wait │ CPU │ billed: 4 units
└───────────────────────────┘
total: 12 units, wait paid 3x
ONE LONG-LIVED PROCESS (Fargate task or EC2 instance)
req 1 ──┐ ┌─ one process (async) ─────┐
req 2 ──┼►│ CPU │ wait │ wait │ CPU │ ──► DB / downstream
req 3 ──┘ │ 1,2,3│ all │ all │ 1,2,3│ billed: 4 units
└───────────────────────────┘
total: 4 units, wait paid once
t1 t2 t3 t4 ──► time
Lambda bills the database wait separately in each execution environment, while one long-lived container or instance process overlaps the wait for concurrent requests and pays for it once (illustrative units, not real prices).
How do you calculate the serverless cost break-even point?
Lambda's cost grows in proportion to traffic. Fargate and EC2 cost grows in steps, with a floor. The break-even point is where Lambda's per-request cost line crosses that floor.
Inputs
- R: average requests per second
- D: average billed duration in seconds
- M: configured Lambda memory in GB
- C: requests per second one task or instance sustains at acceptable p99 latency
- U: target utilization, such as 0.6
- N_min: minimum task or instance count for availability
- S: seconds per month
- H: hours per month
Monthly cost formulas
- Lambda = R × S × (P_request + D × M × P_GB-second)
- Fargate = max(N_min, ⌈R ÷ (C × U)⌉) × H × (vCPU × P_vCPU-hour + GB × P_GB-hour)
- EC2 = max(N_min, ⌈R ÷ (C × U)⌉) × H × P_instance-hour
Solving for the crossover
Set Lambda equal to Fargate's floor cost:
R* = N_min × H × K_task ÷ (S × (P_request + D × M × P_GB-second))
K_task is the hourly price of one Fargate task.
Above R*, compare marginal costs. Lambda's cost per request is P_request + D × M × P_GB-second. Fargate's is K_task ÷ (3600 × C × U). If Lambda's figure is higher, Fargate stays cheaper at every rate beyond R*. Repeat the calculation with the EC2 instance price for the EC2 comparison.
The script that accompanies this section implements these formulas. It takes your inputs and your region's current prices, then prints all three monthly costs and R*.
Sensitivity
- Duration and memory multiply together in Lambda's cost. Doubling either one halves R*.
- C appears only on the container side. Its value comes from load testing, so an optimistic guess biases the result toward Fargate and EC2.
- Prices vary by region and change over time.
Rerun the model after any code change, runtime upgrade, memory retune or price update. Any of these can move the crossover by a large factor.
import math
# Inputs: replace with your own measured values
R = 50.0 # average requests per second
D = 0.120 # average billed duration, seconds
M = 0.5 # configured Lambda memory, GB
C = 40.0 # req/s one task or instance sustains at acceptable p99 (load test)
U = 0.6 # target utilization
N_MIN = 2 # minimum task/instance count for availability
H = 730 # hours per month
S = H * 3600 # seconds per month
# Prices: PLACEHOLDERS, not current list prices. Use your region's prices.
P_REQ = 0.20 / 1e6 # Lambda price per request
P_GBS = 0.0000167 # Lambda price per GB-second
TASK_VCPU, TASK_GB = 0.5, 1.0
P_VCPU_H, P_GB_H = 0.04, 0.0045 # Fargate per vCPU-hour, per GB-hour
P_EC2_H = 0.04 # EC2 price per instance-hour
K_TASK = TASK_VCPU * P_VCPU_H + TASK_GB * P_GB_H # hourly cost of one task
LAMBDA_PER_REQ = P_REQ + D * M * P_GBS # Lambda cost per request
def count(r): # tasks/instances needed, never below the availability floor
return max(N_MIN, math.ceil(r / (C * U)))
lam = R * S * LAMBDA_PER_REQ
far = count(R) * H * K_TASK
ec2 = count(R) * H * P_EC2_H
print(f"Monthly Lambda ${lam:,.2f} Fargate ${far:,.2f} EC2 ${ec2:,.2f}")
# Break-even against each floor: Lambda cost equals N_MIN always-on units
for name, hourly in (("Fargate", K_TASK), ("EC2", P_EC2_H)):
r_star = N_MIN * H * hourly / (S * LAMBDA_PER_REQ)
marginal = hourly / (3600 * C * U) # container cost per request above floor
stays = "stays cheaper" if LAMBDA_PER_REQ > marginal else "may lose again"
print(f"R* vs {name}: {r_star:.2f} req/s; above it {name} {stays}")
A runnable Python break-even model computing monthly Lambda, Fargate and EC2 costs and the crossover rate R, using placeholder prices you must replace.*
Worked example: an illustrative break-even estimate
Illustrative estimate (assumed numbers, not a benchmark). All unit prices below are placeholders. Replace them with current figures from the AWS pricing pages for your region before you draw any conclusion.
Assumed workload: 50 requests/second steady, 100 ms average duration, 512 MB memory, 30-day month. That gives 50 × 2,592,000 s = 129.6M requests/month.
Lambda (assumed $0.000017 per GB-second, $0.20 per million requests). Lambda bills only for the work done, so utilization does not enter the formula:
- Monthly cost = requests × duration (s) × memory (GB) × GB-second price + requests ÷ 1M × request price
- 129.6M × 0.1 × 0.5 × $0.000017 + 129.6 × $0.20 ≈ $136
Fargate and EC2 bill for provisioned capacity, so the formulas are:
- Per-task throughput = concurrent requests per task ÷ duration
- Tasks = max(multi-AZ minimum, ceil(average RPS ÷ (per-task throughput × target utilization)))
Assumptions: a target utilization of 50% to leave peak headroom, a minimum of 2 tasks for multi-AZ, a Fargate task at $0.03/hour and an EC2 instance at $0.08/hour.
| Option | Concurrency per task | Tasks | Monthly cost | Cost per 1M requests |
|---|---|---|---|---|
| Lambda | n/a | n/a | ~$136 | ~$1.05 |
| Fargate, async handler | 10 (100 RPS) | 2 (AZ floor) | ~$43 | ~$0.33 |
| Fargate, single-threaded or blocking | 1 (10 RPS) | 10 | ~$216 | ~$1.67 |
| EC2, async handler | 20 (200 RPS) | 2 (AZ floor) | ~$115 | ~$0.89 |
The third row shows why concurrency per task matters. A single-threaded runtime, blocking I/O or a memory-heavy handler caps each task at one request at a time. That forces five times more tasks than the async case, and Lambda becomes cheaper even at steady traffic. Lambda already bills each invocation individually, so low concurrency per task does not raise its cost the same way.
The AZ floor also sets a minimum bill for Fargate and EC2. Below the throughput of two tasks, you pay for that floor no matter how few requests you serve.
Which costs outside compute shift the comparison?
Compute is rarely the whole bill. Several surrounding charges scale differently depending on which option you pick, and at steady traffic they can matter as much as the compute rate.
| Cost item | How it bills | Scales with | Effect on break-even |
|---|---|---|---|
| API Gateway (typical Lambda front door) | Per request | Request count, linearly | Moves break-even toward lower traffic, because it grows with every request |
| Application Load Balancer (Fargate/EC2) | Hourly fee plus capacity units | Connections, bandwidth, rule evaluations | Gives a fixed floor, then rises slowly, so it costs less per request at high volume |
| NAT gateway | Hourly fee plus per-GB processed | Outbound bytes from private subnets | Penalises any VPC workload that calls external APIs. It applies to all three options |
| Log ingestion | Per GB ingested | Log lines per request multiplied by request count | Verbose per-request logging grows linearly regardless of where the code runs |
| Data transfer out | Per GB | Response size multiplied by request count | Mostly the same across options, so it shrinks the relative gap |
To estimate the gateway effect, compare monthly requests × gateway per-request price against the load balancer's hourly fee × hours plus its capacity-unit charges. Put your own region's prices into both expressions. Because API Gateway grows linearly with requests, it can move the crossover point by a large amount.
Provisioned concurrency changes Lambda's cost curve. You pay for configured concurrency for every hour it is enabled, whether or not requests arrive. In return, the duration rate is lower and initialised environments are already warm. This removes cold starts from your tail latency and reserves headroom below account concurrency limits. It also adds a fixed floor, so Lambda's cost starts to look like Fargate's. If your latency SLO requires provisioned concurrency sized close to peak, much of the pay-per-use advantage is gone.
How do Savings Plans, Reserved Instances and Spot change the result?
Commitment discounts can narrow that gap, but they do not apply evenly across the three options.
| Discount type | Lambda | Fargate | EC2 | Main risk |
|---|---|---|---|---|
| Compute Savings Plans | Yes (duration and provisioned concurrency; not request charges) | Yes | Yes | Paying for unused hourly commitment |
| EC2 Instance Savings Plans | No | No | Yes, one instance family in one region | Locked to that family and region |
| Reserved Instances | No | No | Yes | Locked to instance attributes. Convertible RIs can be exchanged. |
| Spot capacity | No | Fargate Spot (ECS only) | EC2 Spot | Interruption with short notice |
The EC2-only options usually give the deepest discounts, which widens EC2's lead at steady load. They also carry the most stranded-cost risk. You commit to an hourly spend for one or three years and pay it whether you use it or not. If traffic drops, or you move from EC2 to containers or functions, an Instance Savings Plan or a Standard RI keeps billing. Compute Savings Plans follow your usage across EC2, Fargate and Lambda. That flexibility is why many teams commit only to the baseline they are confident in.
To test a commitment, divide what you pay for it by the usage it actually covers:
effective rate = committed spend ÷ covered usage
If covered usage falls, the effective rate rises. Below some level of usage, on-demand pricing would have cost less.
Spot suits stateless API tasks behind a load balancer only if they can drain within the interruption notice. Set the deregistration delay shorter than that window and keep an on-demand baseline that can carry your SLO by itself.
Discount levels, coverage rules and notice periods change over time. Check current AWS pricing and terms before you model any of these options.
How much engineering time does each option cost to run?
Compute pricing leaves out the hours your team spends keeping the platform healthy. Add those hours to the model as their own line item.
On EC2 you own the operating system. That means patching it, building and rolling out AMIs, replacing unhealthy or retired instances, tuning autoscaling policies and warm-up times, and planning capacity ahead of launches. Fargate removes the host layer, but you still size tasks, patch base images and tune service scaling. Lambda narrows the work further, to memory settings, concurrency limits and timeouts. On all three, you still patch your own code and dependencies.
EC2's lower raw price at high utilization only matters if the savings exceed this labor. For a small team, a few hours a month of patching and instance incidents can erase the gap. The work also arrives unevenly: one bad AMI rollout can consume a week.
To estimate your own figure, log a month of platform tickets, pages and maintenance tasks by category. Then calculate:
Monthly ops cost = ops hours per month × loaded hourly rate
Illustrative estimate (assumed numbers, not a benchmark): Assume EC2 takes 12 hours a month, Fargate takes 4 hours, and the loaded rate is $100 per hour. Ops cost is $1,200 for EC2 and $400 for Fargate. EC2 compute must therefore be at least $800 a month cheaper before it comes out ahead.
Migration is a one-time cost, so spread it over the period you expect to stay:
Amortized migration = (migration hours × rate) ÷ months on the platform
Include these tasks in migration hours:
- Refactoring handlers to be stateless and short-lived for Lambda, or into long-lived processes with graceful shutdown for Fargate or EC2.
- Changing CI/CD pipelines.
- Rebuilding logs, metrics, traces and alerts for the new runtime.
When should you choose Lambda, Fargate or EC2, and when should you avoid each?
A decision procedure
- Measure the traffic profile. Pull several weeks of request counts per minute, average duration, and memory per request. Compute the peak-to-average ratio. A ratio near 1 suggests capacity you can provision. A high ratio means provisioned capacity sits idle between peaks.
- Run the cost model for all three options using measured inputs, not vendor defaults.
- Price Fargate and EC2 at realistic utilization. Autoscaling takes time to react, so tasks and instances must carry headroom to absorb a burst before new capacity arrives. If you size for 60% target utilization, you pay for the remaining 40% all the time. Lambda bills per invocation and scales to zero, so it carries no idle headroom. Comparing it against a cluster at 100% utilization flatters the cluster.
- Add non-compute and operational costs from the earlier sections. These include load balancers, NAT, logging, and engineering time.
- Recheck the model when traffic volume, request duration, or memory size changes materially. A change in any of them can move you across the break-even point.
| Option | Fits | Avoid when |
|---|---|---|
| Lambda | Spiky or idle-heavy APIs, low average load | Load is high and steady, or requests spend long periods waiting on I/O, which is billed as duration |
| Fargate | Moderate steady load, teams that want containers without managing hosts | Traffic is mostly idle, or utilization is high enough that EC2's lower unit price dominates |
| EC2 | High, steady utilization with a team able to patch, scale, and secure hosts | The team lacks the capacity to operate it, or traffic is too bursty to keep instances busy |
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 vs ec2 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.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
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.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- 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.