Sub topic 1
What serverless means and how Lambda is billed
Prerequisites
This chapter assumes you can read basic Python, and that you know what JSON and HTTP APIs are. It also assumes you have an AWS account and can use the console or the AWS CLI. You should know what an IAM role is, but you don't need to write policies yet. You don't need to deploy anything in this chapter. The only code is a small cost calculator that runs locally.
What "serverless" means
Serverless doesn't mean there are no servers. It means you don't provision, patch or scale them. AWS runs the machines, and you supply code and configuration. Three properties define the model:
- No server management. You don't pick instance types, install operating system updates or manage a fleet.
- Automatic scaling. The service adds or removes capacity based on incoming work, down to zero.
- Pay for use. You are billed for the work done, not for capacity that sits idle.
AWS Lambda is a function-as-a-service (FaaS) product. You upload a function, which is a piece of code with one entry point called a handler. Lambda runs the handler when an event arrives. An event can be an HTTP request, a message in a queue, a file landing in a bucket, or a schedule.
What changes compared with servers
| Concern | Long-running server (EC2, containers) | Lambda |
|---|---|---|
| Capacity planning | You choose instance count and size | Lambda scales per request, within account limits |
| Idle cost | You pay while it is running | No charge when there are no invocations |
| Process lifetime | Runs until you stop it | Short-lived, up to 15 minutes per invocation |
| State in memory | Persists between requests | May or may not persist, so never rely on it |
| Unit of work | Many requests per process | One event per invocation (per execution environment) |
The last two rows have design consequences. Lambda can freeze or discard the process between invocations, so durable state belongs in a database, a queue or object storage. You can still cache things such as database connections in memory, because they often survive between calls. A later chapter on the execution environment covers this reuse.
Where Lambda fits
Lambda suits spiky or unpredictable traffic, event-driven glue between AWS services, and background jobs. It fits less well for steady, high-volume, CPU-bound work that runs all day. At constant high utilization, a reserved instance or container can cost less per unit of compute. Latency-critical paths also need attention to cold starts, which a later chapter covers.
How a Lambda invocation is billed
Lambda billing has two main parts that apply to every function: requests and duration. Other features add their own charges.
Requests
You pay a flat rate per invocation, listed per million requests. Every call counts, including calls that fail and calls that are retried. At the time of writing, the list price in most regions is $0.20 per million requests.
Duration and GB-seconds
Duration is the time your handler code runs, rounded up to the nearest millisecond. Duration is priced in GB-seconds, which is memory allocated multiplied by time. The formula is:
GB-seconds = (memory in MB / 1024) x (duration in seconds)Two details matter here:
- You are charged for the memory you configure, not the memory your code uses. A function configured with 1024 MB that uses 100 MB is billed as 1 GB.
- Billing granularity is 1 ms. Older material mentions 100 ms rounding, which was removed in 2020.
At the time of writing, x86 functions in most regions cost about $0.0000166667 per GB-second. Functions on the arm64 (Graviton) architecture cost about $0.0000133334 per GB-second, around 20% less. Prices differ by region, so check the official Lambda pricing page before you estimate a real budget.
Memory also sets CPU
You don't configure CPU directly. Lambda allocates CPU power in proportion to memory. The memory range is 128 MB to 10,240 MB. At 1,769 MB a function gets the equivalent of one vCPU, and more memory grants more.
This produces a counterintuitive result. A higher memory setting can make a CPU-bound function so much faster that its total cost stays the same or drops. For example, compare these hypothetical measurements of one function:
| Memory | Duration | GB-seconds per call |
|---|---|---|
| 128 MB | 1000 ms | 0.125 |
| 512 MB | 250 ms | 0.125 |
| 1024 MB | 130 ms | 0.130 |
The first two options cost the same, but the 512 MB setting returns four times faster. Functions that spend most of their time waiting on the network benefit less, because extra CPU doesn't shorten the wait. Measure your own function instead of assuming a ratio.
Free tier
The Lambda free tier gives each account 1 million requests and 400,000 GB-seconds per month. Unlike many 12-month AWS trials, this allowance has no expiry. Check the current terms on the pricing page, because AWS has changed its free plan structure over time.
Charges beyond requests and duration
Several features add cost. Treat them as separate line items.
- Provisioned concurrency. You pay for the capacity you keep initialized, whether or not it is used. Invocations that run on it are billed at a lower duration rate. A later chapter covers it.
- Ephemeral storage. The
/tmpdirectory includes 512 MB at no charge. Configuring more, up to 10,240 MB, is billed per GB-second. - Initialization time. For some configurations, such as container images and provisioned concurrency, the initialization phase has long been billed. AWS also announced that, from August 2025, the init phase of managed-runtime zip functions counts toward billed duration. If a function does heavy work at import time, your measured duration understates the true cost. Verify this against the current pricing documentation.
- Data transfer and other services. Lambda doesn't charge for the services it calls, but each call to DynamoDB, S3 or an API has its own price. Data leaving AWS is billed at normal transfer rates.
- Logging. Each invocation writes logs to CloudWatch Logs, which charges for ingestion and storage. Verbose logging in a high-volume function can cost more than the compute.
A worked cost estimate
Suppose a function receives 5 million invocations per month, is configured with 512 MB, and averages 200 ms per invocation on x86. Assume only the free tier applies.
- Total GB-seconds: 5,000,000 x 0.5 GB x 0.2 s = 500,000.
- Billable GB-seconds after the free tier: 500,000 - 400,000 = 100,000.
- Duration cost: 100,000 x $0.0000166667 = about $1.67.
- Billable requests: 5,000,000 - 1,000,000 = 4,000,000, which is 4 x $0.20 = $0.80.
- Total: about $2.47 per month.
The script below does the same arithmetic, so you can change the numbers and compare memory settings.
FREE_REQUESTS = 1_000_000
FREE_GB_SECONDS = 400_000
PRICE_PER_MILLION_REQUESTS = 0.20
PRICE_PER_GB_SECOND_X86 = 0.0000166667
PRICE_PER_GB_SECOND_ARM = 0.0000133334
def monthly_cost(requests, memory_mb, avg_ms, arm=False, use_free_tier=True):
gb_seconds = requests * (memory_mb / 1024) * (avg_ms / 1000)
price = PRICE_PER_GB_SECOND_ARM if arm else PRICE_PER_GB_SECOND_X86
billable_requests = requests
billable_gb_seconds = gb_seconds
if use_free_tier:
billable_requests = max(0, requests - FREE_REQUESTS)
billable_gb_seconds = max(0.0, gb_seconds - FREE_GB_SECONDS)
request_cost = billable_requests / 1_000_000 * PRICE_PER_MILLION_REQUESTS
duration_cost = billable_gb_seconds * price
return gb_seconds, request_cost, duration_cost
if __name__ == "__main__":
for arm in (False, True):
gb_s, req, dur = monthly_cost(5_000_000, 512, 200, arm=arm)
label = "arm64" if arm else "x86"
print(f"{label}: {gb_s:,.0f} GB-s, requests ${req:.2f}, "
f"duration ${dur:.2f}, total ${req + dur:.2f}")Running it prints about $2.47 for x86 and about $2.13 for arm64. Without the free tier (use_free_tier=False), the same workload costs about $9.33 on x86.
Common mistakes when estimating cost
- Counting only successful calls. Failed invocations and retries are billed. A function that retries three times on a bad message costs four invocations.
- Forgetting that timeouts are billed in full. A function that hangs until its timeout is billed for the entire timeout. A 15-minute timeout on a stuck function is expensive at scale.
- Setting minimum memory to save money. The lowest memory setting is often slower and not cheaper. Test two or three memory settings with realistic input.
- Ignoring waiting time. Lambda bills wall-clock time, including time spent waiting for a database or an API. A slow downstream service increases your Lambda bill.
- Ignoring logs and downstream calls. CloudWatch Logs and service calls often exceed the compute charge for small functions.
Summary of the model
Lambda charges per request and per GB-second of configured memory multiplied by time. It lets you scale to zero and removes server management, and in exchange you accept short-lived, stateless execution. The next chapter shows what a handler looks like and what the event and context objects contain.
Exercise
A function is configured with 2048 MB and runs for 300 ms on average. It handles 2,000,000 invocations in a month, on x86 at $0.0000166667 per GB-second and $0.20 per million requests. Ignoring the free tier, what is the monthly cost, and what would change if the same code were run at 1024 MB and took 450 ms?
Show answer
At 2048 MB, GB-seconds = 2,000,000 x 2 x 0.3 = 1,200,000. Duration cost = 1,200,000 x $0.0000166667 = about $20.00. Request cost = 2 x $0.20 = $0.40. Total is about $20.40. At 1024 MB and 450 ms, GB-seconds = 2,000,000 x 1 x 0.45 = 900,000, so duration cost is about $15.00 and the total is about $15.40. The smaller setting is cheaper here because the speedup from extra memory (1.5x) is smaller than the memory increase (2x), but it is also slower per request. Which setting is better depends on whether you value cost or latency.
Exercise
List three charges that appear on an AWS bill for a Lambda-based application that are not part of the request count or the duration charge for the function itself.
Show answer
Any three of the following: provisioned concurrency, ephemeral storage above 512 MB, CloudWatch Logs ingestion and storage, calls to other services such as DynamoDB or S3, data transfer out of AWS, and (depending on current terms) initialization time billed outside the handler.