How do Lambda, Fargate and EC2 bill for a backend API?

Each service charges for a different unit, and that unit determines how cost tracks traffic.

Lambda charges a fee per request plus a duration charge. The duration charge is execution time multiplied by allocated memory, expressed in GB-seconds. CPU scales with the memory setting, so you don't buy it separately. When traffic stops, the bill stops too, apart from extras such as provisioned concurrency.

Fargate charges for the vCPU and memory you configure on each task, for as long as the task runs. A task serving one request per minute costs the same as one serving at full capacity. You pay for reserved capacity, not for work done.

EC2 charges for instance time based on the instance type. Load doesn't affect the price. You decide how many containers or processes to pack onto each instance, and how well you pack them sets your real cost per request.

Model Billing unit Cost at zero traffic Cost driver
Lambda Requests + GB-seconds Near zero Request volume × duration × memory
Fargate vCPU-time + memory-time per task Cost of the minimum running tasks Number of tasks and their size
EC2 Instance time Cost of running instances Instance count and type

This makes Lambda a variable-cost model. Fargate and EC2 are fixed cost per unit of capacity: you pay for capacity whether or not traffic uses it.

The actual rates differ by region and change over time, so check the current regional pricing pages before running any numbers. Architecture also affects price. ARM (Graviton) options are usually priced below x86 on all three services, so compare like with like.

Why is utilization the variable that decides the break-even?

Lambda bills per invocation and per unit of execution time, so its cost line climbs with traffic. Twice the requests cost roughly twice as much. A Fargate task or EC2 instance costs the same per hour whether it serves one request or saturates its CPU, so its cost is a step function: flat until you need another task or instance. The break-even is where those lines cross. That happens when traffic is steady enough to keep provisioned capacity busy most of the hour. Below that point, Lambda's idle cost of zero wins. Above it, you are paying Lambda a premium for capacity you could have rented in bulk.

Duration is the lever teams most often misjudge. Lambda charges for wall-clock time per execution environment, and each environment handles one request at a time. A handler that spends most of its time waiting on a database query or a downstream API pays for that wait at its full memory allocation. A container running an async or threaded server handles many requests during the same wait, so the cost of that idle time is spread across all of them. For I/O-bound APIs, this pushes the break-even toward lower traffic than a CPU-only comparison suggests.

Real container utilization is also lower than the theoretical figure. Autoscaling reacts after load changes, so you keep headroom to absorb spikes while new tasks start. Minimum task counts for availability add more idle capacity. A break-even that assumes 80% utilization looks very different when the fleet actually averages half that. Use the utilization you have measured, not the utilization you hope for.

LAMBDA  (1 request per environment; each billed for its full duration)

 req A --->+--------------+         +-------------------+
           | env 1: [A]   |-------->|                   |
 req B --->+--------------+         |                   |
           | env 2: [B]   |-------->|  Database or      |
 req C --->+--------------+         |  downstream API   |
           | env 3: [C]   |-------->|                   |
           +--------------+         |  (wait time)      |
   cost: 3 x duration x memory      |                   |
                                    |                   |
FARGATE (1 task multiplexes         |                   |
         requests during the wait)  |                   |
                                    |                   |
 req A --->+--------------+         |                   |
 req B --->| task 1       |========>|                   |
 req C --->| async server |         |                   |
           | [A][B][C]    |         +-------------------+
           +--------------+
   cost: 1 task-hour, busy or idle

UTILIZATION OF PROVISIONED CONTAINER CAPACITY
 +--------------------------------------------------------------+
 |######## used ########|..... headroom .....|... min tasks ....|
 +--------------------------------------------------------------+
  break-even math must use measured 'used', not a planned 80%

Lambda bills each execution environment for the full duration of its single request, including time spent waiting on I/O, while one container shares that wait across many concurrent requests; autoscaling headroom and minimum task counts lower the share of provisioned capacity that does useful work.

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

Start with one formula per platform, expressed in the same unit: dollars per month.

Lambda: cost_L = R × (P_req + D × M × P_gbs)

  • R is requests per month.
  • P_req is the per-request fee.
  • D is the average billed duration in seconds.
  • M is the configured memory in GB.
  • P_gbs is the per-GB-second rate for your region and architecture.

