Skip to content

Serverless and Functions-as-a-Service

Intermediate 45 min read Part 10 of 18

How functions-as-a-service run: triggers, cold starts, Firecracker micro-VMs, scaling, limits, the cost model, serverless databases, and when serverless fits.

Summary#

Serverless means building on cloud services that you never provision, patch or scale yourself, and that you pay for per use rather than per hour of reserved capacity. Its best-known form is Functions-as-a-Service (FaaS), such as AWS Lambda, Google Cloud Run functions, Azure Functions and Cloudflare Workers. You upload a function; the platform runs it in an isolated sandbox whenever an event arrives, such as an HTTP request, a file upload or a queue message. It scales from zero to thousands of instances automatically, and it bills by the millisecond. The price is cold starts, hard limits on duration, memory and state, a cost curve that loses to servers at high steady load, and tight coupling to a provider's ecosystem. Serverless databases, queues and storage extend the same model to data.

Why It Exists#

Running even a simple backend on servers involves a surprising amount of work that has nothing to do with the product. You choose instance sizes, build machine images, patch operating systems, configure auto-scaling groups and load balancers, set up health checks, size capacity for the peak, and pay for that capacity all night when nobody uses it. A team that wants a thumbnail generated whenever a user uploads a photo ends up running a fleet of image-processing servers that sit 95% idle.

Consider three typical workloads:

  • A webhook receiver that handles a few thousand calls a day, unpredictably bunched. A pair of small always-on servers for redundancy costs money every hour and needs patching, for perhaps a few minutes of real work a day.
  • A nightly report that runs for ten minutes. A server that exists only for those ten minutes must still be built, scheduled, monitored and torn down.
  • A product launch whose traffic might be 100 requests per second or 20,000, nobody knows. Provision for 20,000 and waste money; provision for 100 and fall over.

Serverless platforms take over everything below the application code: servers, operating systems, runtimes, scaling, load balancing, high availability across zones, and much of the security patching. They charge only while code runs. For the three workloads above, that means near-zero cost at idle, no infrastructure to maintain, and automatic scaling for the launch.

The idea grew out of earlier platform-as-a-service offerings such as Google App Engine (2008) and Heroku. It became mainstream when Amazon launched AWS Lambda in November 2014, initially as a way to run code in response to S3 uploads and DynamoDB changes. Google, Microsoft, IBM and Cloudflare followed with their own platforms, and the model spread to databases, queues, analytics engines and containers.

How It Works#

"Serverless" covers a family of services that share three properties: no server management, automatic scaling, including to zero, and pay-per-use pricing. The family includes:

  • Functions-as-a-Service: AWS Lambda, Google Cloud Run functions, formerly Cloud Functions, Azure Functions, Cloudflare Workers, Vercel and Netlify functions, and open-source platforms such as Knative, OpenFaaS and Apache OpenWhisk.
  • Serverless containers: AWS Fargate, Google Cloud Run and Azure Container Apps run whole container images with request-based or event-based scaling, closer to traditional services but without managing nodes.
  • Backend-as-a-Service and serverless data: object storage such as S3, databases such as DynamoDB, Firestore and Aurora Serverless, queues and event buses such as SQS, SNS and EventBridge, authentication such as Cognito and Firebase Auth, and analytics such as BigQuery and Athena.

A typical serverless application combines all three: an API gateway invokes functions, which read and write a serverless database, drop files in object storage, and publish events that trigger more functions.

How FaaS works#

From the developer's point of view, a function is a handler: code that receives an event and a context object, does some work, and returns a result. You package it with its dependencies, as a zip file or a container image, choose a runtime, such as Node.js, Python, Java, Go or .NET, set a memory size and a timeout, and attach one or more triggers.

From the platform's point of view, each invocation goes through these steps:

  1. An event arrives at the platform's front end: an HTTP request through an API gateway or a function URL, a notification from storage, a message pulled from a queue, a record from a stream, or a timer.
  2. The front end authenticates and routes the invocation, checks the function's concurrency limits, and asks a placement service for an execution environment.
  3. If a warm environment is idle, an instance that recently finished another invocation of the same function version, the invocation is sent straight to it. This is a warm start, adding only a few milliseconds.
  4. If none is free, the platform creates a new one: it picks a worker host with spare capacity, starts an isolated sandbox, downloads and unpacks the code, starts the language runtime, and runs the function's initialisation code, everything outside the handler, such as importing libraries and opening database connections. This is a cold start.
  5. The handler runs with the event. In AWS Lambda, an environment handles one invocation at a time; concurrency comes from running many environments.
  6. The result returns to the caller, or for asynchronous invocations, to a configured destination.
  7. The environment is kept warm for a while, typically minutes, in case more events arrive, and then reclaimed. The platform does not promise how long.

How FaaS works, in depth#

Three ways a function is invoked. The trigger determines retries, ordering and error handling, which matters as much as the code:

  • Synchronous invocation: the caller waits for the response. API Gateway, Application Load Balancers and function URLs invoke functions this way. Errors go straight back to the caller, which decides whether to retry. The request and response payload is limited, 6 MB each on Lambda.
  • Asynchronous invocation: the caller hands the event to the platform and gets an immediate acknowledgement. S3 notifications, SNS and EventBridge use this mode. Lambda places the event on an internal queue, invokes the function, and on failure retries, by default twice with delays, before sending the event to an on-failure destination or a dead-letter queue. Because events can be delivered more than once, handlers must be idempotent. See Idempotency.
  • Poll-based invocation, through an event source mapping: the platform runs pollers that read from a queue, such as SQS, or a stream, such as Kinesis, DynamoDB Streams or Kafka, gather records into batches, and invoke the function with each batch. For streams, ordering is preserved per shard or partition, and a failing batch blocks its shard until it succeeds, expires or is split, using options such as bisecting the batch on error and reporting partial batch failures. For SQS, failed messages become visible again after the visibility timeout and move to a dead-letter queue after a configured number of receives.

Execution environment reuse. Because a warm environment serves many invocations in sequence, anything created during initialisation, such as SDK clients, database connection pools, parsed configuration and machine-learning models loaded into memory, is reused. This is the most important performance technique in FaaS: do expensive work once, outside the handler. It also means global variables persist between invocations of the same environment, which is useful for caches but dangerous if code assumes a fresh process each time, for example by leaking per-request data into globals.

The function lifecycle in phases. Lambda documents three phases for an environment: Init, which includes starting extensions, the runtime and the function's initialisation code, and is limited to 10 seconds for on-demand functions; Invoke, which runs the handler for each event; and Shutdown, which gives extensions a brief chance to flush data. Monitoring and security agents can run as extensions, separate processes inside the environment, a form of the sidecar pattern. See Microservices Infrastructure Patterns.

