Cloud Computing Tutorial · Compute · Lesson 13 of 24
Serverless Functions
How Lambda, Azure Functions and Cloud Run functions work: events, scaling, cold starts, limits and pricing.
Functions triggered by events
A function is code that runs in response to an event: an HTTP request (through API Gateway or a function URL), a file uploaded to storage, a message on a queue, a schedule. The platform starts as many copies as needed, in parallel, and you pay per request and per GB-second of execution.
def handler(event, context): # AWS Lambda, Python
order = event["detail"]
save(order)
return {"status": "ok"}
Things to know
- Cold starts: the first request on a new instance loads the runtime and your code; keep packages small and initialise clients outside the handler so warm invocations reuse them.
- Limits: Lambda runs at most 15 minutes per invocation, with up to 10 GB of memory; long jobs belong in containers or step-by-step workflows (Step Functions, Durable Functions, Workflows).
- Concurrency: each concurrent request uses one execution environment; accounts have concurrency quotas, and downstream systems (databases) may not cope with thousands of parallel connections.
- Statelessness: keep state in databases, caches or storage, not in the function.
PRICE_PER_GB_SECOND = 0.0000166667 # example Lambda price (x86), USD
PRICE_PER_MILLION_REQUESTS = 0.20
def monthly_cost(requests, avg_ms, memory_mb):
gb_seconds = requests * (avg_ms / 1000) * (memory_mb / 1024)
return gb_seconds * PRICE_PER_GB_SECOND + requests / 1_000_000 * PRICE_PER_MILLION_REQUESTS
for requests in [1_000_000, 50_000_000, 500_000_000]:
print(f"{requests:>11,} requests/month at 120 ms, 512 MB: ${monthly_cost(requests, 120, 512):9,.2f}")
Output
1,000,000 requests/month at 120 ms, 512 MB: $ 1.20 50,000,000 requests/month at 120 ms, 512 MB: $ 60.00 500,000,000 requests/month at 120 ms, 512 MB: $ 600.00
For deep dives, see the Python, Node.js and Java serverless courses.
Test yourself
Where should a Lambda function create its database client to reuse it across invocations?
Inside the handler on every callOutside the handler, during initialisationIn a separate Lambda layer onlyIt can't reuse connections
Show answer
Answer: Outside the handler, during initialisation
Code outside the handler runs once per execution environment and is reused by warm invocations.