Skip to content
BytePatterns

ALB vs API Gateway: Load Balancer or API Front Door

7 min readBytePatterns

ALB vs API Gateway: an hourly Layer 7 load balancer that routes by host and path, or a per-request API front door with auth, throttling and usage plans.

ALB vs API Gateway in one line: both can put an HTTPS endpoint in front of Lambda functions and HTTP backends, but an Application Load Balancer is a Layer 7 load balancer billed per hour plus capacity units, which routes each request by host, path and headers and offers few API features, while Amazon API Gateway is a managed API front door billed per request, which adds authorizers, throttling, usage plans with API keys, request validation, response caching and WebSocket APIs. At low volume API Gateway is usually cheaper; at high, steady volume the ALB's flat hours win, unless you need what only the gateway does. Facts are from the AWS documentation listed at the end, as of October 2026.

Application Load BalancerAPI Gateway
Billing shapeper hour, plus LCUs for trafficper request; nothing when idle
Beyond routingOIDC or Cognito login, JWT validation, redirects, fixed responsesauthorizers, throttling, usage plans, validation, caching, WebSocket
Lambda limits1 MB request and response; no WebSocket to Lambda10 MB payload; 29 s REST integration timeout by default

The problem it solves

A team has a Lambda-backed API and every tutorial puts API Gateway in front of it. Six months later the API serves hundreds of millions of steady requests from its own web app, uses none of the gateway's features, and the gateway is the largest line on the bill. Another team puts an ALB in front of a partner API, one partner floods it, and there is no per-client throttle to stop them. Same mistake twice: choosing the front door before asking what it must do and how much traffic it will see.

The intuition

An ALB routes; that is most of what it does. An HTTPS listener terminates TLS and evaluates rules in priority order, matching host, path, headers, method, query string or source IP. Each rule ends in one routing action: forward to target groups, with weights for canaries, redirect, or a fixed response. On HTTPS listeners a rule can first authenticate users through Amazon Cognito or any OpenID Connect provider, and a jwt-validation action checks access tokens. A target group can hold instances, IP addresses or one Lambda function, which the load balancer invokes directly with the request as a JSON event. For Lambda targets the request body and the response are each capped at 1 MB, and WebSocket upgrades are rejected. What it lacks is the API as a product: per-client quotas, API keys, schema validation, caching.

API Gateway manages the API. It comes as REST APIs, HTTP APIs and WebSocket APIs. Requests can be authorised by IAM, Lambda authorizers, Cognito or JWT. Throttling applies at several levels, starting from an account quota per Region of 10,000 requests per second with a token-bucket burst of 5,000 by default, shared by every API in the account. REST APIs add usage plans with API keys, request validation, response caching and AWS WAF. Payloads go up to 10 MB, and the integration timeout is 29 seconds by default for REST APIs, which can be raised for Regional and private APIs at the cost of throttle quota, and at most 30 seconds for HTTP APIs. The REST-or-HTTP choice inside the gateway is its own article: API Gateway REST API vs HTTP API.

The bills have opposite shapes. An ALB charges for every hour it exists, partial hours counted as whole, plus load balancer capacity units on whichever of four dimensions is highest: new connections, active connections, processed bytes and rule evaluations. API Gateway charges per request in tiers per million, plus data transfer, and nothing when idle; the REST cache is billed by the hour. One is a fixed cost with a slow slope, the other a pure slope, so they cross.

When to use which

  • Low or bursty traffic, a new product, many small APIs: API Gateway; idle costs nothing.
  • Public or partner APIs needing keys, quotas, validation or caching: API Gateway, a REST API.
  • WebSocket APIs on Lambda: API Gateway. An ALB passes WebSockets to instances, not to functions.
  • High, steady request volume from your own clients, routing only: an ALB, especially if it already fronts containers or instances.
  • Mixed backends behind one hostname, Lambda next to ECS services: an ALB with path rules, one target group per backend.
  • Both: an HTTP API with a VPC link to a private ALB, when partners need gateway features and services need load balancing.