Cost is linear in R with no fixed term. That is why Lambda wins at low volume.

Containers: cost_C = N × H × P_hr

  • N is the number of tasks or instances.
  • H is the hours they run per month.
  • P_hr is the hourly rate. For Fargate, that is vCPU-hours plus GB-hours combined.

Don't guess N. Derive it from load using Little's law. In-flight requests equal arrival rate times latency, so:

N = max(N_min, ceil(λ × D_c / (C × U)))

  • λ is peak requests per second.
  • D_c is latency on the container.
  • C is per-task concurrency, meaning how many requests one task can serve at once.
  • U is your measured utilization ceiling.
  • N_min is the floor you keep for availability.

C is the variable that captures multiplexing. Lambda bills each concurrent request separately. A container with C = 50 spreads one hourly rate across fifty overlapping requests.

Break-even: set the two costs equal and solve for R:

R* = N × H × P_hr / (P_req + D × M × P_gbs)

N moves in steps, so R* is not a single number. Compute it for each fleet size. The crossover is the first step where container cost drops below Lambda cost and stays there.

The script that accompanies this section takes every symbol above as a parameter. Feed it current regional prices and your own latency and concurrency metrics, not defaults. It also leaves out free tiers, which matter for prototypes and not for production APIs.

# Usage (placeholder prices; use your region's current rates):
# python breakeven.py --p-req 0.0000002 --d 0.12 --m 0.5 --p-gbs 0.0000167 \
#   --p-hr 0.05 --d-c 0.08 --c 50 --u 0.6
import argparse, math

ap = argparse.ArgumentParser(description="Lambda vs container break-even (USD/month)")
for flag in ["--p-req", "--d", "--m", "--p-gbs", "--p-hr", "--d-c", "--c", "--u"]:
    ap.add_argument(flag, type=float, required=True)  # symbols from the formulas
ap.add_argument("--hours", type=float, default=730)        # H: hours per month
ap.add_argument("--n-min", type=int, default=2)            # availability floor
ap.add_argument("--peak-factor", type=float, default=3.0)  # peak rps / average rps
ap.add_argument("--max-rps", type=int, default=2000)       # upper bound of the sweep
a = ap.parse_args()

per_req = a.p_req + a.d * a.m * a.p_gbs  # Lambda cost of one request
secs = a.hours * 3600
crossover, steps = None, {}
for avg_rps in range(1, a.max_rps + 1):
    R = avg_rps * secs                       # requests per month
    lam = avg_rps * a.peak_factor            # peak arrival rate
    # Little's law; fleet sized for peak and held all month (conservative, no autoscaling)
    n = max(a.n_min, math.ceil(lam * a.d_c / (a.c * a.u)))
    cost_l, cost_c = R * per_req, n * a.hours * a.p_hr
    steps.setdefault(n, cost_c / per_req)    # R* for this fleet size
    if cost_c < cost_l:
        crossover = crossover or (avg_rps, R, n, cost_l, cost_c)
    else:
        crossover = None                     # Lambda cheaper again: crossover must stay

print("tasks  R* (requests/month where this fleet ties Lambda)")
for n, r_star in sorted(steps.items()):
    print(f"{n:5d}  {r_star:,.0f}")
if crossover:
    rps, R, n, cl, cc = crossover
    print(f"Containers stay cheaper from ~{rps} avg rps ({R:,.0f} req/month), "
          f"{n} tasks: Lambda ${cl:,.2f} vs containers ${cc:,.2f}")
else:
    print("Lambda is cheaper across the whole sweep; raise --max-rps")

A parameterized Python script that sizes the container fleet with Little's law, including per-task concurrency, computes R for each fleet-size step, and reports the first request rate at which containers become cheaper than Lambda and stay cheaper.*

Worked example: how sensitive is the crossover to duration and memory?

Illustrative estimate. None of these prices are current list prices. Substitute your region's rates.