State lives elsewhere. The environment's local disk, /tmp, is ephemeral, 512 MB by default on Lambda and configurable up to 10 GB, and private to one environment. Anything that must survive, such as user sessions, job progress or uploaded files, goes to a database, a cache or object storage. This statelessness is what lets the platform start, stop and multiply environments freely.

Isolation between tenants. Functions from thousands of customers share the same physical hosts, so the sandbox must give strong isolation, like a virtual machine, while starting in milliseconds and using little memory, like a container. These goals conflict, and the platforms resolve them differently, as described in the next section.

Cold starts and micro-VMs#

A cold start is the extra latency of the first invocation on a new execution environment. It is the price of scaling to zero: if no environment exists, one has to be created. Its parts are:

  • Sandbox creation: starting an isolated environment on a worker host, from a few milliseconds to a few hundred, depending on the isolation technology.
  • Code download: fetching the package or image, faster when it is small or already cached on the host.
  • Runtime start-up: starting the Node.js, Python, Java or .NET runtime. Interpreted and lightweight runtimes start in tens of milliseconds; the Java Virtual Machine with a large framework can take seconds.
  • Initialisation code: imports, dependency injection, SDK clients, connections, secrets fetched from a vault. This is often the biggest part, and the part the developer controls.

Typical end-to-end cold starts on mainstream platforms are roughly 100 ms to 1 second for small Node.js, Python or Go functions, and one to several seconds for JVM or .NET functions with heavy frameworks, unless snapshotting is used. Warm invocations add only a few milliseconds of platform overhead.

Isolation technologies. Platforms run untrusted code from many customers on shared hosts, and use one of three main approaches:

  • Micro-VMs. AWS built Firecracker, open-sourced in 2018 and described in "Firecracker: Lightweight Virtualization for Serverless Applications" (Alexandru Agache and colleagues, NSDI 2020). It is a virtual machine monitor written in Rust on top of Linux KVM, with a deliberately minimal device model: a few virtio devices for network and block storage, a serial console and little else. No BIOS, no PCI bus, no USB. The paper reports boot times on the order of 125 ms to the guest's user space, memory overhead under 5 MB per micro-VM, and the ability to create many micro-VMs per second on one host. Each Lambda execution environment runs inside a Firecracker micro-VM, so tenants are separated by hardware virtualisation, the same boundary as ordinary cloud VMs. AWS Fargate also uses Firecracker.
  • User-space kernels. Google's gVisor intercepts a container's system calls and implements them in a user-space kernel written in Go, so the application never talks to the host kernel directly. Google has used it for App Engine, Cloud Functions and Cloud Run's first-generation environment, trading some system-call performance for isolation without full VMs.
  • Language isolates. Cloudflare Workers run many customers' code inside a single process, each in its own V8 isolate, the same sandbox Chrome uses to separate browser tabs. An isolate starts in about 5 ms and needs only a few megabytes, so cold starts are nearly invisible and thousands of isolates fit on one machine. The cost is that only JavaScript, TypeScript and WebAssembly run, with a restricted API rather than a full operating system, and the security boundary is the JavaScript engine rather than a hypervisor, which Cloudflare reinforces with additional process-level defences.
IsolationExampleStart-upMemory overheadBoundaryRuns
Micro-VMFirecracker for Lambda and FargateAround 100 ms or moreA few MB plus the guestHardware virtualisationAny Linux code
User-space kernelgVisorTens to hundreds of msModerateSyscall interceptionMost Linux containers
Language isolateV8 isolates for Cloudflare WorkersAbout 5 msA few MBThe language runtimeJavaScript and WebAssembly
Plain containerKnative or OpenFaaS on KubernetesHundreds of ms to secondsModerateLinux namespaces and cgroupsAny container

Cold starts, in depth#

How often cold starts happen. Cold starts are frequent only in some situations: when traffic is very low, so environments are reclaimed between calls; when traffic rises quickly, so many new environments are needed at once; and right after a deployment, since a new version needs new environments. For a steadily busy function, the vast majority of invocations are warm. A study of Azure Functions, "Serverless in the Wild: Characterizing and Optimizing the Serverless Workload at a Large Cloud Provider" (Mohammad Shahrad and colleagues, USENIX ATC 2020), found that invocation rates are extremely skewed: most functions are called rarely, at most once an hour or so, while a small fraction receives the vast majority of invocations. For the rarely called functions, a fixed keep-alive window wastes memory or causes cold starts, so the authors proposed an adaptive policy that learns each function's idle-time distribution and pre-warms environments just before the next call is expected. Azure adopted a version of it.

Mitigations. In rough order of preference:

  1. Make initialisation cheap: smaller packages, fewer dependencies, lazy loading of rarely used modules, lighter frameworks, and avoiding network calls during init where possible. This often halves cold starts at no cost.
  2. Choose a fast-starting runtime for latency-critical paths: Node.js, Python, Go or Rust start much faster than a JVM with a heavy framework. For Java, frameworks designed for fast start-up, such as Quarkus or Micronaut, or ahead-of-time compilation with GraalVM native images, help a lot.
  3. Snapshot the initialised environment. Lambda SnapStart, launched for Java in 2022 and extended to Python and .NET in 2024, runs initialisation once when a version is published, takes a Firecracker snapshot of the micro-VM's memory and disk, and restores new environments from that snapshot, cutting cold starts for Java from seconds to a few hundred milliseconds. Code must handle the fact that every restored environment starts from the same memory, so unique values such as random seeds and connections must be refreshed after restore.
  4. Pay for warm capacity. Provisioned concurrency on Lambda, introduced in 2019, and minimum instances on Cloud Run and Azure keep a set number of environments initialised at all times, so invocations up to that level never cold start. It reintroduces an hourly cost and needs capacity planning, often scheduled for known peaks.
  5. Keep-warm pings, periodic dummy invocations, are a hack: they keep only one environment warm per concurrent ping, and do nothing for bursts. Provisioned concurrency is the supported tool.

Cold starts and the VPC. Functions that need to reach private resources, such as a database in a private network, used to suffer cold starts of ten seconds or more on Lambda while an elastic network interface was attached to each environment. In 2019 AWS changed the design so that functions share pre-created network interfaces through its Hyperplane network virtualisation layer, and this extra delay largely disappeared. Older advice to "avoid VPCs for latency" is outdated.