Watch it run

The animation, from the Lambda and event-driven lesson, shows the back half that both front doors share. Messages land in an SQS queue, a poller hands batches to execution environments that pay cold starts, reserved concurrency caps the function at three while the rest waits, and a bad message ends in a dead-letter queue. Replace the queue and poller with an ALB target group or an API Gateway integration and the environments behave the same: each concurrent request needs one. What disappears is the queue, so a burst beyond the function's concurrency becomes errors at the front door rather than messages waiting, and that is where the gateway's throttling earns its price.

Lambda & Event-Driven Design

Step 1 of 11

Upload events land in a queue. Lambda runs a poller that reads the queue for you and invokes your function with batches.

The same interactive animation as the lesson — step through it with the controls.

The code

A cost-shape model, not a price list. Costs are in units where 1 unit is one ALB-hour; the per-million ratios are assumptions chosen to resemble the published shape, so put your own Region's prices in before trusting a number:

# a MODEL of cost shape in "units" (1 unit = one ALB-hour), not a price list
HOURS = 730                     # one month, always on
ALB_PER_MILLION = 2             # LCU usage grows with traffic, slowly (assumed)
PER_MILLION = {"REST API": 150, "HTTP API": 45}   # rough ratios to one ALB-hour (assumed)

def alb(millions):
    return HOURS + millions * ALB_PER_MILLION   # fixed hours + usage

def apigw(millions, kind):
    return millions * PER_MILLION[kind]          # usage only: zero when idle

for m in (0.1, 1, 5, 20, 100):
    row = f"{m:5} M req/month  ALB {alb(m):6.0f}"
    for kind in PER_MILLION:
        row += f"  {kind} {apigw(m, kind):6.0f}"
    print(row)
for kind, price in PER_MILLION.items():
    print(f"{kind}: ALB is cheaper above {HOURS / (price - ALB_PER_MILLION):.1f} M requests/month")
#   0.1 M req/month  ALB    730  REST API     15  HTTP API      4
#     1 M req/month  ALB    732  REST API    150  HTTP API     45
#     5 M req/month  ALB    740  REST API    750  HTTP API    225
#    20 M req/month  ALB    770  REST API   3000  HTTP API    900
#   100 M req/month  ALB    930  REST API  15000  HTTP API   4500
# REST API: ALB is cheaper above 4.9 M requests/month
# HTTP API: ALB is cheaper above 17.0 M requests/month

The model ignores API Gateway's lower rates at high tiers, free tier allowances and data transfer, and those move the crossover. They do not change its existence: a flat line and a steep line always meet. Routing differs too. An ALB walks its rules by priority and takes the first match; an HTTP API picks the most specific route, whatever order it was added in. A toy of each, then the crossover formula checked against a brute-force comparison:

import fnmatch, random

def alb_route(rules, path):
    """ALB: rules in priority order, the first matching path pattern wins."""
    for priority, pattern, target in sorted(rules):
        if fnmatch.fnmatchcase(path, pattern):
            return target
    return "default action"

def apigw_route(routes, path):
    """Toy HTTP API: the most specific route wins, whatever order it was added in."""
    parts, best = path.strip("/").split("/"), (-1, "$default")
    for route, target in routes:
        segs = route.strip("/").split("/")
        if len(segs) == len(parts) and all(s.startswith("{") or s == p for s, p in zip(segs, parts)):
            best = max(best, (sum(not s.startswith("{") for s in segs), target))
    return best[1]

rules = [(10, "/orders/*", "orders-tg"), (20, "/orders/export", "export-tg")]
routes = [("/orders/{id}", "orders-fn"), ("/orders/export", "export-fn")]
for path in ("/orders/42", "/orders/export", "/health"):
    print(f"{path:15} ALB -> {alb_route(rules, path):14} API GW -> {apigw_route(routes, path)}")