Assumed inputs:

  • Lambda: $0.0000167 per GB-second plus $0.20 per million requests, at 512 MB and 100 ms average duration.
  • Fargate: $0.05 per task-hour. Each task sustains 50 req/s at target utilization.
  • Availability floor: two tasks, so Fargate costs at least $73 per month (730 hours) whatever the traffic.

Lambda costs 1M × 0.1 s × 0.5 GB × $0.0000167 + $0.20 ≈ $1.04 per million requests. The break-even is $73 ÷ $1.04 ≈ 70.5M requests per month.

Scenario Lambda $/M req Break-even (M req/month) Avg req/s
Baseline 1.04 70.5 26.8
Duration doubles (200 ms) 1.87 39.0 14.8
Memory halves (256 MB) 0.62 118 45.0
+$20/month provisioned concurrency 1.04 + $20 fixed 51.2 19.5
Commitment multiplier k on Fargate 1.04 70.5 × k 26.8 × k

Duration. Doubling duration nearly halves the break-even because Lambda bills wall-clock time, including time spent waiting on I/O. A container task keeps serving other requests during that wait. If the extra time is CPU work, per-task throughput also falls, which offsets some of the shift.

Memory. Halving memory looks cheaper on paper. However, Lambda allocates CPU in proportion to memory, so duration often rises and eats the saving.

Provisioned concurrency. This adds a fixed cost to the Lambda side. The crossover moves toward containers because Lambda now carries a fixed cost without matching their per-request efficiency.

Commitments and interruptible capacity. Savings plans, reserved capacity and spot or interruptible capacity act as a multiplier k < 1 on the fixed side. They pull the break-even lower. Spot only fits workloads that tolerate interruption. Check which side a given commitment discounts, because some schemes also cover function compute.

What costs do compute-only comparisons leave out?

A compute-only model compares vCPU-seconds and GB-seconds. At low traffic, the fixed lines around compute often cost more than compute itself.

Front door. API Gateway bills per request, so it scales to zero with traffic. An Application Load Balancer bills hourly plus capacity units, so it costs money even when idle. Networking. Tasks or functions in private subnets that call external APIs need a NAT gateway, which charges hourly and per GB processed. Cross-AZ traffic between your service and its database also adds per-GB charges. Logging. Ingestion is billed per GB. A verbose request log can cost more than the function that writes it. Availability floor. Two Fargate tasks across two AZs run all day, every day, whatever the traffic.

Cost line Lambda Fargate EC2
Front door Per-request gateway Hourly load balancer Hourly load balancer
Always-on minimum None (unless provisioned concurrency) ≥2 tasks for HA ≥2 instances for HA
Engineering overhead Cold starts, concurrency limits Autoscaling and task sizing Patching, AMIs, capacity

Convert overhead and migration into money with one formula:

True monthly cost = compute + front door + NAT + logs + (ops hours × hourly rate) + (migration hours × hourly rate ÷ payback months)

Illustrative estimate (assumed numbers, not a benchmark): Assume a move from Lambda to Fargate saves $40/month on compute. Assume a $100/hour engineer rate, 3 extra ops hours per month for tuning, and an 80-hour migration amortized over 24 months. That adds about $300 + $333 per month, so the net result is a loss of roughly $590/month. Migration work includes rewriting request-scoped handlers into long-running servers, changing tooling, and regression testing. For small workloads, that cost alone can cancel out the compute savings.

When should you choose Lambda, Fargate or EC2, and when should you avoid each?

Model each API with two numbers instead of a monthly request total: the average request rate and the peak-to-average ratio. Two services with identical monthly volume can land on opposite sides of the break-even. A ratio near 1 means provisioned capacity stays busy. A high ratio means you either pay for idle headroom or depend on autoscaling that lags behind the spike. Monthly totals hide that difference.

Option Fits best Avoid if
Lambda Spiky or bursty traffic, near-zero overnight load, async jobs Throughput stays high all day, cold starts break latency targets, or you need long-lived connections
Fargate Flat, sustained throughput with modest ops capacity Traffic sits idle most hours, or nobody owns task sizing and scaling policies
EC2 Teams that keep instances highly utilized and staff patching, image builds and capacity planning The team is small, utilization is low, or no one is on call for hosts