Large container images. Lambda accepts container images up to 10 GB. Downloading 10 GB on every cold start would be impossible, so Lambda splits images into chunks, deduplicates them across customers, using convergent encryption so identical chunks of public base layers can be shared without revealing content, caches them in a tiered cache, and loads chunks lazily as the function reads them. This is described in "On-demand Container Loading in AWS Lambda" (Marc Brooker and colleagues, USENIX ATC 2023). The lesson for users is that common base images are cheaper to cold-start than unusual ones, and that code touched during initialisation matters more than total image size.

The scaling model#

Serverless scaling is measured in concurrency: the number of invocations in flight at the same moment. In Lambda's model, one environment handles one invocation at a time, so concurrency equals the number of environments needed. By Little's law:

concurrency = request rate × average duration

At 1,000 requests per second with an average duration of 200 ms, the function needs about 200 concurrent environments. If a downstream slowdown raises the duration to 2 seconds, the same traffic suddenly needs 2,000, a tenfold increase with no change in traffic. This is the single most important fact about serverless scaling: latency increases consume concurrency.

Platforms scale out by creating new environments as concurrency rises, within limits:

  • An account or regional concurrency limit. On Lambda the default is 1,000 concurrent executions per region per account, a soft limit that can be raised substantially on request. Invocations beyond it are throttled: synchronous callers get an HTTP 429 error, asynchronous events are retried for up to six hours, and pollers slow down.
  • A scaling rate. Since late 2023, each Lambda function can add up to 1,000 concurrent environments every 10 seconds, until it reaches the account limit. Before that, Lambda allowed an initial burst followed by a slower ramp of hundreds of environments per minute. Ramp-up speed matters for sudden spikes such as a ticket sale opening.
  • Per-function controls. Reserved concurrency guarantees a function a slice of the account's concurrency and also caps it at that level, protecting both the function and whatever it calls. Event source mappings for queues can set a maximum concurrency for consumers.

Other platforms differ: Cloud Run and Azure Functions let one instance handle many requests concurrently, Cloud Run defaulting to up to 80 concurrent requests per instance, so they need fewer instances for I/O-bound work and can share connection pools, at the cost of noisy-neighbour effects between requests within an instance. Cloudflare Workers run in every edge location and scale per location.

The scaling model, in depth#

Scaling can hurt what you call. A function that scales to 3,000 environments in seconds can send 3,000 concurrent queries to a database sized for 100 connections, or flood a partner API with a rate limit of 50 requests per second. Serverless moves the bottleneck downstream. The standard defences are:

  • Cap concurrency deliberately: reserved concurrency on the function, or maximum concurrency on its queue trigger, sized to what the downstream system can take.
  • Put a queue in front of fragile dependencies, so bursts are absorbed and drained at a steady rate. See Message Queues.
  • Pool connections outside the function: a proxy such as Amazon RDS Proxy or PgBouncer holds a small pool of database connections shared by thousands of environments; or use databases with HTTP or connectionless APIs, such as DynamoDB, the Aurora Data API, Neon's serverless driver or PlanetScale's HTTP driver.
  • Rate-limit at the edge for client-facing APIs, with API gateway throttling or a token bucket. See Rate Limiting.

Admission control for extreme spikes. For events where demand vastly exceeds supply, such as tickets for a stadium tour that sell out in minutes, scaling every layer is neither possible nor helpful: there are only so many seats. A virtual waiting room admits users to the booking flow at a controlled rate. Users requesting the booking page join a queue, ordered by arrival time, for example in a Redis sorted set; the server pushes each user's position and estimated wait over Server-Sent Events or WebSockets; a scheduler admits batches from the front of the queue as capacity allows, marking each admitted session in a short-lived Redis set that the booking service checks before accepting reservations. Serverless components fit well around such a system, for the queue's web front end and the admission scheduler, while the waiting room protects the stateful booking core, whose capacity cannot scale instantly. See Real-Time Updates and Dealing with Contention.

Throttling behaviour by trigger. Because throttling differs by trigger, the same concurrency cap has different effects. A synchronous API returns errors to users, so caps there must be generous, with provisioned concurrency for predictable peaks. An asynchronous trigger retries throttled events for hours, so a cap only delays work. A queue trigger simply processes more slowly, the backlog grows, and the queue becomes the buffer, which is usually exactly the desired behaviour for background work.

Burst maths. Suppose a flash sale sends traffic from 100 to 10,000 requests per second within a minute, with 100 ms functions. Required concurrency rises from 10 to 1,000. At 1,000 new environments every 10 seconds, Lambda can reach that in about 10 seconds, faster than most auto-scaling groups of virtual machines, which take minutes to boot instances. But each new environment incurs a cold start, so for the first seconds of the spike many users see an extra few hundred milliseconds of latency; provisioned concurrency scheduled before the sale removes this.

Concurrency-based thinking for capacity planning. For serverless systems, plan in concurrency, not servers: peak request rate times the 99th-percentile duration under degraded conditions, compared against account limits, reserved concurrency and the connection limits of every downstream system.

Limits: duration, state and concurrency#

Serverless platforms trade flexibility for operability, and the trade shows up as hard limits. AWS Lambda's are representative; exact values change over time and differ by platform, so check the current documentation when designing.

  • Duration: a Lambda invocation can run for at most 15 minutes. Requests through API Gateway's REST APIs are limited to about 29 seconds by default. Cloud Run services allow requests up to 60 minutes; Cloudflare Workers limit CPU time per request rather than wall-clock time.
  • Memory and CPU: Lambda memory ranges from 128 MB to about 10 GB, and CPU is allocated in proportion, up to six virtual CPUs at the top. A function that needs more CPU must be given more memory, even if it does not need the memory.
  • State: no durable local state. /tmp is ephemeral and per-environment, and in-memory caches survive only while the environment is warm. Two consecutive requests from the same user may land on different environments.
  • Concurrency: the account and regional limits and scaling rate described above, plus per-function reserved concurrency.
  • Payloads: on Lambda, 6 MB for synchronous requests and responses, and much smaller limits for asynchronous events; large data must be passed by reference, such as an S3 key.
  • Package size: 50 MB zipped or 250 MB unzipped for zip deployments, 10 GB for container images.
  • No inbound connections: you cannot SSH in or accept arbitrary TCP connections; the function exists only while handling an event. Long-lived WebSocket connections must be held by a managed gateway, such as API Gateway's WebSocket APIs, which invokes the function per message.
  • Hardware: general-purpose CPUs only on mainstream FaaS; GPUs are generally unavailable on Lambda, though some platforms, such as Cloud Run, offer GPU-backed serverless containers.

Limits, in depth#

