Course contents

14. Cloud and Infrastructure Lesson 8 of 8

Serverless Architecture

Watch functions scale per request, see cold starts and concurrency limits bite, and why a function fleet exhausts database connections without a pooler.

15 minIntermediate7 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • A function platform runs one instance per in-flight request: concurrency = request rate × duration.
  • Cold starts add start-up time to the first request on each new instance; deploys and bursts create many.
  • Concurrency limits throttle excess invocations; a slower dependency raises concurrency as much as more traffic does.
  • Each instance is a separate database client: compute scales faster than the database’s connection limit.
  • Poolers lend connections only while queries run; serverless removes server management, not capacity planning.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Serverless computing, in its function-as-a-service form, lets you deploy a function and have the platform run it in response to events: HTTP requests through an API gateway, messages on a queue, files landing in a bucket, schedules, database change streams. The platform creates execution environments (instances) on demand, routes each event to one, scales the number of instances with load (down to zero when idle), and bills per invocation and compute time. AWS Lambda, Google Cloud Run functions and Azure Functions are well-known examples; container platforms with per-request scaling share many of the same properties.

Why it exists

Running servers means choosing instance sizes, keeping enough capacity for peaks, patching operating systems and paying for idle machines. Many workloads are spiky or small: a webhook called a few hundred times a day, image processing when users upload, a nightly job. Functions remove the fleet: no capacity to plan for normal operation, no idle cost, and event integrations that make glue code short.

How it works

Per-request scaling. In the common model each instance handles one request at a time (some platforms allow several). The number of instances running at once is therefore the concurrency, and Little's law gives it: concurrency = arrival rate × duration. 400 requests per second at 60 ms need about 24 instances; if a dependency makes each invocation four times slower, the same traffic needs about 100.

Instance lifecycle. A new instance must download the code, start the runtime and run your initialisation code before handling its first request: the cold start. Afterwards the instance stays warm for a while and handles further requests without that cost; idle instances are eventually reclaimed. Cold starts range from tens of milliseconds for small packages on fast runtimes to seconds for large packages, heavy frameworks or functions attached to private networks with slow setup. Mitigations: smaller deployment packages, lazy initialisation, faster runtimes, snapshot-based start-up where offered, and paid pre-warmed capacity (provisioned concurrency, minimum instances).

Limits. Platforms cap concurrency per account and region, and let you reserve or cap concurrency per function. Invocations beyond the cap are throttled: synchronous callers get an error (typically HTTP 429), asynchronous event sources retry later. There are also limits on duration, memory, payload size and burst scaling rate.

State. Instances are disposable and do not share memory. Anything that must survive goes to a database, cache, queue or object store. Instances may be reused, so connections opened during initialisation are kept between invocations.

Downstream systems. Each instance is a separate client. With a relational database, connections follow instance count, and instances that are waiting still count. A burst that a function platform absorbs easily can exceed the database's connection limit. Connection poolers or managed database proxies hold a small set of real connections and lend them to callers per transaction; serverless-oriented databases and HTTP data APIs avoid persistent connections altogether.

When to use it

  • Event-driven processing: storage events, queue consumers, change streams, webhooks.
  • Spiky or low and unpredictable traffic, where idle servers would cost more than invocations.
  • Scheduled jobs and lightweight automation.
  • Prototypes and small APIs where operations effort matters more than per-request cost.

When not to

  • Steady, high request rates: always-on servers or containers are often cheaper and more predictable.
  • Latency-critical paths where cold starts in the tail are unacceptable and pre-warming is too expensive.
  • Long-running work beyond the platform's maximum duration (transcoding, large batch jobs), unless split into steps.
  • Workloads that need local state, large in-memory caches or long-lived connections such as WebSockets held by the compute itself.

Trade-offs

Choice You gain You pay
Functions instead of servers No capacity planning, scale to zero, managed patching Cold starts, platform limits, per-request pricing
Pre-warmed capacity No cold starts for that many instances Paying for idle capacity again
Per-function concurrency cap Protects downstream systems Throttled requests during spikes
Connection pooler / database proxy Connections follow query concurrency Another component and hop; transaction-level pooling limits some session features
Asynchronous invocation via a queue Smooths bursts, retries built in Eventual completion, idempotency required

