Understanding Serverless Architecture
What serverless really means, how functions run, cold starts, event-driven design, the cost model, and when serverless is the wrong choice.
There are still servers in serverless. What changes is who thinks about them. You hand the provider a piece of code or a container image, say what should trigger it, and the platform decides how many copies to run, where, and when to throw them away. You pay for the work done rather than for machines sitting idle.
That trade sounds simple, and for a lot of workloads it is the cheapest and least stressful way to run software in the cloud. It also changes how you have to design applications, and it has failure modes that surprise teams coming from virtual machines or Kubernetes. This article opens the Serverless Computing series by explaining the architecture itself: what the term covers, how a function actually runs, how to design for it, what it costs, and where it stops being a good fit. Later articles in the series look at AWS Lambda, Cloud Run functions and Azure Functions individually.
What serverless means
“Serverless” is used loosely, so it helps to pin it down. A service is serverless when it has these properties:
- No servers to manage. You don’t pick instance types, patch operating systems or size a cluster. The unit you deploy is code, a container image or a configuration.
- Automatic scaling, including to zero. Capacity follows demand. When nothing is happening, nothing is running, and you are not billed for compute.
- Pay per use. Billing is tied to requests, execution time or data processed, not to provisioned capacity.
- Built-in availability. The provider spreads the service across zones in a region without you configuring it.
Compare that with the cloud service models: serverless sits at the platform end of the spectrum, but goes further than classic PaaS, which usually still asks you to choose how many instances to keep running.
More than functions
Functions as a Service (FaaS) is the best-known form: AWS Lambda, Cloud Run functions (formerly Google Cloud Functions) and Azure Functions. But a serverless architecture is rarely made of functions alone. It is usually a set of managed services wired together by events:
| Role | AWS | Google Cloud | Azure |
|---|---|---|---|
| Functions | Lambda | Cloud Run functions | Azure Functions |
| Serverless containers | ECS on Fargate | Cloud Run | Azure Container Apps |
| HTTP front door | API Gateway, Lambda function URLs | Cloud Run URLs, API Gateway | API Management, built-in HTTP triggers |
| Queues and pub/sub | SQS, SNS | Pub/Sub | Service Bus, Storage queues |
| Event routing | EventBridge | Eventarc | Event Grid |
| Workflows | Step Functions | Workflows | Durable Functions, Logic Apps |
| Object storage | S3 | Cloud Storage | Blob Storage |
| Database | DynamoDB, Aurora Serverless | Firestore | Cosmos DB (serverless) |
The functions hold your business logic. Everything around them is managed glue that also scales on demand. A useful way to think about a serverless application is as a graph of events flowing between these services, with small pieces of your code at the points where decisions are made.
flowchart LR
U["Client"] --> G["HTTP endpoint"]
G --> F1["Function: create order"]
F1 --> DB[("Managed database")]
F1 --> Q["Queue"]
Q --> F2["Function: charge payment"]
F2 --> E["Event bus"]
E --> F3["Function: send email"]
E --> F4["Function: update analytics"]
S["Object storage upload"] --> F5["Function: resize image"]
T["Schedule"] --> F6["Function: nightly report"]
Notice that only the first step is a request someone waits on. The rest happens asynchronously, through a queue and an event bus. That split between the synchronous path and the background work is the core design decision in most serverless systems, and it comes back several times below.
How a function actually runs
When an event arrives for a function, the platform needs an execution environment for it: an isolated sandbox (a lightweight virtual machine such as Firecracker on Lambda, or a gVisor or VM sandbox on Google Cloud) with your runtime and code loaded. Two cases follow.
- Warm start. An idle environment from an earlier invocation is still around. The platform reuses it, and your handler runs almost immediately.
- Cold start. No idle environment exists, so the platform creates one: it allocates a sandbox, downloads your code or image, starts the runtime, and runs your initialization code (imports, SDK clients, database connections). Only then does the handler run.
sequenceDiagram
participant C as Caller
participant P as Platform
participant E as Execution environment
C->>P: Event or request
alt No idle environment
P->>E: Create sandbox, load code
E->>E: Run init code
end
P->>E: Invoke handler
E-->>P: Result
P-->>C: Response
Note over E: Kept idle for reuse, then reclaimed
Cold starts add anything from tens of milliseconds to several seconds, depending on the runtime, the size of the package and how much work your initialization does. Interpreted runtimes with small packages start fastest. Large Java or .NET applications with heavy frameworks start slowest.
Two practical rules follow from this lifecycle:
- Put expensive setup outside the handler. Code at module level runs once per environment and is reused by every warm invocation. Create SDK clients and connection pools there.
- Don’t rely on anything in memory surviving. An environment can be reclaimed at any time. Local files and in-memory caches are an optimization, never the source of truth.
Each provider has a way to keep environments ready when cold starts matter. Lambda offers provisioned concurrency and SnapStart for supported runtimes, Cloud Run lets you set minimum instances, and the Azure Functions Flex Consumption plan has always-ready instances. All of them trade back some of the pay-per-use model: you pay for that warm capacity whether or not it is used.
A function creates a new database client inside its handler on every invocation, and latency is high even when traffic is steady. What is the simplest improvement?
Correct! Initialization code outside the handler runs once per execution environment, so every warm invocation reuses the client instead of paying the setup cost again.
Concurrency and scaling
On Lambda, each execution environment handles one request at a time. Ten simultaneous requests need ten environments, and scaling means creating more of them. Cloud Run functions and Cloud Run let one instance serve many concurrent requests, and Azure Functions instances also process several events in parallel. This matters for cost and for downstream systems: a burst of a thousand requests can become a thousand database connections on a one-request-per-environment model.
Scaling is fast but not unlimited. Every provider has per-account or per-function caps on concurrency or instance count, and some of them start low on new accounts. Set an explicit maximum on functions that talk to something fragile, such as a relational database or a rate-limited third-party API, so a traffic spike can’t turn into an outage somewhere else.
Designing for events
Most serverless code is triggered by something other than a user waiting on a response: a file landing in a bucket, a message on a queue, a row changing in a database, a timer firing. Designing for those triggers means accepting a few facts about how event delivery works.
Delivery is at least once
Queues, event buses and asynchronous invocations on all three providers generally guarantee that an event is delivered at least once, not exactly once. Retries after timeouts, network errors or partial failures mean your function will occasionally see the same event twice. The fix is to make handlers idempotent: processing the same event twice must have the same effect as processing it once.
The usual technique is to record a unique key for each event in a store with a conditional write, and skip the work if the key is already there. Here is a Lambda handler for an SQS queue that does that with DynamoDB, and reports failed messages individually so one bad message doesn’t force the whole batch to be retried:
import json
import os
import boto3
from botocore.exceptions import ClientError
# Runs once per execution environment, reused by warm invocations.
dynamodb = boto3.client("dynamodb")
TABLE = os.environ["PROCESSED_TABLE"]
def already_processed(order_id: str) -> bool:
"""Record the order ID; return True if it was recorded before."""
try:
dynamodb.put_item(
TableName=TABLE,
Item={"pk": {"S": order_id}},
ConditionExpression="attribute_not_exists(pk)",
)
return False
except ClientError as err:
if err.response["Error"]["Code"] == "ConditionalCheckFailedException":
return True
raise
def charge_payment(order: dict) -> None:
... # call the payment provider with order["id"] as its idempotency key
def handler(event, context):
failures = []
for record in event["Records"]:
try:
order = json.loads(record["body"])
if not already_processed(order["id"]):
charge_payment(order)
except Exception:
failures.append({"itemIdentifier": record["messageId"]})
return {"batchItemFailures": failures}
The batchItemFailures response only takes effect if the event source mapping has ReportBatchItemFailures enabled. A production version would also remove the marker if charge_payment fails, or record it only after the charge succeeds, so a failed attempt can be retried. The point is the shape: a unique key, a conditional write, and work that is safe to repeat.
Keep state outside the function
Functions are stateless by design. Anything that must outlive one invocation goes into a managed service: a database for records, object storage for files, a cache service for shared hot data, a queue for work in progress. This is what lets the platform start and stop environments freely, and it is the same principle as stateless containers in the Container Services series, applied more strictly.
Prefer queues between steps
A function that calls another function directly and waits for it couples their failures and their bills: you pay for the caller while it waits. Putting a queue or event bus between them lets each step scale, retry and fail on its own. Failed messages that exhaust their retries go to a dead-letter queue, where you can inspect them instead of losing them.
For multi-step processes with branching, waiting or compensation logic, use the provider’s workflow service (Step Functions, Workflows, or Durable Functions) rather than chaining functions by hand. The workflow engine keeps the state of each run, handles retries per step, and shows you exactly where a run failed.
A queue-triggered function sends a confirmation email. Customers occasionally receive the same email twice. What is the right fix?
Correct! Queues deliver at least once, so duplicates are expected; the handler has to detect and skip events it has already processed.
Limits that shape the design
Functions are built for short, bounded pieces of work, and the limits reflect that. These are the figures most likely to affect your design; check the official quota pages for the full lists, since some values vary by account and region.
| Limit | AWS Lambda | Cloud Run functions | Azure Functions (Flex Consumption) |
|---|---|---|---|
| Maximum run time | 15 minutes | 60 minutes for HTTP, 9 minutes for event-driven | Configurable, no fixed maximum; HTTP responses capped at 230 seconds |
| Requests per instance | 1 | Up to 1,000 | Multiple, per trigger settings |
| Memory | Up to 10,240 MB | Set per function | Chosen instance memory size |
| Synchronous payload | 6 MB request and response | Set by Cloud Run request limits | Set by HTTP trigger limits |
| Keep warm | Provisioned concurrency, SnapStart | Minimum instances | Always-ready instances |
If a job doesn’t fit, that is a signal rather than a problem to work around. Long batch jobs belong on a batch service or a container job, and long-lived connections such as WebSockets are usually better served by a serverless container platform or a managed real-time service. The Specialized Compute Services series later covers those options.
The cost model
Function pricing has the same structure on all three providers: a charge per request plus a charge for compute time, measured in memory allocated multiplied by duration (GB-seconds), with a monthly free allowance. Serverless containers bill similarly for CPU and memory while an instance is handling requests, or for its whole lifetime if you choose instance-based billing. Exact prices differ by provider, region and architecture, so use the providers’ pricing calculators rather than rules of thumb.
What matters more than the unit price is the shape of your traffic:
- Spiky or low traffic favours serverless. A service that handles a few thousand requests a day costs very little, because you pay nothing between requests. The equivalent VM costs the same at 3 a.m. as at noon.
- Steady, high traffic often favours provisioned capacity. A function busy around the clock pays a per-unit premium for its elasticity. At some sustained volume, a container platform or VMs with committed-use discounts cost less.
- Waiting costs money. Billing by duration means a function waiting on a slow API is billed for the wait. Asynchronous designs and short timeouts keep this in check.
- The glue is billed too. API gateways, queues, event buses, logs and data transfer each have their own charges. In small applications these can exceed the function costs.
flowchart TB
A["New workload"] --> B{"Runs longer than the function limit?"}
B -->|"Yes"| C["Container job or batch service"]
B -->|"No"| D{"Needs a specific OS, GPU or long-lived connections?"}
D -->|"Yes"| E["Serverless containers or VMs"]
D -->|"No"| F{"Traffic steady and high around the clock?"}
F -->|"Yes"| G["Compare against containers with committed pricing"]
F -->|"No"| H["Functions are a strong fit"]
Serverless, containers and VMs compared
Serverless is one end of a spectrum of control versus convenience. The container orchestration comparison covers the middle of it; this table places all three side by side.
| Functions | Serverless containers | Virtual machines | |
|---|---|---|---|
| Unit you deploy | Code package or image | Container image | Disk image and configuration |
| Scaling | Per event, to zero, automatic | Per request or event, to zero, automatic | Autoscaling groups you configure |
| Billing | Requests plus execution time | CPU and memory while active | Per second while running |
| Cold starts | Yes, mitigations available | Yes, minimum instances available | No, but slow to add capacity |
| Run time limit | Minutes | Minutes to hours | None |
| Operational work | Lowest | Low | Highest |
| Portability | Low, tied to provider triggers | High, standard images | High |
Portability deserves a word. The handler code in a function is usually ordinary code, but the triggers, permissions, event formats and surrounding services are provider-specific. Moving a serverless application between clouds means rewriting the glue, not just redeploying. Keeping business logic in plain modules that the handler calls, rather than inside the handler, limits how much has to change.
Where serverless struggles
Serverless is a good default for many new workloads, but it has real weaknesses:
- Latency-sensitive paths with sparse traffic. If a request arrives every few minutes, many will hit a cold start. Paying for warm capacity fixes it at the cost of the scale-to-zero benefit.
- Connection-heavy backends. Hundreds of short-lived environments each opening database connections can exhaust a relational database. Use a connection proxy such as RDS Proxy, a database with an HTTP API, or a concurrency cap.
- Observability across many small pieces. A single user action can cross a gateway, three functions, two queues and an event bus. Without distributed tracing and correlation IDs in every log line, debugging becomes guesswork.
- Local development and testing. Emulators exist for each provider, but the real behaviour of triggers, permissions and retries is best tested in a cloud environment. Plan for a per-developer or per-branch stack.
- Runaway bills from loops. A function that writes to the same bucket that triggers it can invoke itself indefinitely. Lambda detects some recursive loops and stops them, but the safe habit is to write outputs to a different bucket or prefix and set concurrency limits.
Which workload is the strongest fit for functions?
Correct! Short, event-triggered work with uneven traffic plays to scale-to-zero and per-use billing, while very long jobs and constant high load fit other compute options better.
Further reading
- AWS Lambda: understanding the execution environment lifecycle
- AWS Lambda quotas
- Cloud Run functions overview
- Cloud Run functions quotas
- Azure Functions hosting options
- Azure Functions Flex Consumption plan
Key takeaways
- Serverless means no servers to manage, automatic scaling down to zero, and billing tied to use rather than provisioned capacity. It covers functions, serverless containers and managed back-end services.
- Functions run in execution environments that are created on demand and reused while warm. Put setup code outside the handler and never treat local memory or disk as durable.
- Event delivery is at least once, so handlers must be idempotent. Keep state in managed services and put queues between steps.
- Run time, payload and concurrency limits are design constraints. Long jobs and long-lived connections belong on other compute options.
- Serverless is cheapest for spiky and low traffic. For steady high load, compare against containers or VMs with committed pricing, and count the cost of the surrounding services.
- The handler code is portable; the triggers and glue are not. Keep business logic separate from provider-specific wiring.