Working around the duration limit. Long jobs do not fit in one invocation, but they can usually be broken up:

  • Chunk and fan out: split the input into pieces, such as by file, by date range or by 10,000-row batches, and process each in its own invocation, in parallel. A video transcoder can split the video into segments, transcode each segment in a separate function, and merge them, finishing far faster than one long job.
  • Checkpoint and continue: process until close to the time limit, save progress to a database, and re-invoke the function to continue from the checkpoint.
  • Orchestrate with a workflow service: AWS Step Functions chains functions with retries, waits, parallel branches and human approvals; standard workflows can run for up to a year, with the state machine itself holding the progress. Azure Durable Functions write orchestrations as code, with the runtime checkpointing and replaying state. Workflow engines such as Temporal offer the same pattern outside one cloud. See Workflow Engines and Temporal and Handling Long-Running Tasks.
  • Hand off to serverless containers or batch services, such as Fargate, Cloud Run jobs or AWS Batch, which accept hours-long jobs without managing servers.

Working without local state. Statelessness pushes design choices:

  • Sessions in a token, such as a signed JWT, or in a fast store such as DynamoDB or Redis.
  • Files in object storage, passed by key; large intermediate data written to S3 rather than held in memory.
  • Coordination through the database, for example conditional writes and optimistic locking, rather than in-memory locks, since two environments may handle the same entity at once. See Concurrency Control and Locking.
  • Idempotency keys stored in a table, so retried events do not repeat side effects.

The "functions calling functions" anti-pattern. Chaining functions synchronously, where function A invokes function B and waits, means paying for A's idle waiting time, multiplying cold starts, and coupling availability. Hellerstein and colleagues' critique "Serverless Computing: One Step Forward, Two Steps Back" (CIDR 2019) pointed out that early FaaS made communication between functions slow and expensive, forcing data through storage, and lacked specialised hardware, making it a poor fit for data-intensive and distributed computing. Platforms have improved since, but the advice stands: connect functions through queues, event buses or workflow services, not direct synchronous calls.

Limits as a feature. Hard limits are also protective. A 15-minute ceiling stops runaway jobs; memory caps prevent one tenant's leak from affecting others; concurrency limits stop a bug from launching a million environments and a million-dollar bill. Teams moving to serverless often find their designs improving because the limits force small, idempotent, stateless units of work.

The cost model#

Serverless pricing has three common components:

  • Requests: a small fee per invocation, about 0.20 dollars per million on Lambda.
  • Compute time: billed in GB-seconds, memory size multiplied by duration, measured per millisecond on Lambda since 2020. The x86 price is about 0.0000166667 dollars per GB-second, with Arm-based Graviton functions about 20% cheaper.
  • Associated services: API gateway requests, data transfer, logs, queues and databases, each priced per use. These are often larger than the function cost itself.

There is no charge when nothing runs, which is the defining economic property. A free tier, such as 1 million requests and 400,000 GB-seconds a month on Lambda, makes small workloads free.

A worked example. A function with 512 MB of memory and an average duration of 120 ms costs, per invocation, 0.5 GB × 0.12 s = 0.06 GB-seconds, or about 0.000001 dollars of compute, plus 0.0000002 dollars for the request: roughly 1.2 dollars per million invocations. At 3 million invocations a month, about 3.60 dollars before the free tier. If fronted by an HTTP API gateway at about 1 dollar per million requests, add another 3 dollars.

The crossover with servers. Now scale the same function to a steady 1,000 requests per second, 2.6 billion requests a month: about 3,100 dollars a month for Lambda compute and requests, plus about 2,400 dollars for an HTTP API gateway. The same work, 1,000 requests per second at 120 ms of mostly CPU-light I/O, could run on a handful of modest container instances behind a load balancer, perhaps a few hundred dollars a month. At high, steady utilisation, paying per millisecond costs several times more than reserved capacity. At low or spiky utilisation, the reverse holds by an even larger factor, because servers cost money while idle.

The cost model, in depth#

Utilisation is the key variable. A server costs the same whether it is 5% or 95% busy. A function costs in proportion to work done. If a server at full utilisation is, say, four times cheaper per unit of work than the equivalent function, then the break-even is around 25% average utilisation: below it, serverless wins; above it, servers win. Most production fleets average well under 25% CPU, because they are sized for peaks and redundancy, which is why serverless is cheaper for more workloads than intuition suggests, and why it loses badly for steady, high-throughput services.

Hidden costs. Real serverless bills often surprise teams:

  • API gateway fees: REST APIs on API Gateway cost about 3.50 dollars per million requests, HTTP APIs about 1 dollar per million, often more than the functions behind them. Function URLs or an Application Load Balancer can be cheaper at high volume.
  • Logging: every invocation writes logs, and ingesting logs into CloudWatch costs about 0.50 dollars per GB. A chatty function at high volume can spend more on logs than on compute.
  • NAT gateways and data transfer: functions in a private network reaching the internet through a NAT gateway pay per GB processed.
  • Idle waiting: a function waiting 2 seconds for a slow third-party API is billed for 2 seconds. I/O-heavy functions pay for waiting, which is why orchestration services that wait for free, and platforms that bill only CPU time, such as Cloudflare Workers, can be much cheaper for such workloads.
  • Per-transition orchestration fees: Step Functions standard workflows charge per state transition, about 25 dollars per million transitions. A workflow with many tiny steps run at high frequency becomes expensive. This was a central factor in Amazon Prime Video's 2023 account of moving a video-quality monitoring tool from Step Functions and Lambda, which also passed frames between steps through S3, into a single process on ECS, cutting that tool's infrastructure cost by over 90%. See Monolith vs Microservices.

Memory tuning. Because CPU scales with memory, doubling a CPU-bound function's memory can halve its duration, leaving the cost unchanged while cutting latency; for some functions, more memory even reduces cost because the function finishes more than twice as fast. Tools such as the open-source AWS Lambda Power Tuning run a function at several memory sizes and plot cost against duration, to pick the optimum.

Total cost of ownership. The bill is only part of the cost. Serverless removes server patching, capacity planning, auto-scaling configuration and much of the on-call burden for infrastructure. For a small team, the engineering time saved can be worth far more than any difference in the cloud bill. For a large organisation with a mature platform team running Kubernetes at high utilisation, the calculation often goes the other way for core high-traffic services.

Serverless databases#

A serverless application with a traditional database still has a server to size, patch and pay for around the clock, and a connection limit that thousands of function environments can exhaust. Serverless databases extend the model to data: capacity scales automatically, often to zero, and pricing is per request or per unit of consumed capacity.