Alternatives

  • Containers on a managed platform with autoscaling (including per-request scaling to zero on some platforms): more control over runtime and concurrency per instance.
  • Virtual machines or Kubernetes: best for steady load and specialised needs, at the cost of operating the fleet.
  • Queue + worker pool: bounded, predictable concurrency for background work.

Failure modes

  • Downstream exhaustion: database connections, third-party rate limits or a small service overwhelmed by a function that scaled out.
  • Throttling cascades: one function consuming the account's concurrency starves unrelated functions; reserve concurrency for critical ones.
  • Retry storms and duplicates: asynchronous triggers retry failed invocations; without idempotency the same event is processed twice.
  • Cold-start spikes after deploys or quiet periods.
  • Timeouts at the limit: work that usually fits in the maximum duration fails when a dependency slows.
  • Runaway cost: a loop of functions triggering each other or a flood of events bills per invocation.

In production

Measure duration, concurrency, throttles, errors and cold-start rate per function. Set concurrency caps that protect downstream systems and reserve capacity for critical functions. Keep handlers stateless and idempotent, initialise expensive clients outside the handler, and use a pooler, proxy or HTTP-based data access for relational databases. Put queues in front of bursty background work. Configure timeouts shorter than the caller's, and dead-letter destinations for failed asynchronous events. Watch cost per request as traffic grows.

Common misconceptions

  • "Serverless means infinite scale." Concurrency limits, burst rates and everything downstream still apply.
  • "There are no servers." There are; you do not manage them, and their start-up time shows up as cold starts.
  • "Serverless is always cheaper." For idle and spiky workloads, usually; for steady high load, often not.
  • "Throttling only happens when traffic grows." A slower dependency raises concurrency at constant traffic.

Interview angle

Use functions for event-driven and spiky parts of a design (upload processing, webhooks, scheduled jobs) and justify it with cost and operations. Show you know the limits: estimate concurrency with rate × duration, discuss cold starts and pre-warming, concurrency caps and throttling, idempotency for retried events, and how you keep a scaled-out function fleet from overwhelming a relational database (pooler, proxy, queue, or a different datastore).

Model assumptions

