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.
You're deploying a function that reads an object from cloud storage, looks up data in a managed key-value store, and pulls a credential from a secrets service. Design a least-privilege IAM policy for it: how would you structure the roles and permission boundaries? Separately, how would you handle secret rotation and caching so you're not paying a cold-start latency penalty on every credential fetch, without compromising security?
Sample Answer
Direct answer
Give the function its own execution role (the IAM role it runs as, where IAM is AWS Identity and Access Management). That role allows exactly four things:
- read objects under one Amazon S3 (object storage) bucket prefix
- read items from one table
- read one secret
- decrypt with that secret's KMS (AWS Key Management Service) key, and only when the request comes through Secrets Manager. Secrets Manager encrypts every secret at rest with a KMS key, so even though the code only calls
secretsmanager:GetSecretValue, Secrets Manager in turn needs the caller allowed to decrypt with that key, or the call fails
Scope each permission to a specific resource ARN (Amazon Resource Name, the unique id of an AWS resource), not *. Wrap every role your deployment pipeline creates in a permissions boundary: a ceiling policy attached to the role that caps what it can ever be granted, so even a mistaken policy attached later still cannot grant more than the ceiling allows.
For secrets, fetch once per execution environment (the sandboxed instance of your function that a cold start creates, and that later requests reuse while it stays warm) and cache in memory with a short TTL (time-to-live), either through the Lambda secrets extension or a library cache. That way warm invocations (requests that land on an already-running environment instead of triggering a new cold start) never pay for a fetch. Make rotation safe for cached copies by using the alternating-users rotation strategy plus refresh-on-authentication-failure.
Structuring the roles
An identity policy is attached to a principal, here the function's role, and says what that principal may call. A resource-based policy is attached to the resource itself, here the function, the secret, or the KMS key, and says who may reach that resource. A call is only allowed when both sides agree.
| Piece | Controls | For this function |
|---|---|---|
| Execution role (identity policy) | What the function may call | The four statements below, plus writing to its own log group |
| Function resource-based policy | Who may invoke the function | Only the specific bucket notification or API that triggers it |
| Permissions boundary | The maximum the execution role can ever have | Allows only S3, DynamoDB, Secrets Manager, KMS and CloudWatch Logs actions on this app's resources. Denies all iam:* |
| Deployment role (the CI, continuous integration, pipeline) | Who may create or alter roles | May create roles only if the boundary is attached, enforced with a condition key (an extra clause on a permission, here iam:PermissionsBoundary, that must also hold for the action to be allowed), and may iam:PassRole only for roles under this app's path. Passing a role means handing a role to an AWS service so it can act as that role; a deployer needs it to attach the execution role to the function it creates, and it is restricted so the deployer cannot hand out a more powerful role than this app is meant to have |
| Resource policies on the other side | Defense in depth (stacking independent controls so that if one fails or is misconfigured, another still stops the request) | The secret's resource policy and the KMS key policy name this role; the bucket policy restricts the prefix |
Effective permission is the intersection of the identity policy, the boundary, and any organization-level service control policies (guardrails set above the account, by the AWS Organization, that cap what any role in the account can ever do no matter what its own policy allows). An explicit deny anywhere wins.
(Each statement below has a Sid, a statement id: just a human-readable label. AWS ignores it when deciding access; only Effect, Action, Resource and Condition do.)
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "ReadInputObjects",
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::orders-input/incoming/*"
},
{
"Sid": "ReadCustomerLookupTable",
"Effect": "Allow",
"Action": ["dynamodb:GetItem", "dynamodb:BatchGetItem"],
"Resource": "arn:aws:dynamodb:us-east-1:111122223333:table/customer-lookup"
},
{
"Sid": "ReadOnePartnerCredential",
"Effect": "Allow",
"Action": "secretsmanager:GetSecretValue",
"Resource": "arn:aws:secretsmanager:us-east-1:111122223333:secret:prod/order-enricher/partner-api-??????"
},
{
"Sid": "DecryptOnlyViaSecretsManager",
"Effect": "Allow",
"Action": "kms:Decrypt",
"Resource": "arn:aws:kms:us-east-1:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab",
"Condition": {
"StringEquals": { "kms:ViaService": "secretsmanager.us-east-1.amazonaws.com" }
}
}
]
}
Details that separate a real least-privilege policy from a plausible one:
- Read-only verbs. A verb is IAM's term for the action itself, the part of the permission that says what you may do, as opposed to the resource it applies to. No
PutObject,PutItemorScan.GetItemandBatchGetItemcover key lookups. AddQueryonly if the code does range reads. - Secret ARN ends in
-??????. Secrets Manager appends six random characters to secret ARNs.??????matches exactly those six and nothing longer, while a*would also matchpartner-api-admin-.... kms:ViaServicemeans the function can use the key only through Secrets Manager, not decrypt arbitrary data with it. If the bucket uses SSE-KMS (server-side encryption with a KMS key), add a second decrypt statement scoped to S3.- Logs: the basic execution permissions, scoped to this function's log group. A function inside a VPC (Virtual Private Cloud, a private network) also needs the network-interface permissions.
- Multi-tenant tables: add the
dynamodb:LeadingKeyscondition (a restriction on the table's partition key, the attribute DynamoDB uses to decide which physical partition an item lives on and the first part of every lookup) so the role can only read partition keys belonging to the caller's tenant. - Checking for unused grants: generate a policy from recorded CloudTrail (AWS's API audit log) activity with IAM Access Analyzer. Its unused-access findings flag permissions the function has but never uses.
Secret caching without the cold-start penalty
Where the cost comes from. Calling Secrets Manager inside the handler adds a network round trip to every invocation and an API charge per call. The fix is to fetch once per execution environment and reuse the value across warm invocations.
Two supported ways to do it:
- The AWS Parameters and Secrets Lambda Extension, added as a layer (a packaged bundle of code or binaries a function attaches without bundling it into its own deployment package). The function calls
http://localhost:2773/secretsmanager/get?secretId=...with the headerX-Aws-Parameters-Secrets-Tokenset to the function's session token (the temporary credential Lambda issues alongside the execution role's access key, proving to the local extension that the caller really is this running function). It caches for 300 s by default (configurable 0 to 300 s throughSECRETS_MANAGER_TTL), holding up to 1,000 secrets. - Powertools for AWS Lambda parameters with a
max_age. Or a small module-level cache of{value, fetched_at}.
When the fetch happens. Pre-warmed environments (provisioned concurrency) run init code before any request, so fetching at init moves the cost off the request path entirely. With snapshot restore (SnapStart), anything fetched during init is baked into the snapshot and shared by every restored environment. So fetch after restore, not during init.
Never put the secret in an environment variable (readable by anyone with lambda:GetFunctionConfiguration), in /tmp, or in logs. Note that AWS's own sample code prints the retrieved secret. Remove that line.
Cost:
price_per_call = 0.05 / 10_000 # Secrets Manager API calls, USD
invocations_per_s, envs, ttl_s = 200, 50, 300
month_s = 30 * 24 * 3600
no_cache = invocations_per_s * month_s
cached = envs * (month_s / ttl_s) # worst case: every environment refreshes every TTL
print(f"fetch per invocation: {no_cache:,.0f} calls/month = ${no_cache * price_per_call:,.2f}")
print(f"cache per environment, {ttl_s} s TTL, {envs} environments: {cached:,.0f} calls/month = ${cached * price_per_call:,.2f}")
fetch per invocation: 518,400,000 calls/month = $2,592.00
cache per environment, 300 s TTL, 50 environments: 432,000 calls/month = $2.16
At 200 invocations per second, fetching per invocation costs about $2,592 a month in API calls alone (plus the latency). Caching per environment with a 300 s TTL, even assuming all 50 environments refresh every 5 minutes, costs $2.16.
Rotation that is safe for cached values
Secrets Manager rotation moves three staging labels between versions of the secret: AWSCURRENT marks the version callers get by default, AWSPENDING marks the new version created for an in-progress rotation and not yet promoted, and AWSPREVIOUS marks the version that was AWSCURRENT immediately before the last rotation.
- Single-user rotation changes the password of the one database user in place. Every environment holding the old value in its cache then fails authentication for up to one TTL (up to 5 minutes).
- Alternating-users rotation keeps two users. Rotation changes the password of the inactive user and then makes it
AWSCURRENT. The previous credential stays valid until the next rotation, so cached copies keep working. Use this. - Refresh on authentication failure: if a call fails with an auth error, bypass the cache (for example Powertools'
force_fetch=True, or a direct SDK call), fetchAWSCURRENTagain, and retry once. - TTL choice: with alternating users, the TTL no longer has to be short for rotation's sake. It is bounded by how quickly you must stop using a compromised secret. For an emergency revoke, rotate and then publish a new function version or move an alias (a named, mutable pointer to one specific version, used so callers reference a stable name while the version behind it changes) to recycle the environments: pointing callers at a new version or alias forces Lambda to start fresh execution environments for it rather than reuse existing warm ones, so any environment still holding the old cached secret in memory simply stops receiving traffic, rather than waiting out the cache TTL.
Pitfalls
- One shared role for "all the app's functions". One compromised function gets every permission.
secretsmanager:GetSecretValueon*, orkms:Decryptwith no conditions.- Caching forever with no TTL, combined with single-user rotation: an outage every rotation.
- Fetching during snapshot init, or logging the secret "just for debugging".
A serverless function has intermittent cold-start latency spikes that are hurting your p99. Name three practical strategies to reduce cold-start latency, and for each one explain the mechanism by which it helps and its trade-offs in cost, complexity, or effectiveness.
Sample Answer
Direct answer
First confirm the spikes really are cold starts: compare p99 (the 99th-percentile latency, the value only 1% of requests exceed) for invocations whose logs carry an Init Duration against those that don't. If they are, three practical strategies, from cheapest to most expensive: (1) make initialization cheaper (smaller package, fewer and lazier imports, more memory for more CPU); (2) restore from a snapshot instead of initializing (AWS Lambda SnapStart); (3) pre-initialize environments so users never hit a cold one (provisioned concurrency, or minimum instances on other platforms). Do (1) always, then pick (2) or (3) based on runtime support and how strict the latency target is.
Why cold starts land exactly in p99
AWS reports cold starts are typically under 1% of invocations. p99 is the boundary of the slowest 1%. If 0.5% of requests are cold, the slowest 1% is half cold and half slow-warm, and p99 sits at the edge of the warm tail. If 1.5% are cold (low traffic, frequent deploys, bursts that force new environments), the p99 value itself is a cold request. A modest rise in cold-start rate can therefore move p99 from roughly "slow warm request" to "full cold start". This is why the fix list starts with cutting the cold-start cost, and why reducing how often they happen also counts.
Strategy 1: make initialization cheaper
Mechanism. Cold-start time is roughly code download + runtime start + your init code. Shrinking any term shrinks the spike.
- Import only what you use (a single SDK service client rather than the whole SDK); remove unused dependencies, test fixtures and docs from the package.
- Lazy-load heavy objects needed only on some code paths.
- Raise memory: Lambda allocates CPU in proportion to memory (1,769 MB equals one full vCPU, one virtual CPU core, a unit of allocated compute), so CPU-bound init (parsing, class loading, JIT warm-up, where JIT is just-in-time compilation of hot code) runs faster.
Trade-offs.
| Cost | Complexity | Effectiveness |
|---|---|---|
| Free to cheap. More memory costs more per millisecond, but if run time falls in proportion the cost per call is roughly unchanged. | Low; ordinary engineering. Lazy loading moves some delay to the first request that needs it. | Helps every cold start and every runtime. Bounded: you cannot optimize below runtime start-up plus unavoidable work. |
Strategy 2: snapshot restore (Lambda SnapStart)
Mechanism. When you publish a function version, Lambda runs Init once, takes a snapshot of the initialized environment's memory and disk (a Firecracker microVM snapshot, Firecracker being the lightweight virtual machine technology Lambda runs on), and caches it. New environments resume from the snapshot instead of re-running Init.
Trade-offs.
| Cost | Complexity | Effectiveness |
|---|---|---|
| No extra charge on Java. On Python and .NET you pay a snapshot caching charge per published version (minimum 3 hours) plus a restore charge each time an environment is restored. | Moderate. Supported only on Java 11+, Python 3.12+ and .NET 8+, on published versions (numbered, immutable snapshots of your code and configuration), not on $LATEST (the mutable pointer that always reflects whatever you deployed most recently). Not combinable with provisioned concurrency, Amazon EFS (Elastic File System, a network filesystem) mounts (attaching that shared filesystem to the environment), or more than 512 MB of /tmp. Anything unique created at Init (random seeds, IDs, credentials) is duplicated across every restored copy and must be regenerated after restore; network connections may need re-establishing. | Large for heavy-init runtimes (JVM, Java Virtual Machine, the runtime Java code executes in, start-up; big framework loads). AWS notes it works best at scale; rarely invoked functions benefit less. Restores are faster than a full Init but not free. |
Strategy 3: pre-initialized capacity (provisioned concurrency)
Mechanism. You tell Lambda to keep N environments initialized for a version or alias at all times. Requests up to N concurrent never see a cold start; above N, they spill over (run on ordinary on-demand environments instead of the pre-warmed ones) to normal on-demand environments (and can be cold). The equivalents elsewhere are minimum instances on Google Cloud Run and always-ready instances on Azure Functions.
Trade-offs, with numbers. Price in US East (N. Virginia): $0.0000041667 per GB-second for keeping capacity provisioned, and duration drops to $0.0000097222 per GB-second (from $0.0000166667) for work that runs on it.
- 10 environments at 1 GB for a 30-day month: 10 GB x 2,592,000 s = 25,920,000 GB-s x $0.0000041667 = $108.00 per month, even with no traffic.
- If those environments serve 5 million requests of 80 ms at 1 GB (400,000 GB-s), duration costs $3.89 instead of $6.67 on-demand. The $108 floor dominates unless utilization is high.
| Cost | Complexity | Effectiveness |
|---|---|---|
| A 24/7 floor you pay whether used or not. | Needs published versions and aliases (an alias is a named pointer such as live to one version); you must size N and ideally scale it on a schedule or on utilization (Application Auto Scaling, the AWS service that scales non-server resources, can change N on a schedule or on utilization). Watch ProvisionedConcurrencySpilloverInvocations to see when you are under-provisioned. | The strongest: cold starts disappear up to N. Does not help bursts above N. |
Worked example: choosing
A checkout API on Node.js with a 250 ms p50 (median latency: half of requests finish faster than this) and 1.8 s p99, 40 requests/s in business hours, 2 requests/s at night; cold-starting requests show ~1.5 s Init Duration.
- Trim the bundle and replace a whole-SDK import with single clients:
Init Durationfalls from ~1.5 s to, say, ~600 ms (measure it; don't assume). - SnapStart is not available for Node.js, so for the remaining spikes use provisioned concurrency. By Little's law (concurrency equals arrival rate times how long each request takes; here the 250 ms p50 stands in for that per-request time), 40 req/s x 0.25 s means about 10 requests are in flight at once, so provision ~12 (headroom) during business hours via a schedule and ~2 at night. Priced at the same $0.0000041667 per GB-second as above (1 GB, roughly 12 business hours and 12 night hours a day): 12 environments busy 12 h/day plus 2 environments the other 12 h/day, over a 30-day month, is about $75.60/month, cheaper than holding a flat 10 environments 24/7 ($108, from the pricing above) precisely because it drops to 2 overnight.
- Re-check p99 and the spillover metric after a week.
Pitfalls
- "Keep-warm" pings (a scheduled event calling the function every few minutes) keep one environment warm. A burst that needs 20 environments still cold-starts 19. Provisioned concurrency is the supported version of this idea.
- Blaming cold starts for everything. Slow downstream calls, network set-up for functions attached to a VPC (Virtual Private Cloud, a private network), or large payloads also show up in p99. Split latency by cold versus warm before paying for a fix.
- Deploy frequency matters. Every deployment replaces all environments, so ten deploys a day means ten waves of cold starts.
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.
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.
Your team needs to pick a compute model for a platform with spiky, unpredictable traffic, and one concrete workload on the table is a CPU-bound, latency-sensitive job like image processing under strict SLAs. Compare serverless (FaaS) and managed Kubernetes across cost model (pay-per-use versus reserved), cold-start latency, burst concurrency, observability, vendor lock-in, and operational burden. Give a recommended phased roadmap, including migration considerations, for getting there.
Sample Answer
Direct answer
For a platform with spiky, unpredictable traffic, I would run the CPU-bound image-processing workload on serverless functions (FaaS) first, with a small amount of provisioned concurrency for the baseline, behind a queue wherever the SLA (service-level agreement) allows asynchronous processing. The reason is arithmetic: to meet a strict SLA through spikes on Kubernetes, you must keep peak capacity running or accept queueing while nodes boot, and at a 20x peak-to-baseline ratio that is roughly 7x the cost of the serverless option in the example below. I would plan the roadmap so the workload can move to managed Kubernetes when measured average utilization makes containers cheaper (about 48% on the prices below) or when a hard limit such as GPUs or 15-minute runtimes forces it.
Terms used throughout:
- FaaS (functions as a service): the provider runs your function on demand and bills per request and per GB-second (memory size times run time). AWS Lambda is the example.
- Managed Kubernetes: a cloud-run Kubernetes control plane (for example EKS, Amazon Elastic Kubernetes Service) that runs your containers as pods (one or more containers scheduled and scaled together) on servers (nodes) you pay for while they run; a pod autoscaler adds or removes pod copies to match load, and if no node has room, a cluster autoscaler adds or removes nodes themselves.
- Cold start: the delay when the platform creates a new execution environment (download code, start the runtime, run initialization) before it can serve a request.
- Provisioned concurrency: paying Lambda to keep a set number of environments initialized so those requests skip the cold start.
- p99: the 99th percentile latency, the time within which 99% of requests finish.
Assumptions for the worked example
| Input | Value |
|---|---|
| Work per image | 300 ms of CPU at 1 vCPU (assumed; measure it) |
| Baseline | 20 images/s |
| Spikes | 400 images/s, totalling 60 minutes a day, arriving unpredictably |
| SLA | p99 under 2 s per image for synchronous requests |
| Prices | AWS us-east-1 list prices: Lambda $0.0000166667 per GB-s, $0.20 per million requests; provisioned concurrency $0.0000041667 per GB-s allocated and $0.0000097222 per GB-s of duration; Fargate (AWS's serverless container runtime, billed per second for the vCPU and memory a container reserves) $0.000011244 per vCPU-second and $0.000001235 per GB-second |
Lambda allocates CPU in proportion to memory, reaching one full vCPU at 1,769 MB, so a CPU-bound function should be sized at 1,769 MB or more, not at the 128 MB default.
LAMBDA_GBS, LAMBDA_REQ = 0.0000166667, 0.20/1e6
PC_ALLOC, PC_DUR = 0.0000041667, 0.0000097222
FG_VCPU_S, FG_GB_S = 0.000011244, 0.000001235
SEC_MONTH = 730*3600
mem_gb = 1769/1024 # 1 vCPU equivalent
cpu_s = 0.300 # ASSUMED: 300 ms of CPU per image at 1 vCPU
baseline, spike, spike_min_per_day = 20, 400, 60 # img/s; spikes total 60 min/day
days = 730/24
imgs = (baseline*(24*60-spike_min_per_day)*60 + spike*spike_min_per_day*60)*days
avg_rate = imgs/SEC_MONTH
# Lambda on-demand only
lam = imgs*(cpu_s*mem_gb*LAMBDA_GBS + LAMBDA_REQ)
# Lambda with provisioned concurrency covering baseline (conc = rate*duration, +50%)
pc = int(round(baseline*cpu_s*1.5))
pc_alloc = pc*mem_gb*SEC_MONTH*PC_ALLOC
base_imgs = baseline*SEC_MONTH
pc_dur = base_imgs*cpu_s*mem_gb*PC_DUR
od_imgs = imgs-base_imgs
lam_pc = pc_alloc + pc_dur + od_imgs*cpu_s*mem_gb*LAMBDA_GBS + imgs*LAMBDA_REQ
print(f"images/month={imgs/1e6:.2f}M avg={avg_rate:.1f}/s peak concurrency={spike*cpu_s:.0f} vCPU")
print(f"Lambda on-demand: ${lam:,.0f}/month")
print(f"Lambda + {pc} provisioned envs for baseline: ${lam_pc:,.0f}/month")
def fargate(vcpus): return vcpus*(FG_VCPU_S+2*FG_GB_S)*SEC_MONTH
peak_vcpu = spike*cpu_s/0.7 # run at 70% target utilization
print(f"containers sized for peak ({peak_vcpu:.0f} vCPU always on): ${fargate(peak_vcpu):,.0f}/month")
avg_vcpu = avg_rate*cpu_s/0.7
print(f"containers if autoscaling were perfect ({avg_vcpu:.1f} vCPU avg): ${fargate(avg_vcpu):,.0f}/month")
lam_vcpu_s = mem_gb*LAMBDA_GBS
fg_vcpu_s = FG_VCPU_S+2*FG_GB_S
print(f"$ per busy vCPU-second: Lambda={lam_vcpu_s:.3e} Fargate(1vCPU,2GB)={fg_vcpu_s:.3e} ratio={lam_vcpu_s/fg_vcpu_s:.2f}")
print(f"containers win on compute price above {fg_vcpu_s/lam_vcpu_s:.0%} average utilization")
images/month=94.17M avg=35.8/s peak concurrency=120 vCPU
Lambda on-demand: $832/month
Lambda + 9 provisioned envs for baseline: $813/month
containers sized for peak (171 vCPU always on): $6,178/month
containers if autoscaling were perfect (15.4 vCPU avg): $553/month
$ per busy vCPU-second: Lambda=2.879e-05 Fargate(1vCPU,2GB)=1.371e-05 ratio=2.10
containers win on compute price above 48% average utilization
Reading those numbers before the takeaway: the provisioned count of 9 and the peak concurrency of 120 both come from the same idea (conc = rate x duration in the code). Keeping up with the 20 images/s baseline without queueing needs 20 x 0.3 s = 6 environments busy at once; add 50% headroom for the noise around that average and you provision 9 (pc). The 400 images/s spike needs 400 x 0.3 s = 120 concurrent environments to absorb instantly (peak concurrency=120 vCPU), and sizing containers for that peak at a 70% target utilization (headroom so a real traffic wobble does not immediately throttle) needs 120 / 0.7 ≈ 171 vCPU held always-on.
Provisioned concurrency has two prices, not one: a reservation rate ($0.0000041667/GB-s, PC_ALLOC) charged for every second an environment sits ready whether or not it is handling a request, and a lower execution rate ($0.0000097222/GB-s, PC_DUR, versus $0.0000166667 on-demand) charged only while it is actually running code, because you already paid to reserve it. The baseline's 52.56M images a month (base_imgs, 56% of the 94.17M total) run at that discounted execution rate, about $170 to hold 9 environments ready plus $265 while they are busy; every image above baseline (od_imgs, about 41.6M) still pays the full on-demand rate (about $359), plus the flat per-request fee on all 94.17M images (about $19). That totals the printed $813, a little under the $832 of running every image at the plain on-demand rate, because the discount on the baseline's share of images outweighs the cost of holding 9 environments ready around the clock.
Why 48%, specifically: Lambda's price per unit of actual work is fixed no matter how busy the account is, so its cost per busy vCPU-second is the constant $2.879e-05 printed above. A container's price is fixed per second it runs whether or not it has work, so its cost per unit of actual work falls as utilization rises, a container running at half utilization effectively pays double its sticker price for the work it does. Setting the container's cost per busy second at utilization U equal to Lambda's fixed rate gives the crossover:
U1.371×10−5=2.879×10−5⇒U=2.8791.371≈0.48Below about 48% utilization the container is paying for idle time Lambda never bills; above it, the container's busy-time price undercuts Lambda's fixed one.
Container cost is priced at Fargate (per-second container) rates for a like-for-like unit price; EC2 virtual-machine nodes under EKS would be somewhat cheaper per vCPU but add the $0.10/hour cluster fee and node management.
The key reading: the realistic Kubernetes number lies between $553 and $6,178, and where it lands depends on how much capacity you must hold warm to survive a spike you cannot predict. Scaling a Kubernetes deployment means the pod autoscaler adds pods, and if no node has room, the cluster autoscaler must launch new nodes, which takes time you must measure in your own environment. Unpredictable spikes of 20x therefore push you toward the $6,178 end. Serverless costs about $830 whichever way the spikes fall. Provisioned concurrency for the baseline is roughly cost-neutral here ($813 versus $832) because the baseline keeps those environments busy, and it removes cold starts from the steady part of the traffic.
Comparison across the six named dimensions
| Dimension | Serverless (FaaS) | Managed Kubernetes | Verdict for this workload |
|---|---|---|---|
| Cost model | Pay per use: per request plus per GB-second, zero when idle; about 2.1x the price of a busy container per vCPU-second | Reserved capacity: pay for nodes whether busy or not; cheaper per unit when utilization is high | FaaS while utilization is low and spiky; K8s above about 48% average utilization |
| Cold-start latency | New environments add latency, larger for big container images with native image libraries; provisioned concurrency removes it for the baseline | No per-request cold start, but new nodes take a long time to arrive during a spike | FaaS with provisioned baseline; spikes pay some cold starts, which the 2 s SLA must be tested against |
| Burst concurrency | Lambda scales each function by up to 1,000 new environments every 10 seconds, up to the account concurrency quota (default 1,000 per region, raisable) | Limited by spare node capacity and node-launch time | FaaS clearly: 120 concurrent at peak is far inside Lambda's limits |
| Observability | Per-invocation metrics and logs out of the box; distributed tracing needs instrumentation; no host to log into when debugging | Full control: Prometheus (an open-source metrics system) metrics, profilers, sidecars (helper containers running next to each service); you run the stack | K8s gives deeper profiling for CPU-bound tuning; FaaS is adequate with tracing added |
| Vendor lock-in | Triggers, event shapes, IAM (AWS Identity and Access Management) permissions and orchestration are provider-specific | Images and manifests are portable across clouds | K8s, but mitigable on FaaS by shipping the function as a container image with a thin handler |
| Operational burden | No nodes, patching or cluster upgrades | Cluster upgrades, node patching, autoscaler tuning, capacity planning | FaaS, unless a platform team already runs K8s |
Design specifics for the image workload on FaaS
- Pass references, not bytes. Clients upload to object storage (S3) with a pre-signed URL (a time-limited upload link that needs no credentials); the function receives the object key. Lambda's synchronous payload limit is 6 MB per request and response, too small for many images.
- Asynchronous by default. Where the product allows it, an upload event goes onto a queue (SQS, Amazon Simple Queue Service, AWS's managed message queue) that triggers the function; the queue absorbs spikes and a reserved-concurrency cap (a hard ceiling on how many concurrent environments this function may use, protecting shared account capacity and downstream systems from being overrun; distinct from provisioned concurrency, which keeps environments pre-warmed) protects anything downstream. Only truly interactive paths call synchronously.
- Deterministic output keys (for example
thumbnails/{image_id}/{size}.webp) so a retried event overwrites the same object instead of creating duplicates. - Memory sized for CPU: benchmark at 1,769 MB and above. Extra memory adds more vCPU, but only helps if the image library uses multiple threads.
- Container-image packaging with the native imaging library baked in; keep the image small because image size affects cold starts.
Phased roadmap
Assume the current state is image processing inside an existing monolith on virtual machines.
- Phase 0: measure (1-2 weeks). Instrument the current path: CPU time per image by size, image-size distribution, real peak-to-baseline ratio, and SLA misses. Replace my assumed 300 ms with the measured number and rerun the cost model.
- Phase 1: extract behind an interface. Put image processing behind an internal API and an upload event, with the business logic in a plain library that does not know whether it runs in Lambda or a container. This is the lock-in insurance.
- Phase 2: shadow, then canary, on FaaS. First shadow it: send a copy of production traffic to the function and compare outputs byte for byte and latency at p99, without serving its results to users. Then canary it: route 5%, 25%, 100% of real traffic, with a flag that routes back to the old path instantly. Load-test a synthetic 20x spike before 100%, including a cold-start-heavy run.
- Phase 3: harden. Provisioned concurrency sized to the measured baseline, reserved concurrency as a ceiling, a DLQ (dead-letter queue, where messages that fail repeatedly are parked for inspection) on the async path, alarms on throttles (invocations rejected because a concurrency limit was hit), errors, duration p99 and queue age (how long a message waits before being processed, a sign the consumer is falling behind).
- Phase 4: re-evaluate quarterly. Track average utilization (busy vCPU-seconds divided by provisioned vCPU-seconds had it run on containers). If it stays above roughly 50%, or the workload needs GPUs or more than 15 minutes per task, move it to managed Kubernetes. Because Phase 1 kept the logic in a portable container image, that move is a deployment change, not a rewrite.
Migration considerations: run old and new paths in parallel until output parity is proven; keep the old path deployable for rollback through at least one full traffic cycle (for example a month-end peak); make every processing step idempotent (running it twice has the same effect as running it once) so a replay during cut-over is harmless; and budget for the database or storage behind the function, which sees the same 20x spikes once the compute stops being the bottleneck.
Trade-offs and pitfalls
- Comparing FaaS with a perfectly autoscaled cluster. That comparison favors Kubernetes ($553 versus $832) but assumes capacity appears the instant a spike starts, which is the one thing unpredictable traffic denies you.
- Under-sizing Lambda memory for CPU-bound work. At low memory the function gets a fraction of a vCPU and runs proportionally slower, so it can cost about the same while blowing the SLA.
- Ignoring the 2.1x unit-price gap. It is why serverless is a phase for this workload's current traffic shape, not necessarily its permanent home.
- Choosing Kubernetes for portability alone when nobody on the team runs it. The operational burden is real on day one; lock-in cost is only paid if you actually move.
Unlock Full Question Bank
Get access to all 21 Serverless and Function-as-a-Service Architecture interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.