The main families:

  • Serverless key-value and document stores: DynamoDB in on-demand mode bills per read and write request with no capacity planning, scales to very high request rates, and uses an HTTP API, so there are no connection pools to exhaust. Firestore, Cosmos DB serverless and Upstash Redis offer similar per-request models. See DynamoDB.
  • Serverless relational databases: Aurora Serverless v2 scales MySQL- or PostgreSQL-compatible capacity in fine-grained units called Aurora Capacity Units, each about 2 GB of memory with matching CPU, adjusting within seconds, and since 2024 can pause at zero when idle. Neon separates PostgreSQL compute from a shared, multi-tenant storage layer, so compute can scale to zero and resume in a fraction of a second, and databases can be branched like Git. PlanetScale, built on Vitess, offers sharded MySQL with non-blocking schema changes. Aurora DSQL, announced by AWS in 2024, is a distributed SQL database with active-active multi-region writes and no instances to manage.
  • Edge and embedded databases: Cloudflare D1 and Turso run SQLite-based databases replicated close to edge functions.
  • Serverless analytics: BigQuery, Athena and Snowflake bill per query or per second of compute, separating storage from compute so that analytical capacity exists only while queries run.

Serverless databases, in depth#

Separation of storage and compute. Most serverless databases share one architectural idea: durable data lives in a distributed, replicated storage layer, and stateless compute nodes that run queries can be added, removed or paused without moving data. Aurora's storage layer replicates data six ways across three availability zones; Neon stores PostgreSQL pages and write-ahead log in its own storage service backed by object storage; Snowflake and BigQuery read columnar files from object storage. Because compute holds no unique data, it can scale to zero and come back, at the cost of a resume latency, from a few hundred milliseconds to several seconds, and cold caches after resume.

Per-request pricing changes data modelling. With DynamoDB on-demand, every read and write unit is billed, roughly 0.125 dollars per million read units and 0.625 dollars per million write units in major regions after AWS's late-2024 price reduction. A design that reads 50 items to render a page costs 50 times more than one that reads one well-designed item, so access-pattern-driven modelling, such as single-table design with pre-joined items, directly reduces the bill as well as latency. At steady high throughput, provisioned capacity with auto-scaling is markedly cheaper than on-demand, the same utilisation crossover as for functions.

Connections are the classic problem. PostgreSQL and MySQL allocate memory per connection, and a few hundred connections can strain a server. A burst to 2,000 Lambda environments, each opening a connection, overwhelms them. Solutions, from best to worst: use a database with an HTTP or connectionless API; put a pooling proxy, such as RDS Proxy, in between, which multiplexes many client connections over a small pool; cap the function's concurrency to match the pool; and open connections in initialisation code so warm environments reuse them.

Keeping a search index in sync. A common serverless pattern is to keep the database as the source of truth and derive query-optimised stores from its change stream. For example, a dating or marketplace app may store profiles in DynamoDB and serve "people near me matching these filters" from an OpenSearch index with geospatial and attribute indexes. A function triggered by DynamoDB Streams receives each change and updates the index. Two details matter. First, consistency lag: the index is eventually consistent, typically within a second or two, so the design must tolerate briefly stale results. Second, batching: search engines are optimised for reads and handle many small writes poorly, so the stream trigger should be configured with a batch size and batching window, such as up to 500 records or 5 seconds, and use the bulk indexing API. This is change data capture with a serverless consumer. See Change Data Capture and Geospatial Indexing.

Choosing. Pick DynamoDB or Firestore for high-scale key-value and document access with known patterns and spiky load; Aurora Serverless v2 or Neon when you need full SQL and relational modelling with variable load; a regular provisioned database when load is steady and high; and serverless analytics engines for ad-hoc queries over large data.

Good and bad use cases#

Serverless is excellent for some workloads and a poor fit for others. The deciding factors are traffic shape, duration, state, latency sensitivity and steady-state volume.

Good fits:

  • Event glue: reacting to a file upload by generating thumbnails, scanning for malware or extracting text; reacting to a database change by updating a search index, sending a notification or invalidating a cache.
  • Webhooks and integrations: receiving payment, Git or chat webhooks at unpredictable rates.
  • Scheduled jobs: nightly reports, clean-ups, data exports, certificate checks, replacing cron servers.
  • APIs with spiky, unpredictable or low traffic: internal tools, new products, B2B APIs with bursty partners, marketing campaign back ends.
  • Embarrassingly parallel batch work: processing thousands of files, rendering, simulations or ETL steps by fanning out to thousands of functions for a few minutes.
  • Stream and queue processing at moderate volume, with the platform managing pollers, batching and retries.
  • Edge logic: authentication checks, A/B routing, header rewriting, personalisation and redirects at CDN edge locations, using Cloudflare Workers, Lambda@Edge or CloudFront Functions.
  • Prototypes and small teams, where avoiding infrastructure work matters most.

Poor fits:

  • Long-running or stateful processes: video encoding of a whole film in one step, long simulations, game servers, stateful stream processing with large windows.
  • Latency-critical paths with strict tail targets, where an occasional few hundred milliseconds of cold start is unacceptable, unless provisioned concurrency is used.
  • High, steady throughput services, where reserved containers or VMs are several times cheaper.
  • Many persistent connections, such as chat servers holding a million WebSockets, unless a managed gateway holds the connections.
  • Chatty, fine-grained workflows passing large data between many steps, as in the Prime Video case.
  • Specialised hardware, such as GPUs for model training or high-throughput inference, on platforms that do not offer it.
  • Workloads needing fine control of the operating system, kernel parameters, networking or local disks.

Common serverless architectures#

Three shapes cover most serverless systems.

1. The serverless web API. A CDN serves the static front end from object storage; an API gateway authenticates requests and routes them to functions; functions read and write a serverless database; an identity service issues tokens. Every layer scales to zero and to bursts.

2. The event-processing pipeline. Files land in object storage or events in a stream; each triggers a function that transforms, enriches or routes the data to the next store or queue; failures go to dead-letter queues for inspection and replay.

3. The orchestrated workflow. A workflow service, such as Step Functions, coordinates a multi-step business process, calling functions for each step, waiting for callbacks or timers, retrying failed steps, and running compensations, so no single function needs to run long.

Common serverless architectures, in depth#

Function granularity. How much code goes in one function? Options range from a function per route, such as POST /orders, to one function per service, a "Lambdalith" containing a small web framework that routes all of a service's endpoints internally. Per-route functions give fine-grained permissions, scaling and metrics, but multiply deployments and cold starts, since each route has its own environments. A function per service shares warm environments across routes, so cold starts are rarer, and is easier to run locally, at the cost of coarser permissions. Many teams now start with one function per bounded context or per service and split out routes that have very different resource or scaling needs.