The simulation is a simplified model, not a benchmark. The function is modelled as a server whose worker count is its concurrency limit (1,000 unless a step lowers it) with no queue, so an invocation over the limit is rejected at once (standing in for HTTP 429); each worker is one instance handling one request at a time. A warm invocation takes 60 ms (lognormal, cv 0.3). Cold starts are approximated by making every invocation take 700 ms for the first two seconds of the step; in reality only each new instance's first request pays. A slow dependency is modelled by making invocations four times slower. The database accepts 40 concurrent connections; waiting more than 150 ms for one fails the request. Without a pooler each invocation holds a connection for 55 ms of its 60 ms run; with a pooler it borrows one only for 15 ms of queries. Instances that are reused but idle, which in reality also hold connections, are not modelled, so real connection counts are higher. Arrivals are random (Poisson). One-way latencies are fixed: users to the gateway 20 ms, 1 ms inside the cloud. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. No servers to size: one instance per request

    Here there is no server fleet to plan. The API gateway invokes a function for each request, and the platform runs as many copies (instances) as there are requests in progress. You pay per invocation and per unit of compute time; with no traffic, nothing runs and nothing is billed.

    One second in, traffic jumps twentyfold, from 20 to 400 requests per second. Nobody adds capacity, yet latency stays flat and nothing fails: about 25 instances now run at once. The number of instances you need is simply arrival rate × duration (Little’s law): 400 per second × 60 ms ≈ 24.

    Scene: An API gateway invokes a function for each request. Traffic jumps from 20 to 400 requests per second one second in; about 25 instances run at once, latency stays flat and nothing fails.

    Key idea: Serverless scales per request: concurrency = requests per second × duration, provided by the platform on demand.

  2. 2. Cold starts

    A new version has just been deployed, so no instance is warm. A new instance first has to start: fetch the code, boot the runtime, run your initialisation (load libraries, open connections). Only then does it handle the request. That cold start adds hundreds of milliseconds, sometimes seconds for large packages or heavy runtimes.

    For the first two seconds requests take about 700 ms instead of 60, then instances are warm and latency drops back. (Simplified: the model slows every request during those two seconds; really only each new instance’s first request pays, but after a deploy or during a burst that is a lot of them.) Mitigations: keep packages small and initialisation lazy, choose a fast-starting runtime, or pay for pre-warmed instances (provisioned concurrency, minimum instances).

    Scene: Right after a deploy every request takes about 700 ms while instances start. Two seconds in, instances are warm and latency drops back to about 100 ms end to end.

    Key idea: Cold starts put the instance start-up time on the request path; they show up in the tail, after deploys and during bursts.

  3. 3. Concurrency limits throttle

    “Scales automatically” has a ceiling. Platforms cap the number of instances running at once per account and region, and you can cap a single function. This function is limited to 50 concurrent instances; at 400 requests × 60 ms it needs about 24, so all is well.

    One second in, a downstream API slows down and each invocation takes four times longer. Same traffic, but now it needs about 100 instances at once. Everything above 50 is throttled (HTTP 429) immediately. Concurrency is driven by duration as much as by traffic: a slow dependency multiplies it.

    Scene: The function is capped at 50 concurrent instances. One second in, each invocation becomes four times slower; the needed concurrency doubles past the cap and the excess requests are throttled.

    Key idea: Concurrency limits bite when duration grows, not only when traffic grows. Throttled requests fail fast unless the caller retries.

  4. 4. Add a relational database

    The slowdown is gone and the limit is back at 1,000. The function now reads from a relational database that accepts at most 40 connections.

    Each instance opens its own connection and holds it for its whole run, about 55 ms of the 60. At 400 requests per second that is about 22 connections in use: fine.

    Scene: Each function instance holds a database connection while it runs. At 400 requests per second about 22 of the database’s 40 connections are in use and nothing fails.

    Key idea: Every running function instance is a separate database client. Connection count follows instance count.

  5. 5. The function scales, the database does not

    One second in, traffic rises to 1,000 requests per second. At 60 ms each that needs about 60 instances, and every one wants a connection. The database has 40.

    Instances queue for connections, and an instance that waits is still running, so the platform keeps adding instances: about 200 run at once, most of them just waiting. Some wait longer than 150 ms and fail. Nothing is throttled at the function: the platform did exactly what it promised. The bottleneck moved to the one component that cannot scale per request.

    Scene: Traffic rises to 1,000 requests per second. The function scales out, but the requests need about 55 database connections and the database has 40. Waiting instances pile up to about 200 and some requests fail with connection timeouts.

    Key idea: Serverless compute scales faster than the stateful systems behind it. Connection exhaustion is the classic first failure.

  6. 6. A connection pooler in between

    We put a connection pooler (a database proxy) between the functions and the database. Instances connect to the pooler, which keeps a small set of real database connections and lends one out only while a query runs, here about 15 ms of each invocation instead of 55.

    At the same 1,000 requests per second the database now needs about 15 connections. The errors stop. Managed database proxies and tools like PgBouncer do this; serverless-friendly databases that speak HTTP avoid long-lived connections altogether.

    Scene: A connection pooler sits between the function and the database and hands out connections only while queries run. At 1,000 requests per second the database uses about 15 connections and nothing fails.

    Key idea: Pool connections outside the functions, so connection count follows query concurrency, not instance count.

  7. 7. When serverless fits

    The function serves 1,000 requests per second through the pooler without errors.

    Serverless fits spiky or low, unpredictable traffic and event-driven work (files landing in a bucket, queue messages, schedules, webhooks): no idle servers, no capacity planning, scaling handled for you. It fits less well for steady high load (per-request pricing can cost more than always-on servers), latency-critical paths that cannot tolerate cold starts, long-running jobs (platforms cap duration) and anything that keeps state in memory between requests.

    Design for it: stateless handlers, idempotent processing (events can be delivered twice), concurrency limits that protect downstream systems, and pooled or HTTP-based access to databases.

    Scene: Users reach the function through the API gateway at 1,000 requests per second; the function reads the database through a connection pooler. Nothing fails.

    Key idea: Serverless removes server management, not capacity planning: the limits move to concurrency, cold starts and the stateful systems behind.