Who should use this break-even analysis?
This analysis is for engineers and technical leads who run, or are about to build, an HTTP API on AWS and need to choose between Lambda and a container platform such as Fargate, or ECS or Kubernetes on EC2. It is most useful in four situations:
- A new API where you need a defensible starting platform before traffic data exists.
- A growing Lambda API whose bill has started to climb with request volume.
- An underused container fleet that runs mostly idle outside business hours.
- A planned migration in either direction, where you need to know whether the saving justifies the engineering effort.
If your API serves a few thousand requests a day, you can probably skip the modelling. Lambda's idle-time advantage will dominate, and the absolute numbers will be too small to matter. The analysis earns its keep once monthly compute spend is large enough that a wrong choice costs more than the time spent running the numbers.
How does the break-even comparison work?
The method models each platform as a monthly cost function of traffic and finds where the two curves cross.
- Model Lambda as a straight line. Cost grows in proportion to request count. Each request carries a fixed cost made up of the invocation charge, the GB-seconds it consumes, the front-door charge and its log volume. At zero traffic the cost is close to zero.
- Model containers as a staircase. Cost depends on how many tasks you must run. That number is set by peak load, redundancy and headroom, not by total requests. A minimum fleet costs money even at zero traffic, and each added task adds one more step.
- Find the crossover. At low volume, Lambda's line sits below the container floor. As volume grows, the line rises until it crosses the staircase. Past that point, containers are cheaper per request because the fixed cost is spread over more traffic.
- Stress-test the inputs. Duration, memory, peak-to-average ratio and per-container concurrency each shift the crossover. You vary them one at a time to see which assumptions the decision depends on.
- Add non-compute costs. Engineering time, operational effort and migration cost go into the comparison last, as a payback calculation.
The sections below cover each step in that order.
How does Lambda pricing work for an API?
Lambda bills an API on two meters. The first is a flat per-request charge, applied to every invocation regardless of what the handler does. The second is compute, billed in GB-seconds: the memory you configure multiplied by the billed duration of each invocation. The memory setting is the input you control directly. Raising it also allocates more CPU proportionally, so a higher setting can shorten duration enough to offset part of its own cost.
Billed duration is wall-clock time, not CPU time. A handler that spends 180 ms waiting on a database query or a third-party API pays for those 180 ms at full memory size, even though the CPU sits idle. I/O-bound APIs are therefore often more expensive on Lambda than their actual compute work would suggest.
The function is only one part of the request path. Most HTTP APIs sit behind API Gateway, which adds its own per-request charge. At typical API workloads with short handlers and modest memory, that charge can equal or exceed the Lambda compute bill. Add these to the per-request side as well:
- Data transfer out to clients and across network boundaries.
- Logging volume, because log ingestion and storage are priced per GB, and verbose per-request logs scale linearly with traffic.
- Tracing, which is charged per trace recorded or scanned.
If you need to mitigate cold starts, provisioned concurrency adds a fixed charge for every hour it is configured, whether or not traffic arrives. That cost behaves more like a container than like pay-per-use.
Pull current rates from the AWS pricing page for your region before running any numbers. Do not rely on figures in this article.
How does container pricing work, and why is fleet size set by peak load?
Containers flip the model. Whether tasks run on Fargate or on EC2 instances under ECS or Kubernetes, you pay for provisioned vCPU and memory per unit of time. An idle task at 3 a.m. costs the same as a saturated one at noon.
That makes fleet size the real cost driver, and average load does not set it. Four things do:
- Peak RPS. The fleet must absorb the busiest minutes, not the daily mean.
- Redundancy floor. You need at least one task per availability zone. Across three AZs that means three tasks running even at zero traffic.
- Deploy surge. Rolling deploys start new tasks before draining old ones, so capacity briefly exceeds steady state.
- Autoscaling headroom. Scaling reacts in minutes, not milliseconds. You target a utilization below 100%, for example around 60–70%, so the fleet can absorb a spike while new tasks start.
Concurrency offsets that overhead. A container handling I/O-bound requests, which spend most of their time waiting on a database or downstream API, serves many requests at once. Each Lambda execution environment serves one request at a time. With 200 requests in flight, you have 200 environments, and each one bills for its full duration, including the time spent waiting.
API Gateway + Lambda
client --> API Gateway --------> Lambda (1 request per environment)
[$ per request] [$ per request + $ per GB-second]
Load balancer + container fleet
client --> Load balancer -------> Container tasks (many requests per task)
[$ per hour + [$ per vCPU-hour + $ per GB-hour,
usage-based units] billed whether idle or busy]
API GATEWAY + LAMBDA
+------------------+
+--->| Lambda env 1 | 1 request
+-------------+ | +------------------+
client --->| API Gateway |---+--->| Lambda env 2 | 1 request
| $ / request | | +------------------+
+-------------+ +--->| Lambda env N | 1 request
+------------------+
$ / request + $ / GB-second
(I/O wait time still bills)
LOAD BALANCER + CONTAINER FLEET
+------------------+
+--->| Task, AZ a | many requests
+-------------+ | +------------------+
client --->| Load |---+--->| Task, AZ b | many requests
| balancer | | +------------------+
| $ / hour + | +--->| Task, AZ c | many requests
| usage units | +------------------+
+-------------+ $ / vCPU-hour + $ / GB-hour
(billed whether idle or busy)
Fleet size set by:
peak RPS + 1 task per AZ
+ deploy surge + scaling headroom
API Gateway and Lambda charge per request, and each execution environment bills for one request at a time. A load balancer and container fleet bill per hour for provisioned capacity, which is sized for peak load and redundancy rather than average traffic.
How do you calculate the break-even point between Lambda and containers?
Treat each option as a monthly cost function, then find where the two functions cross.
Lambda scales linearly with request count N:
C_lambda = N × (r_req + d × m × r_gbs + r_front + b × r_log)
Here d is the average billed duration in seconds, m is memory in GB, r_front is the per-request price of the API front door, and b × r_log is the log volume per request times the ingestion price. Logging is easy to forget, but at high volume it can rival compute.
Containers are a step function driven by peak load, not by N:
C_containers = max(min_tasks, ⌈peak_RPS × headroom / RPS_per_task⌉) × r_task × 730 + C_lb
To connect peak load to N, write peak_RPS = (N / 2,628,000) × peak_to_avg. The constant 2,628,000 is the number of seconds in a 730-hour month. Because the container curve has steps, there is no clean closed-form solution. The script below sweeps N and reports the first volume at which Lambda costs more. Replace every placeholder rate with your provider's current prices.
Assumed inputs (placeholders, not real prices):
- Lambda: $0.20 per million requests, $0.0000167 per GB-second, 100 ms duration, 0.5 GB memory
- Front door: $1.00 per million requests
- Logs: 1 KB per request at $0.50 per GB
- Containers: $0.05 per task-hour, 100 RPS per task, 1.5× headroom, 3× peak-to-average, minimum 2 tasks
- Load balancer: $20 per month
Result (illustrative estimate): Lambda costs about $2.54 per million requests. The container floor is $93 per month. The lines cross at roughly 37 million requests per month, which is about 14 average RPS. Past that point, each added task covers about 22 average RPS for $36.50. Lambda would charge about $148 for the same traffic, so the gap between the two keeps growing.
import math
R_REQ = 0.20 / 1e6 # Lambda $ per request
R_GBS = 0.0000167 # Lambda $ per GB-second
DURATION_S = 0.100 # average billed duration (s)
MEMORY_GB = 0.5
R_FRONT = 1.00 / 1e6 # API front door $ per request
LOG_GB_PER_REQ = 1e-6 # ~1 KB of logs per request
R_LOG = 0.50 # log ingestion $ per GB
R_TASK = 0.05 # container $ per task-hour
RPS_PER_TASK = 100
HEADROOM = 1.5
PEAK_TO_AVG = 3.0
MIN_TASKS = 2
C_LB = 20.0 # load balancer $ per month
HOURS = 730
SECONDS = HOURS * 3600 # 2,628,000 s in a 730-hour month
PER_REQ = R_REQ + DURATION_S * MEMORY_GB * R_GBS + R_FRONT + LOG_GB_PER_REQ * R_LOG
def lambda_cost(n):
return n * PER_REQ # linear in request count
def container_cost(n):
peak_rps = (n / SECONDS) * PEAK_TO_AVG
tasks = max(MIN_TASKS, math.ceil(peak_rps * HEADROOM / RPS_PER_TASK))
return tasks * R_TASK * HOURS + C_LB # step function of peak load
for n in range(0, 1_000_000_000, 100_000):
if lambda_cost(n) > container_cost(n):
print(f"Lambda per million: ${PER_REQ * 1e6:.2f}")
print(f"Break-even ~{n / 1e6:.1f}M req/month (~{n / SECONDS:.1f} avg RPS)")
print(f"Lambda ${lambda_cost(n):.2f} vs containers ${container_cost(n):.2f}")
break
A Python sweep of both monthly cost functions with placeholder rates, reporting the first request volume where Lambda costs more than containers (illustrative estimate).
Which inputs move the break-even point the most?
That 14 RPS figure is only as reliable as the four inputs behind it. Changing each one while holding the others fixed shows which assumptions deserve the most scrutiny.
| Change from baseline (illustrative estimate) | Lambda cost | Container cost | Crossover moves to |
|---|---|---|---|
| Average duration doubles | Roughly doubles | Unchanged if CPU isn't the bottleneck | ~8 RPS |
| Memory size doubles | Roughly doubles | Unchanged if task size holds | ~8 RPS |
| Peak-to-average ratio doubles | Unchanged | Fleet doubles | ~28 RPS |
| Per-container concurrency halves | Unchanged | Fleet doubles | ~28 RPS |
| Per-container concurrency rises 4x | Unchanged | Fleet shrinks to a quarter | ~4 RPS |
Concurrency is often the biggest lever because its plausible range is the widest. Duration and memory usually vary within a factor of two or three. A container's concurrency depends on runtime and I/O model, so a blocking, thread-per-request service and an async one on the same hardware can differ by an order of magnitude. A Lambda execution environment handles one request at a time no matter how much of that time it spends waiting on I/O.
The model has three blind spots:
- Averages hide tail latency. Lambda bills every slow request in full, and containers must be sized for p99 latency, not the mean.
- Downstream slowdowns hit the two models differently. If a database slows down, Lambda duration and cost rise immediately. A container fleet absorbs the slowdown at no extra cost until it saturates, and then latency degrades sharply.
- Full utilization is a fiction. Containers need headroom for deploys, failover and scaling lag. If you model them at theoretical capacity, you overstate their cost advantage. Plan for 60–70% utilization instead.
When should you use Lambda, and when should you avoid it?
Traffic shape matters as much as total volume. Lambda bills per invocation, so idle hours cost nothing. A container fleet bills for every hour it runs, so it only pays off when it stays busy.
To estimate utilization, divide average RPS by the RPS your fleet can serve at its target latency. Illustrative estimate: an API averages 40 RPS. It runs four tasks, and each task sustains 100 RPS. Utilization is 40 / 400 = 10%, which means you pay for nine idle units of capacity for every busy one. If the same fleet averaged 300 RPS, utilization would be 75%, and containers would likely be cheaper. Use a full week of request metrics so weekends and nightly lulls count toward the average.
Lambda becomes the wrong choice in three situations:
- Database connections. Each concurrent execution can open its own connection, so a spike can exhaust the database's connection limit. Adding a pooling layer fixes this, but it is extra infrastructure and extra cost.
- Latency SLOs. Cold starts break tight p99 targets. Provisioned concurrency removes cold starts, but it bills whether you use it or not, which erodes Lambda's idle advantage.
- Concurrency quotas. Spikes beyond your account's concurrency quota are throttled, not queued.
Containers fail on spikes too. If autoscaling takes minutes to add capacity, a burst can overrun the fleet before new tasks are healthy.
| Workload | Better fit | Why |
|---|---|---|
| Internal tools, webhooks, near-idle APIs | Lambda | Idle time is free |
| Bursty, unpredictable traffic | Lambda | Scales per request without headroom |
| Sustained high-volume APIs | Containers | High utilization spreads fixed cost |
| Strict latency or heavy database use | Containers | No cold starts; stable connection pools |
from datetime import datetime, timedelta, timezone
import boto3
LOAD_BALANCER = "app/orders-api-alb/0123456789abcdef" # placeholder ALB dimension
TASKS = 4 # tasks currently provisioned
RPS_PER_TASK = 100 # measured in your own load test at target p99
cw = boto3.client("cloudwatch")
end = datetime.now(timezone.utc)
start = end - timedelta(days=7) # full week so weekends and nights count
resp = cw.get_metric_statistics(
Namespace="AWS/ApplicationELB",
MetricName="RequestCount",
Dimensions=[{"Name": "LoadBalancer", "Value": LOAD_BALANCER}],
StartTime=start,
EndTime=end,
Period=3600, # hourly buckets: 168 datapoints for a week
Statistics=["Sum"],
)
hourly = [p["Sum"] for p in resp["Datapoints"]]
if not hourly:
raise SystemExit("No datapoints returned; check the LoadBalancer dimension.")
avg_rps = sum(hourly) / (7 * 24 * 3600)
peak_rps = max(hourly) / 3600 # peak hourly average; real bursts are sharper
capacity = TASKS * RPS_PER_TASK
print(f"average RPS: {avg_rps:.1f}")
print(f"peak-hour RPS: {peak_rps:.1f}")
print(f"fleet capacity: {capacity} RPS")
print(f"utilization: {avg_rps / capacity:.0%}")
print(f"peak/avg ratio: {peak_rps / avg_rps:.1f}x" if avg_rps else "no traffic")
A boto3 script that pulls a week of hourly ALB request counts from CloudWatch and divides average RPS by provisioned fleet capacity to estimate utilization and the peak-to-average ratio.
What levers reduce cost on each side?
Each lever changes one term in the cost models. For Lambda, that is requests × per-request price plus requests × duration × memory (GB) × GB-second price. For containers, it is instance or task count × hours × hourly rate.
| Lever | Side | Variable it changes | Why it works |
|---|---|---|---|
| Right-size memory | Lambda | Memory, duration | CPU scales with memory, so more memory can shorten CPU-bound runs enough to lower GB-seconds. Less memory saves on I/O-bound functions. |
| ARM vs x86 | Lambda | GB-second price | ARM is usually priced lower per GB-second if your runtime and native dependencies support it. |
| Cut time blocked on I/O | Lambda | Duration | You pay for wall-clock time spent waiting on databases and downstream APIs. Connection reuse, parallel calls and caching reduce it. |
| Batching | Lambda | Request count | Processing several records per invocation spreads the per-request charge and startup overhead across more work. |
| Spot / interruptible capacity | Containers | Hourly rate | Spare capacity costs less, but it can be reclaimed at short notice. Use it for stateless replicas behind a load balancer. |
| Savings plans, commitments | Containers | Hourly rate | You get a lower rate in exchange for committing to a level of spend over a term. |
| Bin-packing on EC2 | Containers | Instance count | Packing many tasks onto fewer instances raises utilization. Fargate bills per task size, so unused headroom inside a task is still billed. |
| Scale down overnight | Containers | Hours | Scheduled or metric-based scale-in removes peak-sized capacity when traffic drops. |
Base commitments on measured baseline usage, not growth projections. If traffic comes in below forecast, you keep paying for the committed spend, and the unused portion can cancel out the discount. Commit to the floor you are confident about and cover the rest with on-demand or Spot capacity.
What are the alternatives to a straight Lambda-or-containers choice?
The choice is not binary. Several other options change the cost terms in the model without requiring a full platform switch.
- A different front door for Lambda. API Gateway's per-request charge is often a large share of the Lambda-side bill. Lambda function URLs give a function an HTTPS endpoint without API Gateway. An Application Load Balancer can also invoke Lambda functions as targets, which swaps a per-request charge for the load balancer's hourly and usage-based pricing. Both options drop API Gateway features such as request validation, usage plans and some authorization options, so check which of those you actually rely on.
- Plain EC2 instances without an orchestrator. Running the service directly on instances in an Auto Scaling group behind a load balancer gives you the container cost model with less platform overhead. You give up the scheduling and bin-packing that ECS or Kubernetes provide, and you take on more of the instance management.
- Fargate vs EC2-backed containers. Within the container option, Fargate removes instance management but bills per task size. EC2-backed ECS or Kubernetes requires capacity management but lets you pack tasks densely and use commitment discounts on instances. The break-even model applies to both. Only r_task and the utilization assumptions change.
- Optimizing the current platform first. Before migrating, apply the levers in the previous section. Right-sizing Lambda memory, trimming log volume, or scaling a container fleet down overnight can shift the crossover enough that a migration no longer pays off.
- A hybrid split by route. Run high-volume, steady routes on containers and spiky or rarely called routes on Lambda. A single load balancer or API layer can route paths to different backends. This often yields the lowest total cost because each route sits on the side of its own break-even point.
Each alternative still fits the same method: express its cost as a function of request volume and peak load, then compare it against the other curves.
How do engineering time and migration cost change the decision?
Compute is one line in the model. Engineering hours belong there too, because they can easily exceed the monthly difference between the two pricing models.
On the container side, recurring work includes patching base images, tuning scaling policies and planning capacity ahead of known peaks. On the Lambda side, it includes mitigating cold starts, managing concurrency, payload and timeout limits, and debugging requests that cross several functions and queues with no long-lived process to inspect.
Migration is a one-time cost. You change packaging, rebuild local development, rewire observability and rework deployment pipelines. A modest projected saving may take years to repay that effort.
Payback months = (migration hours × loaded hourly rate) ÷ (monthly compute saving − monthly increase in ops effort)
Illustrative estimate (assumed numbers, not a benchmark): 160 migration hours at $100/hour is $16,000. With a compute saving of $800/month and $200/month of added ops effort, the net saving is $600/month, and payback takes about 27 months. If traffic is likely to change within that window, the saving may never arrive.
A repeatable procedure keeps the decision cheap:
- Export one month of request counts and latency percentiles per route.
- Run both cost models on that data.
- Apply a growth margin to the projected volume.
- Re-run the models whenever traffic changes significantly, not on a fixed schedule.
The answer does not have to be one platform. Running steady, high-volume routes on containers and spiky or rarely called routes on Lambda is often the cheapest setup overall.
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 containers 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.