Events as the glue. Serverless systems are naturally event-driven: functions communicate by publishing events to an event bus, such as EventBridge, SNS or Kafka, rather than calling each other. Event buses route by content, such as "all OrderPlaced events with a total over 1,000 dollars go to the fraud-check function", and can archive and replay events. This gives loose coupling, but also the usual event-driven challenges of tracing flows, versioning schemas and handling duplicate deliveries. See Event-Driven Architecture.

Infrastructure as code is essential. A serverless application is made of many small managed resources: functions, permissions, queues, topics, tables, buckets and API routes. Managing them by hand is impossible. Frameworks such as AWS SAM, the Serverless Framework, AWS CDK, SST, Terraform and Pulumi define them in code, deploy them as a unit, and create per-developer or per-branch environments cheaply, since idle serverless resources cost almost nothing.

Security model. Each function gets its own IAM role, ideally with least privilege: the thumbnail function can read from one bucket and write to another, and nothing else. This is more granular than most server deployments, where one instance role covers a whole application. The flip side is that dozens of roles and policies must be maintained, and an over-broad policy copied between functions becomes a common vulnerability. Secrets come from a secret manager at initialisation and are cached in memory.

Observability. With no servers to log in to, observability comes from the platform and from instrumentation: structured logs with request IDs, platform metrics such as invocations, errors, throttles, duration and concurrent executions, and distributed traces through the API gateway, functions, queues and databases, via AWS X-Ray or OpenTelemetry. Cold starts appear as an init duration in logs and traces, and should be tracked as their own metric. See Observability.

Testing. Pure business logic in functions should be separated from the handler, so it can be unit-tested without the cloud. Integration tests run against real cloud resources in an ephemeral stack per branch, because emulators, such as LocalStack, do not perfectly reproduce IAM, limits and event formats. Contract tests verify the shape of events between producers and consumers.

When to Use It#

Use serverless when most of these hold:

  • Traffic is spiky, unpredictable, low or intermittent, so idle capacity would be wasted.
  • The work is event-driven and naturally split into short, stateless units: seconds to a few minutes.
  • The team is small or wants to minimise operations, and the speed of delivery matters more than squeezing infrastructure cost.
  • The workload fans out widely for short periods, such as batch processing of many files.
  • You are building glue between managed services: storage, queues, databases, identity, and third-party APIs.
  • Latency targets tolerate occasional cold starts, or you can afford provisioned concurrency on the critical path.

When NOT to Use It#

  • Steady, high-volume services whose fleet would run at high utilisation: containers or VMs with reserved pricing are several times cheaper.
  • Long-running, stateful or connection-heavy workloads: game servers, chat servers holding connections, stateful stream processors, long simulations.
  • Strict tail-latency requirements on every request, without budget for provisioned concurrency.
  • Heavy data movement between steps, where passing data through storage and paying per transition dominates.
  • Workloads that need specialised hardware or OS control.
  • When portability is a hard requirement: deep use of one provider's triggers, IAM and managed services makes moving costly. Knative, OpenFaaS or Cloud Run's container-based model reduce, but do not remove, this coupling.

How to Implement It#

  1. Map the workload to triggers: which events start work, synchronous HTTP, asynchronous notifications, queues, streams or schedules, and what retry and ordering behaviour each implies.
  2. Design small, stateless, idempotent units: each function does one job in seconds; state lives in databases and object storage; every handler tolerates duplicate events.
  3. Connect functions through queues, event buses and workflows, not direct synchronous calls; use a workflow service for multi-step processes and anything long-running.
  4. Choose data stores that suit bursts: HTTP-based or serverless databases, or a connection proxy for relational databases; cap concurrency to what each downstream can handle.
  5. Optimise initialisation: small packages, lazy imports, clients created outside the handler, a fast runtime for latency-sensitive paths, SnapStart or provisioned concurrency where needed.
  6. Set limits and failure paths explicitly: timeouts shorter than the caller's, reserved concurrency, dead-letter queues or on-failure destinations, alarms on throttles and errors.
  7. Define everything as code with SAM, CDK, SST, Terraform or the Serverless Framework, with per-branch environments.
  8. Instrument: structured logs with request IDs, traces across gateway, functions and queues, and dashboards for duration, errors, throttles, concurrency and cold starts.
  9. Model the cost at expected and peak volume, including gateway, logs, data transfer and database requests, and revisit it as traffic grows.

A queue-triggered function in TypeScript that processes a batch, deduplicates retried messages, and reports only the failed messages for retry:

import type { SQSEvent, SQSBatchResponse } from "aws-lambda";
import { DynamoDBClient, PutItemCommand, DeleteItemCommand } from "@aws-sdk/client-dynamodb";
 
const ddb = new DynamoDBClient({});      // created once per environment, reused while warm
const TABLE = process.env.DEDUP_TABLE!;
 
export const handler = async (event: SQSEvent): Promise<SQSBatchResponse> => {
  const failures: { itemIdentifier: string }[] = [];
  for (const record of event.Records) {
    const msg = JSON.parse(record.body) as { eventId: string; orderId: string };
    const key = { pk: { S: msg.eventId } };
    try {
      await ddb.send(new PutItemCommand({            // claim the event ID once
        TableName: TABLE,
        Item: { ...key, expiresAt: { N: String(Math.floor(Date.now() / 1000) + 86400) } },
        ConditionExpression: "attribute_not_exists(pk)",
      }));
    } catch (err: any) {
      if (err.name === "ConditionalCheckFailedException") continue; // duplicate: already done
      failures.push({ itemIdentifier: record.messageId });
      continue;
    }
    try {
      await fulfilOrder(msg.orderId);                // the real work, idempotent where possible
    } catch {
      await ddb.send(new DeleteItemCommand({ TableName: TABLE, Key: key })); // release the claim
      failures.push({ itemIdentifier: record.messageId });            // retry just this one
    }
  }
  return { batchItemFailures: failures };            // needs ReportBatchItemFailures enabled
};
 
declare function fulfilOrder(orderId: string): Promise<void>;
TechnologyFits when
AWS LambdaThe broadest FaaS ecosystem and triggers; AWS-centric systems
Google Cloud Run and Cloud Run functionsContainer-based serverless with concurrency per instance; long requests; GPUs
Azure Functions and Durable FunctionsMicrosoft stack; code-first orchestrations
Cloudflare Workers, Vercel and Netlify functionsEdge logic with near-zero cold starts; front-end-centric apps
AWS Fargate, Azure Container AppsServerless containers for long-running services and jobs
Knative, OpenFaaS, OpenWhiskFaaS on your own Kubernetes; portability across clouds
AWS Step Functions, TemporalMulti-step workflows, long waits, retries and compensation
API Gateway, function URLs, ALBHTTP front doors with auth, throttling and routing
SQS, SNS, EventBridge, Pub/SubQueues and event buses connecting functions
DynamoDB, Firestore, UpstashServerless key-value and document data with per-request pricing
Aurora Serverless v2, Neon, PlanetScale, Aurora DSQLServerless relational databases
RDS Proxy, PgBouncerConnection pooling between bursts of functions and SQL databases
SAM, CDK, SST, Serverless Framework, TerraformInfrastructure as code for serverless applications

