Serverless and Function-as-a-Service Architecture Questions
Building applications on managed, event-triggered compute: functions-as-a-service (AWS Lambda, Azure Functions, Google Cloud Functions, Cloudflare Workers) and serverless containers. Covers the invocation lifecycle and cold starts (init vs handler work, provisioned concurrency, packaging, layers and container images), statelessness and externalizing state, execution limits (timeouts, memory, payload and /tmp size), concurrency and scaling behavior (account limits, burst scaling, protecting downstream databases with connection proxies and throttling), event sources and trigger semantics (at-least-once delivery, retries, idempotent handlers, dead-letter handling), composing functions with managed services and workflow orchestrators (Step Functions and equivalents), and serverless-specific observability, security (per-function IAM, secrets) and pay-per-invocation cost modeling. Includes when serverless fits versus containers or VMs, and vendor lock-in trade-offs. General compute selection, generic messaging patterns, and general idempotency theory are covered by their own topics.
Explain stateless versus stateful function design in a serverless architecture. When should a function be fully stateless, and when is holding state (session context, aggregated results, a warm cache) actually justified? Where does that state live once it's outside the function, and what latency or consistency trade-offs come with each option?
Sample Answer
Direct answer
A stateless function keeps nothing it depends on between invocations: everything it needs arrives in the event or is read from an external store, and everything worth keeping is written back out. That is the default in serverless, because the platform runs many copies in parallel, routes each request to whichever copy is free, and destroys copies whenever it likes. Holding state inside the function is justified only as a disposable optimization: a warm cache of read-mostly data or a reused connection, where losing it costs a slower request but never a wrong answer. Anything that must be correct or durable (sessions, running totals, workflow progress) lives outside the function, and you pick the store by the latency and consistency you need.
Why "in-memory state" breaks in FaaS
Three properties of the platform, each enough on its own:
- Many copies. At 50 concurrent requests there are about 50 separate execution environments (sandboxes), each with its own memory. A counter in one is invisible to the others.
- No affinity. A user's second request can land on a different environment than their first, so an in-memory session is simply missing.
- No lifetime guarantee. Environments are frozen when idle, recycled every few hours even under load, and reset after a crash. Memory contents vanish without warning.
The simulation below routes 1,000 click events to environments the way a platform might (any environment, new ones added under load), and has the platform recycle one environment part-way through. Each environment keeps a local counter; the "external" counter stands in for an atomic counter in a database (one whose increments cannot partially overlap: two simultaneous +1s always land as +2, never silently lose one).
import random
random.seed(7)
EVENTS = 1000
envs = {} # env_id -> in-memory click count (what a "stateful" function would keep)
external_total = 0 # stands in for an atomic counter in an external store
next_env = 0
def pick_env():
global next_env
# the platform routes to any idle environment, and adds new ones under load
if not envs or random.random() < 0.01:
envs[next_env] = 0
next_env += 1
return random.choice(list(envs))
for i in range(EVENTS):
e = pick_env()
envs[e] += 1 # in-memory aggregation
external_total += 1 # externalized aggregation
if i == 600: # the platform recycles one environment mid-stream
victim = min(envs)
lost = envs.pop(victim)
print("environments created:", next_env)
print("any single environment's count:", envs[min(envs)])
print("sum of surviving in-memory counts:", sum(envs.values()))
print("counts lost when env", victim, "was recycled:", lost)
print("external counter:", external_total)
Output:
environments created: 15
any single environment's count: 163
sum of surviving in-memory counts: 792
counts lost when env 0 was recycled: 208
external counter: 1000
No single environment knows the true total (163 is one environment's view), the in-memory sum is short by the 208 clicks held in the recycled environment, and only the externalized counter is right.
When holding state is justified
| State kept in the function | Justified? | Condition |
|---|---|---|
| Reused database or HTTP client connection | Yes | Reconnect if it has gone stale after a freeze. |
| Cache of read-mostly data (config, feature flags, meaning switches that turn a feature on or off without a deploy, reference tables, a loaded model) | Yes | Has a TTL (time-to-live, an expiry) or version check; a miss just means one slower request. |
| Per-user session context | No | Another environment will serve the next request. Put it in an external store keyed by session ID. |
| Aggregated results (counters, running sums, batches being built) | No | Copies split the data and recycling loses it. Aggregate in the store, or stream events to something built to aggregate. |
| Progress of a multi-step job | No | A crash or timeout loses it. Use a workflow orchestrator (for example AWS Step Functions, a managed state machine that records each step's result) or a job table. |
The test: if this state disappeared right now, would the next request be slower, or wrong? Slower is acceptable for an in-function cache. Wrong means it belongs outside.
Where externalized state lives, and what each option costs you
| Store | Typical use | Latency (order of magnitude) | Consistency to know about |
|---|---|---|---|
| Key-value database (Amazon DynamoDB, Azure Cosmos DB, Firestore) | Sessions, idempotency records (a stored marker of which request IDs have already been processed, so a retry can be detected and skipped), counters via atomic update | Single-digit milliseconds within the Region | DynamoDB reads are eventually consistent by default (a read right after a write can be stale); request a strongly consistent read when you must see your own write. Atomic ADD/conditional updates let many copies update one counter without losing increments. |
| In-memory cache (Redis or Memcached, as a managed service such as Amazon ElastiCache) | Hot session data, rate-limit counters, shared cache | Sub-millisecond to low milliseconds, network hop included | Replication to replicas is asynchronous, so a failover can lose recent writes. Treat it as a cache unless you've configured and tested durability. On AWS it runs inside a VPC (Virtual Private Cloud, a private network), so the function must join that network. |
| Object storage (Amazon S3) | Large blobs, intermediate files, batch outputs | Tens of milliseconds per request | S3 gives strong read-after-write consistency for objects, but it is not built for small, frequent updates to the same key. |
| Relational database (PostgreSQL, MySQL) | Transactional state across entities | Low milliseconds, plus connection set-up | Strong consistency and transactions; the risk is connection count, since each concurrent environment wants its own connection. Use a connection proxy (such as Amazon RDS Proxy) or cap function concurrency. |
| Workflow orchestrator (Step Functions, Azure Durable Functions) | Multi-step progress, retries, waiting for humans | Per-step overhead, well above a single function call | The orchestrator owns the state machine, so a failed step resumes rather than restarting from zero. |
Worked example: a click-counting API
Requirement: count clicks per article per minute, 2,000 clicks per second at peak, dashboard reads the counts. Assume a lightweight handler, about 15 ms per click (just an increment call): by Little's Law (the number of requests in flight equals the arrival rate times the time each spends being handled), 2,000/s x 0.015s = 30, which is where the "~30 environments in flight" below comes from.
- Wrong: each function keeps
counts[article] += 1in memory and writes it out "every minute". With ~30 environments in flight (the arithmetic above), 30 partial counts race to overwrite each other, and a recycled environment loses its last minute. - Right, simple: each click performs an atomic increment on a key such as
article#42#2026-09-27T10:15in DynamoDB. 2,000 writes per second is fine for the table as a whole, but a single viral article sends all its writes to one key; spread that hot key (a single partition key taking disproportionate traffic) across N sub-keys (#shard0to#shardN) and sum them on read. - Right, at larger scale: put clicks on a stream (a managed, ordered, replayable log of events that many independent readers can consume, such as Amazon Kinesis or Apache Kafka) instead of writing straight to the table. A stream is split into shards, in this context a partition of the stream that one reader handles at a time (a different sense of "shard" from the DynamoDB sub-keys just above, which split a hot row, not a stream); let one consumer, a process reading a shard in order, aggregate clicks per minute and write the result once. Aggregation in a stream consumer is safe because the stream, not the function's memory, is the source of truth: if a consumer crashes partway through a minute, a new one picks up the shard from the last committed position and can be replayed, meaning it re-reads events the stream already has instead of losing them.
- The justified warm state: each function keeps a 60-second in-memory cache of the article metadata it needs to validate clicks. Losing it costs one extra read.
Trade-offs and pitfalls
- Latency versus correctness. Every external read or write adds a network hop. Cache reads locally when stale data is acceptable; never cache anything you then use to make an authoritative decision (balances, inventory).
- Globals leak across requests. Module-level variables survive between invocations in the same environment, so per-request data stored there can bleed into the next user's request. Keep request data local.
/tmpis memory-adjacent state too. Files there survive between warm invocations and vanish on recycle. Same rule: cache only.- Retries make external writes happen twice. Event sources deliver at least once, so a retried invocation can double-increment. Where exactness matters, record a per-event ID with a conditional write (a database write that only succeeds if a stated condition holds, here "this event ID is not already recorded") and skip duplicates.
Describe the lifecycle of a typical FaaS invocation: cold start, initialization, warm invocation, and teardown. Using AWS Lambda as an example, which initialization steps run only on a cold start versus on every request? What does this imply for where you place expensive setup work, like loading a large dependency, in your handler code?
Sample Answer
Direct answer
A FaaS invocation runs inside an execution environment: an isolated sandbox holding your code, the language runtime and any extensions. The first request that needs a new environment pays a cold start: the platform fetches your code, boots the sandbox, starts the runtime and runs your initialization code (everything outside the handler function). Later requests that land on the same environment are warm: only the handler runs. Between requests the environment is frozen; eventually the platform tears it down. So expensive setup, like loading a large dependency, belongs in initialization code at module scope, where it is paid once per environment, not inside the handler, where it would be paid on every request.
The lifecycle, phase by phase (AWS Lambda)
stateDiagram-v2
[*] --> Init: first request or scale-out
Init --> Invoke: handler runs
Invoke --> Frozen: response returned
Frozen --> Invoke: next request (warm)
Invoke --> Init: crash or timeout resets it
Frozen --> Shutdown: idle or recycled
Shutdown --> [*]
- Cold start, platform part. Lambda downloads your code (zip or container image) and starts the sandbox. You cannot run code here; you influence it only through package size and runtime choice.
- Init phase. Three steps, in order: Extension init (starts any extensions, which are helper processes such as monitoring agents), Runtime init (boots Python, Node.js, the JVM, Java's language runtime, and so on), Function init (runs your module-level code: imports, SDK clients, config loads). On-demand functions get 10 seconds for Init; if it does not finish, Lambda retries the Init as part of the first invocation, bounded by the function timeout. (Provisioned concurrency, a paid feature that keeps a chosen number of environments already initialized and idle so the very first request to each hits a warm environment, and SnapStart, which pre-initialize environments, are allowed a longer Init.) Since 1 August 2025, Init time is billed for on-demand zip functions too, as it already was for container images, custom runtimes (a runtime you bring yourself, via the
providedruntime family, instead of one of Lambda's built-in language runtimes) and provisioned concurrency. - Invoke phase. Lambda calls your handler with the event. The function timeout (up to 15 minutes) limits this phase. The
Durationmetric covers this phase only; on a cold invocation theREPORTlog line (a summary line Lambda automatically appends to every invocation's logs, with Duration, Billed Duration and Memory Used) adds a separateInit Durationfield. - Freeze and thaw. After the handler returns, the environment is frozen: no CPU, but memory, open connections and files in
/tmpsurvive. The next request thaws it (a warm start). Background work you started and did not finish resumes on thaw, which is a source of odd bugs. - Shutdown. When the environment is idle long enough, or during routine maintenance (Lambda recycles environments every few hours even under constant traffic), Lambda sends a
Shutdownevent to extensions and kills the runtime. The window is 0 ms with no extensions, 500 ms with an internal extension (one that runs in-process, inside the runtime itself), and 2,000 ms with external extensions (ones that run as their own separate process alongside the runtime, such as a monitoring agent shipped as a layer; Lambda needs longer to signal and wait for a whole separate process to exit cleanly). If an invocation crashes or times out, Lambda resets the environment and the next request pays Init again (the diagram'sInvoke --> Initedge above: the same failure path as a normal shutdown, just triggered by a crash instead of idling out).
What runs only on a cold start versus on every request
| Runs once per environment (cold start only) | Runs on every request |
|---|---|
| Downloading code, starting the sandbox | Your handler function body |
| Extension and runtime start-up | Parsing and validating the event |
Module-level code: import statements, creating SDK and database clients, reading config or secrets, loading a large dependency into memory | Per-request calls to databases or other services |
| Anything you cache in a global variable on first use | Building the response |
Where to put expensive setup
boto3 is the AWS SDK for Python, and /opt is the read-only directory where Lambda mounts any layers attached to the function, the natural place a packaged model file would land.
import json
import boto3
s3 = boto3.client("s3") # module scope: created once per environment
_model = None # large dependency, loaded lazily and then kept
def get_model():
global _model
if _model is None: # first request in this environment pays; later ones reuse it
_model = load_large_dependency("/opt/model.bin")
return _model
def handler(event, context):
user_id = event["user_id"] # per-request data stays local, never global
result = get_model().predict(event["features"])
return {"user_id": user_id, "score": result}
(load_large_dependency stands for whatever deserializes your dependency.)
Rule of thumb: if every request needs the dependency, load it at module scope so it happens during Init (with provisioned concurrency or SnapStart that means before any user waits). If only some code paths need it, load it lazily as above so the paths that don't need it get a fast cold start.
Worked example: why placement matters
"At module scope" below covers both patterns shown above: loading eagerly when the module is first imported, and loading lazily into a global on first use, the way get_model does. Either way the expensive work runs exactly once per environment, during whichever request first triggers it; only the code path differs.
Loading the dependency takes 1,200 ms; the rest of the handler takes 40 ms. Suppose each environment serves 500 requests before it is recycled.
- At module scope: one request in 500 pays 1,200 ms extra. Averaged, that is 1,200 / 500 = 2.4 ms per request, and 499 of 500 requests take about 40 ms.
- Inside the handler: every request takes 1,200 + 40 = 1,240 ms, 31 times slower, and you pay for 1,240 ms of duration on every call instead of 40 ms.
The cold request still takes about 1,240 ms either way; module placement just stops you paying that cost 500 times.
Pitfalls
- Per-request data in globals leaks between requests. A global
current_userset in one invocation is still there in the next. Keep request data local. - Frozen connections go stale. A database connection opened at Init may be dropped by the server while the environment is frozen. Reuse it, but reconnect on error.
- Hitting the 10-second Init cap turns a slow Init into a retry inside the first invocation, which then pays Init plus handler against the function timeout. If Init is near 10 s, shrink it or pre-initialize.
- Snapshot-based start (SnapStart) restores many environments from one snapshot, so anything "unique" created at Init (random seeds, unique IDs, temporary credentials) is shared by every restored copy. Generate those in the handler or in an after-restore hook (a callback that runs once for each newly restored environment, immediately after SnapStart restores it from the snapshot, the intended place for values that must be unique per environment).
- Don't assume the environment persists. Treat globals and
/tmpas a best-effort cache that can vanish at any time.
What event-driven design patterns are commonly used in serverless architectures? Walk through a concrete example: a pipeline that needs to kick off a downstream job whenever a new file lands in object storage. What components and events would you wire together, and how would you make sure the trigger is reliable and doesn't fire the job twice for the same file?
Sample Answer
Direct answer
Serverless systems are usually built by wiring managed services together with events, not by writing servers that poll. The common patterns are:
- event notification (a service announces "something happened")
- queue-based load leveling (a queue sits between producer and consumer)
- publish/subscribe fan-out (one event, many independent consumers)
- orchestration (a workflow engine drives the steps)
- the claim-check pattern (pass a pointer to large data, not the data)
- dead-letter handling (failures go somewhere you can see them)
For "a file lands, so run a job" I would wire it like this:
- The bucket emits an Object Created event to an event router (Amazon EventBridge, a managed service that receives events from many sources and routes each one to whichever targets match its filtering rules).
- A rule filtered on the input prefix (the folder-like portion of the object key that events are matched against, such as
incoming/) sends it to a queue. - A small function starts a workflow (Step Functions Standard, one of two execution modes: Standard keeps a full execution history and can run for up to a year; Express, mentioned below, is cheaper and higher-throughput but keeps no long history, and suits short executions better) whose name is derived from the object's identity.
- The workflow runs the job.
Every hop is at-least-once (each event may be delivered more than once, though never fewer), so reliability comes from queues with dead-letter queues and alarms. "Not twice" comes from a deterministic execution name. A second start with the same name does not start a second job.
The patterns, briefly
| Pattern | What it is | Use it when |
|---|---|---|
| Event notification | A service emits "this happened" (object created, row changed) | Something should react to a change without the producer knowing who |
| Queue-based load leveling | A queue between producer and consumer | The consumer is slower, rate-limited or sometimes down |
| Pub/sub fan-out | One event delivered to many independent consumers (an Amazon SNS, Simple Notification Service, topic; EventBridge rule targets) | Several teams react to the same fact |
| Orchestration | A workflow engine calls the steps and holds the state | Multi-step jobs with retries, waits and branching |
| Choreography | Each service reacts to the previous one's events; no central controller | Loosely coupled, short chains |
| Claim check | Put the large payload in object storage; pass only its location | Payloads bigger than event or message limits |
| Dead-letter queue (DLQ) | Where messages go after repeated failures | Always, on every async hop |
The pipeline
flowchart LR
up[Upload to incoming/] --> bucket[(Object storage bucket)]
bucket -->|Object Created event| router[EventBridge rule: prefix incoming/]
router --> q[Queue]
q --> starter[Starter function]
starter -->|StartExecution, deterministic name| wf[Workflow: Step Functions Standard]
wf --> job[Batch or data-processing job]
wf --> done[Completion event]
q -.->|after 5 failures| dlq[DLQ + alarm]
- Why EventBridge rather than a direct bucket-to-function trigger. Rules can filter on prefix and suffix, send one event to several targets, and archive and replay events. A direct S3-to-Lambda notification also works, but it is an asynchronous invoke (Lambda queues the event internally and retries it on failure without the caller waiting for a response) with Lambda's own retry queue (a separate, less visible retry mechanism than a queue you configure and can alarm on yourself), and you get fewer controls.
- Why a queue before the starter. The queue gives a buffer, a retry policy you control, a DLQ, and a visible metric (age of oldest message) to alarm on.
- Why a workflow rather than running the job inside the function. A Lambda invocation lasts at most 15 minutes. A Standard workflow can wait on a job for far longer, and it records every step, so retries and failures are visible.
- Multipart uploads (large files uploaded to object storage in separate chunks that are only assembled into the final object once every part has arrived) emit one event, when the upload completes, so the job never sees a half-written file.
Making the trigger reliable
- Assume duplicates and delays. S3 documents its event notifications as delivered at least once, usually within seconds but sometimes a minute or longer. The event router and the queue are also at-least-once.
- Every async hop gets a DLQ and an alarm. Alarm on DLQ depth above 0, and on the age of the oldest message in the main queue.
- Reconcile. A scheduled sweep compares objects under
incoming/with the set of files the workflow has processed. It re-triggers anything missing. This catches the rare lost event, a misconfigured rule, or an outage longer than the retry windows. - Avoid recursion. If the job writes output back into the same bucket, write it under a different prefix (or bucket) than the rule listens on. Otherwise every output file triggers another job.
Making sure the job fires once per file
Derive the workflow's execution name from the object's identity: bucket + key + version id (enable versioning on the bucket first: with it on, every overwrite of the same key is kept as a separate, uniquely identified version instead of replacing the object in place, and it is that per-write version id, not the key alone, that changes on a genuine re-upload). For a Standard workflow, a second StartExecution (the API call that starts a workflow execution) with the same name and input returns the existing execution while it is running, and returns ExecutionAlreadyExists once it has closed. Either way, no second job starts. Names can be reused 90 days after an execution closes.
import hashlib
def execution_name(bucket, key, version_id):
# Same object version -> same name; a re-upload (new version) -> new name.
digest = hashlib.sha256(f"{bucket}/{key}#{version_id}".encode()).hexdigest()
return f"ingest-{digest[:40]}" # 47 chars, within the 80-char limit, no banned characters
class FakeStandardWorkflow:
"""Models documented StartExecution semantics for STANDARD workflows."""
def __init__(self):
self.executions = {} # name -> (input, status)
def start(self, name, payload):
if name in self.executions:
prev_input, status = self.executions[name]
if status == "RUNNING" and prev_input == payload:
return "same execution returned (idempotent)"
raise RuntimeError("ExecutionAlreadyExists")
self.executions[name] = (payload, "RUNNING")
return "started"
def handle(event, sfn):
d = event["detail"]
name = execution_name(d["bucket"]["name"], d["object"]["key"], d["object"]["version-id"])
payload = f'{d["bucket"]["name"]}/{d["object"]["key"]}'
try:
return name, sfn.start(name, payload)
except RuntimeError as e:
return name, f"{e}: already handled, acknowledge the message"
sfn = FakeStandardWorkflow()
evt = {"detail": {"bucket": {"name": "raw-landing"},
"object": {"key": "incoming/2026-09-27/orders.csv", "version-id": "v1"}}}
print(handle(evt, sfn)) # first delivery
print(handle(evt, sfn)[1]) # duplicate while running
sfn.executions[execution_name("raw-landing", "incoming/2026-09-27/orders.csv", "v1")] = (
"raw-landing/incoming/2026-09-27/orders.csv", "SUCCEEDED")
print(handle(evt, sfn)[1]) # duplicate after it finished
evt["detail"]["object"]["version-id"] = "v2"
print(handle(evt, sfn)[1]) # genuine re-upload
('ingest-f5772e2d0a15754e5cd838f6fdd74a26602f48ad', 'started')
same execution returned (idempotent)
ExecutionAlreadyExists: already handled, acknowledge the message
started
- Duplicate while the job is running: the same execution is returned.
- Duplicate after it finished:
ExecutionAlreadyExists, which the starter treats as "already handled" and acknowledges. - A genuine re-upload (new version id) gets a new name and correctly starts a new job.
Two edges to handle deliberately:
- A retry after a FAILED execution needs a new name (for example, append an attempt number after checking the old execution's status). Otherwise
ExecutionAlreadyExistsblocks the legitimate retry. - The job itself should also be idempotent. It writes its output to a deterministic path and overwrites, so a manual re-run can't double-count.
Pitfalls
- Hashing the event id instead of the object identity. Duplicates carry different event ids, so the dedupe never matches.
- Dropping the version id and deduping on key alone. A legitimate re-upload of
orders.csvwould be silently ignored. - No DLQ alarm. Failed files wait unseen until someone asks where the report is.
What does 'serverless' and Functions-as-a-Service (FaaS) mean in production? Compare FaaS to running the same workload as containers, covering lifecycle, typical billing model, and operational overhead. When is FaaS a good fit versus a poor one?
Sample Answer
Direct answer
"Serverless" means you give a cloud provider your code plus a rule for when to run it, and the provider owns the machines: provisioning, scaling, patching and idle capacity. FaaS (functions-as-a-service) is the most common form. You deploy one function (AWS Lambda, Azure Functions, Google Cloud Run functions, Cloudflare Workers), it runs when an event arrives (an HTTP request, a queue message, a file landing in storage), and you pay per request and per millisecond of running time, with zero cost while idle. Compared with running the same code as containers, FaaS trades control and steady-state cost efficiency for near-zero operations and pay-for-use billing. It fits spiky, event-driven, short tasks; it fits poorly for steady high-volume traffic, long jobs, and anything that needs a long-lived process.
A plain-language picture: containers are like leasing a car (you pay every month whether you drive or not, and you look after it); FaaS is like a taxi (you pay only for trips, someone else maintains it, but a lot of trips every day costs more than the lease, and sometimes you wait for one to arrive).
How FaaS and containers actually differ
| Dimension | FaaS (AWS Lambda as the example) | Containers (Kubernetes, Amazon ECS, Cloud Run services, Cloud Run's always-on container mode, distinct from the Cloud Run functions mentioned above) |
|---|---|---|
| Lifecycle | The platform creates an execution environment (a small isolated sandbox with your code loaded) when a request needs one. Creating it is the cold start. It is reused for later requests while "warm", frozen between requests, and destroyed whenever the platform decides (Lambda recycles environments every few hours even under steady traffic). One environment handles one request at a time. | You start long-lived processes that run until you stop them. You choose how many replicas run and when to add more (autoscaling rules). One process usually serves many requests concurrently. |
| Billing | Per request plus duration in GB-seconds (memory configured in GB multiplied by seconds of run time), measured to 1 ms. Lambda in US East (N. Virginia), x86: $0.20 per million requests and $0.0000166667 per GB-second. Idle costs nothing. | Per vCPU-hour (one virtual CPU core running for one hour) and GB-hour of whatever you provisioned, busy or idle. You usually need at least two replicas for availability, so there is a cost floor. |
| Operational overhead | No servers, OS patching, cluster upgrades or capacity planning. You still own: code, permissions (a least-privilege IAM role, where IAM is AWS Identity and Access Management, per function), timeouts, concurrency limits, retries, logs and metrics. | You own image patching, cluster and node management (less on managed options such as AWS Fargate, which runs containers without you managing servers), health checks, rollout strategy and scaling policy. |
| Hard limits | Lambda: 15-minute maximum run time, 128 MB to 10,240 MB memory, 6 MB request and 6 MB response payload for synchronous calls, 250 MB unzipped package (10 GB as a container image), 1,000 concurrent executions per Region by default (raisable). | Effectively your cluster's size. Jobs can run for days; processes can hold WebSocket connections open (a WebSocket is a persistent, two-way network connection that stays open between messages, unlike a normal request/response HTTP call). |
Worked example: where the cost lines cross
An HTTP API whose handler takes 100 ms on average with 512 MB (0.5 GB) of memory. A 30-day month has 2,592,000 seconds. Cost per month at a steady rate of r requests per second:
cost(r)=r×2,592,000×(106$0.20+0.1s×0.5GB×$0.0000166667)| Steady load | Requests / month | Request charge | GB-seconds | Duration charge | Total |
|---|---|---|---|---|---|
| 1 req/s | 2,592,000 | $0.52 | 129,600 | $2.16 | $2.68 |
| 50 req/s | 129,600,000 | $25.92 | 6,480,000 | $108.00 | $133.92 |
So every 1 request/second of sustained load costs about $2.68 a month on Lambda, and the bill scales linearly. Now suppose (an assumed figure; substitute your real quote) a pair of small always-on containers that can comfortably serve 50 req/s costs $30 a month. The break-even is $30 / $2.68 per req/s, about 11.2 req/s sustained. Below that, FaaS is cheaper and you also skip the operations work; well above it, the containers win on cost. (This ignores the Lambda free tier of 1 million requests and 400,000 GB-seconds a month, and extras common to both, such as the API gateway, the managed service that receives HTTP requests and routes them to your function, billed per request, and logging charges.)
Most real traffic is not flat: an internal tool busy 2 hours a day and idle 22 costs FaaS almost nothing during the idle hours, while the containers bill all 24. That idle ratio, more than the peak rate, is what usually decides it.
When FaaS is a good fit versus a poor one
Good fit
- Event glue: react to an uploaded file, a queue message, a database change stream, a schedule (a nightly report), or a database change stream (a feed of row-level insert, update and delete events a database emits as they happen).
- Spiky or unpredictable traffic with long idle periods, where paying for idle replicas is waste.
- Low-to-moderate volume APIs where a few hundred ms of occasional cold-start latency is acceptable.
- Small teams that would rather not run a cluster.
Poor fit
- Steady, high-volume traffic above the break-even: you pay a premium for elasticity you are not using.
- Work longer than 15 minutes, or that needs a long-lived process (WebSocket servers, streaming consumers holding state, in-memory caches you rely on).
- Strict tail-latency targets where a cold start in the p99 (the 99th-percentile latency: the value only 1% of requests exceed) breaks the SLO (service-level objective), unless you pay to keep environments warm.
- GPU work, or large in-memory datasets that every environment would load separately.
My default: start event-driven and low-traffic workloads on FaaS, and move a component to containers when its measured sustained load passes the break-even, it hits a hard limit, or cold starts break its latency target.
Trade-offs and pitfalls
- "Serverless" still has servers, you just do not manage them. You gain speed and lose knobs: no choosing the OS, limited control over networking, CPU tied to the memory setting.
- Scaling can hurt what sits behind you. 1,000 concurrent functions can mean 1,000 database connections, and most relational databases cap total connections in the low hundreds (each one holds memory and overhead on the database server), so that alone can take the database down before it ever drops a request for load reasons. Relational databases need a connection proxy (a lightweight service that sits between many function instances and the database, holding a small pool of real database connections open and multiplexing many callers onto them) or a concurrency cap on the function (a hard ceiling on how many copies run at once, so the connection count never exceeds what the database can hold).
- Retries are part of the model. Asynchronous and queue triggers deliver at least once (a message may arrive more than once), so handlers must be idempotent: running twice has the same effect as once.
- Hidden line items: API gateway fees, log ingestion, NAT gateway (network address translation gateway: the managed component that lets resources inside a private network reach the internet, billed per hour and per GB) traffic for functions inside a private network. Price the whole path, not just the function.
- Vendor lock-in comes mostly from the triggers, permissions and managed services around the function, not the function code. Keeping business logic in plain modules the handler calls keeps a later move to containers cheap.
What security best practices would you apply to a serverless function that handles sensitive data? Think about execution-role design, how secrets get to the function, network placement, and what you log, and don't log. What's different about the blast radius here compared to a traditional always-on server?
Sample Answer
Direct answer
Give each function its own narrowly scoped identity, deliver secrets at runtime from a secrets store (never baked into code or plain environment variables), put the function inside a private network only when it must reach private resources, and treat logs as a place sensitive data must never land. The blast radius (how much an attacker can reach if one component is compromised) is smaller per unit than an always-on server because each function has its own short-lived credentials and no long-lived host, but it is wider in count: a serverless app is dozens of functions, each an entry point with its own permissions to get wrong.
The four controls, one at a time
1. Execution-role design (least privilege per function)
On AWS Lambda the execution role is the IAM (AWS Identity and Access Management) role the function assumes when it runs; its temporary credentials are what your code uses to call other services.
- One role per function, not one role per app. A
get-patient-recordfunction needsdynamodb:GetItemon one table. It should not inherit thes3:PutObjectthat the export function needs. - Scope to resource ARNs (Amazon Resource Names) and actions, never
*. Add conditions where they exist (for example, restrict KMS, AWS Key Management Service, decrypt to calls made through a specific service). - Separate the invoke side too. The function's resource-based policy says who may invoke it. Lock it to the specific API gateway route (one HTTP method and path exposed by the managed service that turns HTTP requests into invocations) or queue that triggers it, so nobody else in the account can call it directly with crafted input.
2. How secrets reach the function
- Store database passwords and API keys in a secrets manager (AWS Secrets Manager, Azure Key Vault, Google Secret Manager). Grant the role read access to only that secret.
- Fetch at runtime and cache briefly. On Lambda, the AWS Parameters and Secrets Lambda Extension serves secrets from a local cache over
localhost:2773; its default cache TTL (time-to-live) is 300 seconds, adjustable withSECRETS_MANAGER_TTL. That keeps per-invocation latency and API cost down while still picking up rotations within minutes. - Why not environment variables? Lambda encrypts them at rest with KMS (AWS Key Management Service), but anyone with permission to read the function's configuration sees them in plaintext, they show up in infrastructure-as-code diffs (the reviewable, version-controlled change files that a tool like Terraform or CloudFormation generates, often posted in a pull request for anyone on the review to read), and they cannot rotate without a redeploy. Use them for non-secret configuration such as the name of the secret.
3. Network placement
- A function that only calls managed APIs (object storage, a queue, a key-value store over its public endpoint with IAM auth) does not need to be in a VPC (Virtual Private Cloud, your private network in the cloud). Putting it there adds configuration without adding protection.
- A function that talks to a private database must be attached to the VPC in private subnets (network segments with no direct route to the public internet), with a security group (a stateful firewall attached to the function's network interface, allowing only the traffic you list) that allows only the database port. Reach other AWS services through VPC endpoints (private connections to AWS APIs) rather than a NAT gateway (network address translation gateway, which gives private subnets outbound internet access), and restrict egress (outbound traffic leaving the network) so compromised code cannot exfiltrate (quietly send stolen data out to an attacker) to arbitrary internet hosts.
4. What you log, and what you never log
| Log | Never log |
|---|---|
| Request ID, trace ID, function version | Raw request bodies containing personal or payment data |
| Outcome, latency, error class | Secrets, tokens, Authorization headers |
| Hashed or tokenized user identifiers | The full event object "for debugging" |
A hashed identifier is a one-way scramble that cannot be reversed back to the original value; a tokenized identifier swaps the real value for a reference id that is meaningless without a separate, tightly controlled lookup table. Either lets you correlate one user's events across logs without the logs themselves holding personal data.
A common leak is print(event) left in from development: on an API-triggered function the event includes headers and body. Use structured logging with an allow-list of fields, and add a log-side masking policy (CloudWatch Logs data protection policies can detect and mask patterns such as card numbers) as a second net, not the first.
Worked example
A claims-processing function reads a claim record, calls a fraud-scoring API, and writes a decision.
- Role:
dynamodb:GetItemanddynamodb:UpdateItemonarn:...:table/claims,secretsmanager:GetSecretValueon the one fraud-API key secret,kms:Decrypton the table's key (DynamoDB tables can be encrypted at rest with a customer-managed KMS key instead of the AWS-owned default; when they are, reading or writing items needs decrypt or encrypt permission on that specific key too). Nothing else. - Secret: fetched via the extension at invoke time, cached up to 300 s; rotation monthly.
- Network: no VPC, because both the table and the fraud API are reached over authenticated public endpoints. If the claims store moved to a private relational database, the function would move into private subnets with a VPC endpoint for Secrets Manager.
- Logs:
claim_id_hash,decision,fraud_score_bucket,latency_ms. The claimant's name and bank details never appear.
Blast radius: serverless versus an always-on server
| Dimension | Always-on server | Serverless function |
|---|---|---|
| Credentials | One host role shared by every app and cron job on the box | One role per function, temporary credentials expiring on their own |
| Persistence for an attacker | Can install a backdoor and wait | Environment is recycled; no host to persist on |
| What one exploit reaches | Everything the host role can reach, plus local files and neighbours | Only what that function's role allows |
| Number of entry points | A few | Many: every trigger (HTTP route, queue, bucket event) is one |
The honest caveats that make this a senior answer:
- Credentials are still stealable while the environment is alive. The execution role's temporary credentials are exposed to the runtime as environment variables, which means any code running inside that process, including a compromised dependency, can read them simply by reading its own process environment; nothing stops it. A dependency with remote code execution (a bug that lets an attacker run arbitrary code inside your process, for example through unsafe deserialization) or a server-side request forgery bug (a flaw that tricks the server into making an HTTP request of the attacker's choosing, for example to an internal endpoint that hands back these same credentials) can read and use them until they expire. Least privilege is what bounds the damage, not the ephemerality.
- Warm environments are reused. Globals and files in
/tmpsurvive between invocations on the same environment. Never cache one caller's sensitive data in a global or/tmpwhere the next request could read it. - Event injection is the new input surface. A function triggered by a file upload or queue message must validate that payload as strictly as an HTTP body.
Pitfalls
- One shared "lambda-role" with
AdministratorAccessbecause it was faster during a prototype. - Secrets in environment variables "because they are encrypted".
- Putting every function in a VPC by default, then opening a NAT gateway to the whole internet so they can reach public APIs.
- Logging the full event, which quietly turns the log store into the largest sensitive-data store in the account.
Unlock Full Question Bank
Get access to all 24 Serverless and Function-as-a-Service Architecture interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.