EC2's lower unit price only pays off when both conditions hold: the instances stay busy, and the operational work is already budgeted.

A hybrid setup is the main alternative to choosing one option. Run hot, steady endpoints on containers, and route spiky or asynchronous paths such as webhooks, batch fan-out and scheduled jobs to Lambda. The trade-off is two deployment models, two observability setups and more failure modes to understand. That overhead is only worth it when each path is large enough to matter.

Cost is also only one constraint. Moving to save compute dollars can increase tail latency, reduce isolation or slow down developers. Price those effects before treating the cheapest option as the right one.

How can you keep your break-even analysis current without wasting engineering time?

Treat the break-even as a model that runs on a schedule, not a decision you revisit in meetings.

Feed it measured inputs

Pull p50 and p95 duration and peak memory from the metrics you already collect. Lambda reports billed duration and max memory used for every invocation. For containers, use request latency and per-task memory from your existing monitoring. Use p50 for the cost estimate and p95 to check headroom. Memory on Lambda is a sizing choice, so model the size you actually run, not the default.

Set triggers, not calendars

Store the computed crossover as a request rate. Then alert when sustained traffic moves past a band around it, for example ±30%. A band avoids recomputing on every spike. Also rerun the model when AWS publishes price changes, when you add a region, or when you change architecture (for example, moving to Arm). Each of these changes the inputs, and stale inputs give stale answers.

Keep migration cheap

The model only helps if acting on it is affordable. To make that true:

  • Keep handlers stateless.
  • Put the application behind a framework adapter, so the same code starts from a function handler or a container entrypoint.
  • Emit identical logs, metrics and traces in both modes, so you can compare latency and errors directly after a switch.

Why automate

Ad hoc debates repeat the same estimates with different assumptions each time. Premature migrations spend weeks chasing savings that traffic never delivers. A scheduled model with thresholds turns both into a dashboard check. Engineers only spend time when the numbers say a move pays for itself.

import math

HOURS = 730                # hours per month used for both models
SECONDS = HOURS * 3600

# Measured inputs: replace with values from your own metrics.
# p50 drives cost; task_rps is the load one task sustains while p95 stays within SLO.
M = {"p50_ms": 45, "lambda_mem_gb": 0.5, "task_rps": 80,
     "task_vcpu": 0.5, "task_gb": 1.0, "min_tasks": 2}

# Placeholder unit prices: load current prices for your region and architecture.
P = {"per_req": 0.20e-6, "per_gb_s": 0.0000166667,
     "per_vcpu_h": 0.04, "per_gb_h": 0.0045}

def lambda_month(rps):
    per_req = P["per_req"] + (M["p50_ms"] / 1000) * M["lambda_mem_gb"] * P["per_gb_s"]
    return rps * SECONDS * per_req

def fargate_month(rps):
    # Tasks scale in steps, with a floor kept for availability.
    tasks = max(M["min_tasks"], math.ceil(rps / M["task_rps"]))
    return tasks * HOURS * (M["task_vcpu"] * P["per_vcpu_h"] + M["task_gb"] * P["per_gb_h"])

def crossover_rps(limit=10_000):
    # Lowest sustained rate where Lambda costs more than Fargate.
    return next((r for r in range(1, limit) if lambda_month(r) > fargate_month(r)), None)

def check(current_rps, platform, band=0.30):
    x = crossover_rps()
    if x is None:
        return "no crossover in range; recompute after any price, region or architecture change"
    if platform == "lambda" and current_rps > x * (1 + band):
        return f"sustained {current_rps} rps exceeds band above crossover {x}: review Fargate"
    if platform == "fargate" and current_rps < x * (1 - band):
        return f"sustained {current_rps} rps is below band under crossover {x}: review Lambda"
    return f"within band of crossover {x} rps: no action"

print(check(current_rps=120, platform="lambda"))

A scheduled break-even check that computes the Lambda/Fargate crossover from measured p50 duration, memory and per-task throughput, using placeholder unit prices, and flags a review only when sustained traffic leaves a ±30% band on the more expensive side.

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.