Trade-offs#

OptionProsConsPick when
FaaS such as LambdaNo servers; scale to zero and to bursts; per-ms billing; fine-grained IAMCold starts; 15-minute limit; one request per environment; costly at steady loadEvent-driven, spiky, short tasks
Serverless containers such as Cloud Run and FargateAny container; longer requests; concurrency per instanceCoarser scaling; some idle cost unless scaled to zeroWeb services and jobs that outgrow FaaS limits
Edge functions such as WorkersMilliseconds cold start; close to users; billed on CPU timeRestricted runtime and APIs; small limitsRequest routing, auth, personalisation at the edge
Containers on Kubernetes or VMsFull control; cheapest at high utilisation; portableCapacity planning, patching, scaling, on-callHigh, steady traffic; stateful or specialised workloads
Provisioned concurrencyNo cold starts up to a levelHourly cost; capacity planning returnsLatency-critical serverless paths with known peaks
Serverless databases, on-demandNo capacity planning; scale to zero or burstsPer-request price at high volume; resume latencyVariable or unpredictable data workloads
Provisioned databasesLower cost at steady load; predictableSizing; idle cost; connection limits under burstsSteady, high database load

Common Pitfalls#

  • Ignoring cold starts on user-facing paths, especially with heavy Java or .NET frameworks; measure p99 including init duration.
  • Exhausting database connections when functions burst; use pooling proxies, HTTP-based databases or concurrency caps.
  • Non-idempotent handlers, which double-charge or double-send when the platform retries asynchronous or queue events.
  • Synchronous function-to-function chains, paying for waiting and multiplying latency and failure.
  • Timeout mismatches: a function timeout longer than the API gateway's, so users get errors while functions keep running; or an SQS visibility timeout shorter than the function timeout, causing duplicate processing.
  • Poison messages blocking a stream shard, because there is no maximum retry age, bisect-on-error or partial-batch reporting.
  • Recursive triggers, such as a function that writes to the same bucket that triggers it, creating an expensive infinite loop; write outputs to a different bucket or prefix. AWS now detects some recursive loops automatically, but design should not rely on it.
  • Over-broad IAM roles copied between functions.
  • Unbounded logging and per-request gateway fees that dwarf the compute bill.
  • Treating serverless as free at scale, and not revisiting the architecture when traffic becomes high and steady.
  • Deep vendor lock-in by accident, with business logic tangled with provider-specific event formats; keep core logic in plain modules behind thin handlers.

Real-World Examples#

These are summarised from public engineering posts and talks.

  • Amazon Prime Video described in 2023 moving one video-quality monitoring tool from a Step Functions and Lambda design, which hit a scaling limit at about 5% of the expected load and incurred high per-transition and S3 costs, to a single process on ECS, cutting that tool's infrastructure cost by over 90%. It is a lesson about a specific high-volume, data-heavy workload, not about serverless in general.
  • Meta described XFaaS at SOSP 2023: an internal function platform handling trillions of calls a day. It keeps hardware utilisation high by deferring delay-tolerant calls to off-peak times, sharing pre-warmed runtime pools across functions, and treating data centres worldwide as one pool.
  • The BBC has written about rebuilding much of its website on AWS with a serverless rendering layer, where functions render web pages behind caches, handling large and spiky traffic around major news events.
  • Liberty Mutual has spoken publicly about a "serverless-first" strategy for new applications, using managed services to cut operational work and time to market.
  • Cloudflare runs Workers on its global edge network, with V8 isolates making cold starts nearly invisible; many sites use Workers for routing, authentication and API back ends.
  • Firecracker itself is a real-world example of infrastructure designed for serverless: AWS built it so that Lambda and Fargate could give each customer workload VM-grade isolation at container-like speed and density.

In the Interview#

Deep Dive: Inside a FaaS platform, from Firecracker to placementShow

Firecracker's design. Firecracker runs one process per micro-VM. The process implements a minimal virtual machine monitor on KVM: a handful of emulated devices, virtio-net and virtio-block, a serial console and a minimal keyboard controller used only to reset the VM, plus a REST API on a Unix socket for configuration. Removing everything else, such as PCI, USB, graphics and legacy BIOS, shrinks both the attack surface and the start-up time. Each Firecracker process is further confined by a jailer, which places it in its own chroot, namespaces and cgroups, drops privileges, and applies a strict seccomp filter allowing only the few dozen system calls the VMM needs. Built-in rate limiters on network and disk I/O stop one micro-VM from starving its neighbours. Defence in depth means an attacker must escape the guest kernel, then the VMM, then the jail.

Density. Because each micro-VM's overhead is a few megabytes, a large host can run thousands of them. The guest kernel and runtime pages are similar across many micro-VMs, and memory is allocated lazily as the guest touches it, so the platform can oversubscribe memory and CPU, packing environments whose peak usage would exceed the host if all peaked together, relying on statistical multiplexing across many uncorrelated workloads. The Firecracker paper describes this soft allocation as key to Lambda's economics.

Placement for warmth. The placement layer tries to send each invocation to a host that already has a warm, idle environment for that function version, and otherwise to a host with spare capacity and, ideally, the function's code already cached. It must balance packing for utilisation against spreading for resilience and noisy-neighbour avoidance. Research such as "Peeking Behind the Curtains of Serverless Platforms" (Liang Wang and colleagues, USENIX ATC 2018) measured major providers from the outside, observing cold-start latencies, how long idle instances were kept, how instances were co-located on hosts, and performance isolation problems on some platforms at the time; it showed how much platform design choices affect users.

Snapshots. Firecracker can snapshot a running micro-VM's memory and device state to disk and restore it elsewhere. SnapStart uses this: initialise once, snapshot, and restore many times. Restoring requires loading memory pages lazily from the snapshot, cached across hosts, so that a restored environment starts quickly and fetches only the pages it touches. Because every restore begins from identical memory, randomness, unique IDs and network connections must be re-established after restore, and the platform provides hooks for this.

Isolates versus micro-VMs. Isolate-based platforms such as Cloudflare Workers avoid most of this machinery: one process hosts thousands of isolates, there is no guest kernel, and context switching between tenants is cheap. In exchange, every tenant shares one process and one runtime, so the platform relies on the V8 sandbox, frequent runtime patching and extra defences, such as process-level isolation for suspicious workloads, against Spectre-style side channels. The choice reflects a classic trade-off between isolation strength and density and start-up speed.