random.seed(2)
ok = True
for _ in range(1000):
    hours, lcu, per_m = random.randint(1, 744), random.uniform(0, 5), random.uniform(6, 300)
    cross = hours / (per_m - lcu)
    for m in (random.uniform(0, 200) for _ in range(20)):
        ok &= (m * per_m > hours + m * lcu) == (m > cross)    # brute force vs formula
print(ok)
# /orders/42      ALB -> orders-tg      API GW -> orders-fn
# /orders/export  ALB -> orders-tg      API GW -> export-fn
# /health         ALB -> default action API GW -> $default
# True

On the ALB, /orders/export never reaches its target group: the broader rule has the lower priority number and matches first. Give specific rules the smaller numbers.

The complexity

  • ALB: a fixed monthly floor from the hourly charge, then LCUs on the busiest dimension; for Lambda targets one LCU covers less processed data per hour than for instances, and the first ten rule evaluations per request are free.
  • API Gateway: linear in requests with tiered discounts, no floor, plus the REST cache by the hour and, for WebSocket APIs, messages and connection minutes.
  • Throughput: the gateway's account quota is shared by every API in the Region and can be raised; an ALB scales with traffic and has no per-client limit at all.

Where it goes wrong

  • An ALB for a quiet internal API. It costs the same every hour whether it serves ten requests or none. API Gateway or a Lambda function URL costs nothing idle.
  • API Gateway for a high-volume API that uses no gateway features. Every request pays the per-request fee. Compare against an ALB at your real volume.
  • Uploading files through either. The ALB's Lambda limit is 1 MB and the gateway's payload limit is 10 MB. Hand out presigned S3 URLs instead.
  • Rule order on the ALB. A wildcard rule with a lower priority number shadows the specific one, as in the code.
  • Expecting the ALB to rate-limit clients. It has no usage plans; attach an AWS WAF rate-based rule, or use the gateway.
  • Long synchronous work behind API Gateway. The integration timeout ends the request at 29 or 30 seconds while the function keeps running. Return early and finish asynchronously.

When it shows up in interviews

As "how do clients reach your Lambda functions?" in a serverless design, then "what would that cost at a billion requests a month?". The strong answer names both options, picks by features first and volume second, and knows the limits: 1 MB for ALB to Lambda, 10 MB and about 30 seconds for the gateway. For when the backend should be Lambda at all, see Lambda vs Fargate vs EC2.

How to say it in an interview

"Both can front Lambda. An ALB is a Layer 7 load balancer: listener rules route by host and path to target groups, including Lambda, it can authenticate users with OIDC, and it bills per hour plus LCUs, so it is cheap per request at high steady volume. API Gateway is an API product: authorizers, per-client throttling, usage plans and API keys, request validation, caching and WebSockets, billed per request with nothing when idle. I start with API Gateway for new or bursty APIs and anything public, and move high-volume internal traffic that only needs routing to an ALB."

Frequently asked questions

What is the difference between ALB and API Gateway?

An ALB is a load balancer that routes HTTP requests by host, path and headers to targets including Lambda, billed per hour plus capacity units. API Gateway is a managed API service with authorizers, throttling, usage plans, validation and caching, billed per request. ALB suits high steady volume; API Gateway suits API features and low or spiky traffic.

Can an Application Load Balancer invoke a Lambda function?

Yes. Register the function in a target group of type lambda, one function per group, and a listener rule forwards matching requests to it. The load balancer passes the request as a JSON event and expects a response with a status code and headers. Bodies are limited to 1 MB each way, and WebSockets are not supported.

Is ALB cheaper than API Gateway?

At high, steady volume, usually yes: the ALB's cost is mostly a fixed hourly charge, while API Gateway charges for every request. At low or bursty volume API Gateway is cheaper, because it costs nothing when idle. Where they cross depends on REST versus HTTP API and your Region's prices.

Sources