Deep Dive: Worked design and numbers for an image-processing pipelineShow

Requirements. A photo-sharing app receives 2 million uploads a day, averaging about 23 per second, with evening peaks of 200 per second and launch-day spikes of 1,000. Each upload needs three resized versions and a content-safety check. Processing takes about 1.5 seconds per image on one vCPU.

Design. The client uploads directly to object storage with a pre-signed URL, so no compute sits in the upload path. The storage bucket sends an event to an SQS queue, not directly to the function, so bursts are buffered and failures retried. A function with 1,769 MB of memory, the size at which Lambda allocates the equivalent of one full vCPU, consumes the queue in batches of 5. It writes resized images to a separate output bucket, avoiding recursive triggers, and records results in a DynamoDB table keyed by image ID and version, which also makes reprocessing idempotent. Messages that fail five times go to a dead-letter queue with an alarm.

Concurrency. At the 200-per-second peak, concurrency is 200 × 1.5 s = 300 environments. A launch spike of 1,000 per second would need 1,500; we cap the function at 800 with maximum concurrency on the queue trigger, so the queue absorbs the excess and drains within minutes. The DynamoDB table in on-demand mode easily handles 800 writes per second.

Cost. Daily compute is 2,000,000 × 1.5 s × 1.769 GB ≈ 5.3 million GB-seconds. At about 0.0000166667 dollars per GB-second, that is about 88 dollars a day, roughly 2,650 dollars a month, or about 2,100 dollars on Arm functions. Requests add 2 million × 0.20 dollars per million ≈ 0.40 dollars a day, which is negligible. SQS and DynamoDB add a few hundred dollars more.

Comparison with servers. The average load is 23 × 1.5 ≈ 35 busy vCPUs, and the evening peak is 300. A container fleet auto-scaling between, say, 50 and 320 vCPUs, averaging perhaps 90 vCPUs including headroom and the lag of scaling, would cost on the order of 2,000 to 3,000 dollars a month at typical on-demand prices, cheaper with reserved or spot instances. So the costs are comparable. The serverless design wins on operations, with no cluster to run, and on burst handling: it reaches 800 concurrent workers in seconds, where VMs take minutes. If volume grew tenfold and became steadier, a container fleet on spot instances would probably become meaningfully cheaper, and the decision should be revisited.

Latency. Users see their photo immediately, using the original image or a client-side preview, while resized versions appear within a few seconds. Cold starts, a few hundred milliseconds for a Python function with an image library, are irrelevant on this asynchronous path.

Deep Dive: Research and evolution of serverless computingShow

Early research. "Occupy the Cloud: Distributed Computing for the 99%" (Eric Jonas and colleagues, SoCC 2017) introduced PyWren, which ran large parallel Python computations by launching thousands of Lambda functions, showing that FaaS could serve as an on-demand supercomputer for embarrassingly parallel work. "SOCK: Rapid Task Provisioning with Serverless-Optimized Containers" (Edward Oakes and colleagues, USENIX ATC 2018) studied container start-up costs and showed how lean containers and caching of initialised Python interpreters, with pre-imported packages, cut start latency dramatically.

The critiques and the vision. "Serverless Computing: One Step Forward, Two Steps Back" (Joseph Hellerstein and colleagues, CIDR 2019) argued that FaaS was a step forward for autoscaling but a step back for data-centric and distributed computing, citing limited lifetimes, I/O bottlenecks, communication only through slow storage, and no specialised hardware. "Cloud Programming Simplified: A Berkeley View on Serverless Computing" (Eric Jonas and colleagues, UC Berkeley technical report, 2019) predicted that serverless would become the default form of cloud computing, and listed the challenges to get there: ephemeral storage, fine-grained coordination, predictable performance, security and better abstractions for state.

Measurement and optimisation. "Serverless in the Wild" (2020) gave the first large-scale characterisation of a production FaaS workload, at Azure, and an adaptive keep-alive policy. The Firecracker paper (2020) explained how AWS achieved isolation and density. "On-demand Container Loading in AWS Lambda" (2023) showed how large container images could cold-start quickly through chunking, deduplication and caching. XFaaS (SOSP 2023) showed how Meta reached high utilisation by treating its whole fleet as one pool and time-shifting delay-tolerant calls.

Product evolution. Key milestones include AWS Lambda in 2014; Azure Functions and Google Cloud Functions in 2016 and 2017; Cloudflare Workers, announced in 2017; Firecracker's open-sourcing and Knative in 2018; Cloud Run and Lambda provisioned concurrency in 2019; container image support and 1 ms billing for Lambda in 2020; Arm-based Lambda in 2021; SnapStart in 2022; faster per-function scaling in 2023; and the steady extension of serverless pricing to databases, from DynamoDB on-demand in 2018 to Aurora Serverless v2 scaling to zero in 2024.

Where it is heading. The trends point to fewer differences between serverless and containers: serverless platforms run arbitrary containers with per-instance concurrency and GPUs, while container platforms scale to zero. Durable execution, where the platform persists the state of long-running code, addresses the limit on state and duration. Edge platforms bring compute and data closer to users. The core idea, paying for work rather than for machines, keeps spreading to more of the stack.

Key Takeaways#

  • Serverless means no servers to manage, automatic scaling including to zero, and pay-per-use pricing; FaaS is its best-known form, alongside serverless containers, databases, queues and storage.
  • A function is invoked by triggers: synchronous, asynchronous with platform retries, or poll-based from queues and streams in batches. Each implies different retry and ordering behaviour, so handlers must be idempotent.
  • Cold starts come from creating a sandbox, loading code, starting the runtime and running init code; isolation technologies such as Firecracker micro-VMs, gVisor and V8 isolates trade start-up speed and density against isolation strength. Reduce cold starts with lean init, fast runtimes, SnapStart and provisioned concurrency.
  • Scaling is measured in concurrency = request rate × duration; slow dependencies multiply it, and fast scale-out can overwhelm databases and partners, so cap concurrency, buffer with queues and pool connections.
  • Limits on duration, memory, payloads and state push designs toward small, stateless units, chunked work and workflow orchestration.
  • The cost model wins at low, spiky utilisation and loses at high, steady load; watch hidden costs such as gateways, logs, data transfer and orchestration transitions.
  • Serverless databases separate storage from compute to scale per request or to zero; choose HTTP-based stores or connection proxies to survive bursts.
  • Use serverless for event glue, scheduled jobs, webhooks, spiky APIs and parallel batch work; avoid it for long-running, stateful, connection-heavy, latency-critical or high-steady-throughput services.