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.
A greenfield service needs to choose between serverless functions and containers managed by Kubernetes. What practical criteria would you use to decide: think about latency and cold starts, traffic pattern, cost model, operational overhead, vendor lock-in, and your team's existing skills. In what kind of scenario does one option clearly win?
Sample Answer
Direct answer
Default to serverless functions when traffic is low, bursty or unpredictable, the work is short and stateless, and the team has no Kubernetes platform already running. Default to Kubernetes-managed containers when traffic is steady and high, requests need consistently low latency, the work is long-running or needs special hardware, or the organization already operates a Kubernetes platform with people to run it. For a typical greenfield service with no existing platform, I would start serverless and write down the traffic level at which I would move.
Two terms first:
- Serverless functions (FaaS, functions as a service), for example AWS Lambda: you deploy a function; the provider starts copies on demand, scales them to zero when idle, and bills per request plus per millisecond of run time.
- Containers on Kubernetes: you package the service as a container image and Kubernetes (a container orchestrator: it runs your containers as pods, one or more containers scheduled and scaled together, on nodes, the physical or virtual machines that make up the cluster) keeps a chosen number of copies running on servers you pay for whether or not they are busy. On AWS the managed version is EKS (Amazon Elastic Kubernetes Service).
The criteria
| Criterion | Serverless functions | Kubernetes containers | Question to ask |
|---|---|---|---|
| Latency and cold starts | A cold start (booting a new function environment on first request or during scale-up) adds latency to some requests; mitigated by provisioned concurrency (paying to keep environments warm) | Pods are already running, so no per-request cold start; scaling up new pods and nodes is slower | Does the p99 (99th percentile) latency target tolerate an occasional slow request? |
| Traffic pattern | Scales to zero and up quickly; ideal for spiky or idle-most-of-the-day traffic | Needs capacity running for the baseline; autoscaling reacts more slowly | What is the ratio of peak to average traffic? |
| Cost model | Pay per request and per GB-second (memory allocated, in GB, times run time, in seconds; the unit Lambda's execution price is billed in); nothing when idle | Pay for provisioned capacity (servers kept running and billed 24x7, whether or not they are doing work) plus the cluster itself | What is the average utilization? |
| Operational overhead | No servers, OS patching or cluster upgrades | Cluster upgrades, node patching, autoscaler tuning, networking | Who will be on call for the platform? |
| Vendor lock-in | Handler signatures, event formats and triggers are provider-specific | Container images and Kubernetes manifests move between clouds fairly easily | How likely is a move, and what would it cost? |
| Team skills | Needs event-driven design (structuring the system around reacting to events rather than direct calls) skills and distributed tracing (following one request's path across multiple services to debug it) | Needs Kubernetes operations skills | What does the team already run well? |
Two hard limits also decide it on their own: AWS Lambda caps one invocation at 15 minutes and 10,240 MB of memory, and it has no GPUs. Work that exceeds those goes to containers.
Worked example: where the cost lines cross
Compare Lambda with one always-on container sized at 1 vCPU (one virtual CPU core, a unit of allocated compute) and 2 GB, using AWS us-east-1 list prices (Lambda $0.0000166667 per GB-second plus $0.20 per million requests; Fargate, AWS's serverless container runtime, $0.000011244 per vCPU-second and $0.000001235 per GB-second):
How to read the code before running it: LAMBDA_GBS/LAMBDA_REQ are Lambda's per-GB-second and per-request prices; FG_VCPU_S/FG_GB_S are Fargate's per-vCPU-second and per-GB-second prices; H = 730 is the average hours in a billing month, used to turn an hourly or per-second rate into a monthly one. per_req prices one 100 ms, 1 GB request: 0.1*1.0*LAMBDA_GBS is 100 ms (0.1 s) times 1 GB, i.e. 0.1 GB-seconds of execution, priced at LAMBDA_GBS, plus the flat LAMBDA_REQ per-request fee. The container's monthly price, task, sums its vCPU cost and its memory cost, each a rate times seconds in the month.
LAMBDA_GBS, LAMBDA_REQ = 0.0000166667, 0.20/1e6
FG_VCPU_S, FG_GB_S = 0.000011244, 0.000001235
H = 730
task = (1*FG_VCPU_S + 2*FG_GB_S) * 3600 * H
per_req = 0.1*1.0*LAMBDA_GBS + LAMBDA_REQ # 100 ms at 1 GB
print(f"1 vCPU/2 GB Fargate task 24x7: ${task:.2f}/month")
print(f"Lambda per request (100 ms, 1 GB): ${per_req:.8f}")
be = task/per_req
print(f"breakeven: {be/1e6:.1f}M requests/month = {be/(H*3600):.1f} req/s average")
print(f"EKS control plane: ${0.10*H:.2f}/month")
1 vCPU/2 GB Fargate task 24x7: $36.04/month
Lambda per request (100 ms, 1 GB): $0.00000187
breakeven: 19.3M requests/month = 7.3 req/s average
EKS control plane: $73.00/month
How to read it:
- Below about 7 requests per second on average, Lambda is cheaper than even one always-on container. A new internal API doing 50,000 requests a day (about 0.6 requests/s) costs roughly 1.5M x $0.00000187, under $3 a month, on Lambda.
- On Kubernetes you would also pay $73 a month for each EKS cluster's control plane (the managed pieces that run the cluster itself, scheduling and API server, separate from and in addition to the nodes that run your pods), run at least two copies for availability, and spend engineer time on the cluster.
- Above the breakeven, containers win on raw compute price, and the gap widens as steady traffic grows, because a busy container is cheaper per unit of work than the same work billed by the millisecond.
The example is deliberately simple: it ignores the free tier, assumes 100 ms per request, and assumes one container could serve that load. Rerun it with your own duration and memory.
Scenarios where one option clearly wins
- Serverless clearly wins: a webhook receiver, a scheduled nightly report, or an image thumbnailer triggered by uploads. Traffic is bursty or idle most of the day, each task takes seconds, there is no platform team, and scale-to-zero means paying almost nothing when idle.
- Kubernetes clearly wins: a high-traffic API steady at around 2,000 requests/s with a strict 20 ms p99 target, maintaining long-lived WebSocket connections (persistent two-way connections), at a company that already runs a Kubernetes platform. Utilization is high, cold starts are unacceptable, and the operational cost is already paid.
Trade-offs and pitfalls
- Counting only the compute bill. The larger cost of Kubernetes for a small team is people: upgrades, security patching, on-call. The larger hidden cost of serverless at scale is the per-millisecond premium on steady traffic.
- Assuming cold starts always matter. For asynchronous work (queues, file uploads) a few hundred extra milliseconds is invisible; they only matter for user-facing, latency-sensitive requests.
- Treating the decision as permanent. Packaging the function as a container image and keeping business logic out of the handler keeps a later move cheap.
- Ignoring the downstream database. Functions can scale to hundreds of copies quickly and exhaust a relational database's connection limit, so plan a connection proxy (a lightweight service, such as RDS Proxy, that pools and limits database connections on functions' behalf) or a concurrency cap.
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".
What would you monitor for a serverless service in production? Cover infrastructure-level signals (invocations, duration, errors), a function-level breakdown (time spent in initialization versus in the handler), and any service-specific output you'd want visibility into. For each category, explain why it matters.
Sample Answer
Direct answer
Monitor three layers. Platform signals tell you whether requests are arriving, succeeding, being throttled, and how long they take. Function-level lifecycle signals separate time spent initializing a new execution environment (a cold start) from time spent in your handler, because they have different causes and different fixes. Service-specific output tells you whether the function is doing the right thing, which platform metrics cannot see: a function can return HTTP 200 all day with wrong answers.
1. Infrastructure-level signals
Names below are AWS Lambda's CloudWatch metrics; other platforms expose equivalents.
| Signal | Metric | Why it matters |
|---|---|---|
| Traffic | Invocations | Baseline for every ratio; a sudden drop often means the trigger broke, not the function |
| Failures | Errors, alert on Errors / Invocations | Includes your exceptions and runtime errors such as timeouts |
| Rejections | Throttles | Requests refused because no concurrency was available. They are not counted in Invocations or Errors, so an error-rate alarm alone misses them |
| Latency | Duration at p50, p95 and p99 | The p99 (99th percentile, the slowest 1 in 100) is what users complain about; averages hide it |
| Capacity | ConcurrentExecutions against the account or reserved limit (a per-function ceiling on concurrency you carve out of the shared account limit, guaranteeing that function its own capacity) | Tells you how close you are to throttling before it happens |
| Pre-warmed capacity | ProvisionedConcurrencySpilloverInvocations | Requests that overflowed pre-warmed environments into cold on-demand ones |
| Backlog (queues and streams: an ordered, append-only log of records, such as Kinesis or DynamoDB Streams, that a function reads sequentially instead of receiving pushed one at a time) | IteratorAge (how far behind the current time the function's read position, its iterator, or bookmark, into the stream has fallen) for streams, AsyncEventAge for asynchronous invocations, queue depth and age of oldest message | A function can look healthy while falling further behind |
| Lost work | Dead-letter queue depth, AsyncEventsDropped, DeadLetterErrors | Events that failed all retries. A DLQ (dead-letter queue) that grows silently is data loss in slow motion |
2. Function-level breakdown: initialization versus handler
A single invocation's time is:
- Init: a new environment is created, the runtime starts and your global-scope code runs (imports, SDK clients, loading a model).
- Handler: your function body for this request.
They must be separated because Lambda's Duration metric excludes cold-start time. The init time appears as Init Duration on the REPORT log line of the invocation that paid it, and only on those invocations. So:
- Cold-start rate = invocations whose REPORT line carries
Init Duration, divided by all invocations. Compute it from logs (for example with a CloudWatch Logs Insights query, a query language and console for searching and aggregating over your CloudWatch log data directly, over REPORT lines) or with CloudWatch Lambda Insights (a monitoring add-on that automatically collects a function's CPU, memory and cold-start metrics without you writing the queries yourself). - Init duration distribution (p50 and p99), watched per deploy: a new dependency that adds 800 ms of imports shows up here and nowhere else.
- Handler duration broken down further with tracing spans (the individual timed segments, for example one downstream call, that a distributed tracing tool such as AWS X-Ray stitches together into one request's timeline): time in downstream calls versus your own computation.
- Memory:
Max Memory Usedagainst configured memory, from the same REPORT line. Near the limit means out-of-memory risk; far below means you may be over-paying.
Worked example: a function shows p99 Duration of 120 ms, yet users see 1.4 s spikes (about the 1,200 ms Init Duration plus the 120 ms handler time, plus the normal network and invocation overhead neither metric captures on its own). Logs show 0.8% of invocations carry Init Duration of about 1,200 ms. The spikes are cold starts, invisible in Duration, because Duration only ever measures handler time and excludes Init.
Here is why the percentile hides them. Sort every invocation's user-facing latency (Init plus handler, for the ones that pay Init) from fastest to slowest. The slowest 0.8% of that list are exactly the cold ones, so they occupy the top 0.8% of the distribution: from the 99.2nd percentile up to the 100th. The 99th percentile sits at the 99.0 mark, still just below where the cold cluster starts at 99.2, so p99 lands on a warm value, about 120 ms, even though 0.8% of real users are waiting over a second. Since 0.8% is under 1%, the p99 of user latency sits right at the edge: if the cold-start rate crept up past 1% (more traffic, a new dependency, fewer warm environments), the cold cluster would grow to cover the 99th percentile itself, and the reported p99 would jump from about 120 ms to roughly 1,200 to 1,300 ms in one step, even though no individual request got any slower. The fix is on the init side (trim imports, pre-warm), not in the handler.
3. Service-specific output
Emit these yourself as custom metrics (for example with the CloudWatch embedded metric format, which turns structured log lines into metrics):
- Business outcome counts: orders accepted, payments declined, messages delivered. A drop with flat
Invocationsmeans requests arrive but fail logically. - Output quality: for a validation or scoring function, the distribution of outputs (share of rejects, score histogram). For an ML inference function, prediction distribution and confidence; a shift means input drift (the real-world data the model now sees has statistically changed shape from what it was trained or validated on) or a bad model version.
- Downstream dependency health: latency and error rate per dependency, so a slow database is distinguishable from slow code.
- Idempotency or duplicate signals: duplicates detected and skipped, since event sources deliver at least once (the same event may arrive more than once).
Keep dimensions (the labels, such as function version or region, you attach to a metric so you can slice and filter it) low-cardinality (built from few distinct values): tag by function version or region, never by user ID, because each unique combination of dimension values is stored and billed as its own separate metric time series, so a high-cardinality dimension like user ID can silently create millions of them.
Why each category matters, in one line each
- Platform signals answer "is it up and keeping up?"
- Init versus handler answers "is latency coming from environment start-up or from my code?", which decides between pre-warming and code optimization.
- Service output answers "is it right?", the only layer that catches silent correctness failures.
Pitfalls
- Alarming on error rate but not on
Throttles, so a saturated function looks healthy. - Reading average
Durationand concluding there is no cold-start problem. - No alarm on DLQ depth.
- Putting request IDs or user IDs into metric dimensions and receiving a large bill for millions of metrics.
How do FaaS platforms scale as traffic increases rapidly? Using AWS Lambda as an example, explain how new execution environments get provisioned, what account or regional concurrency limits exist, and what reserved versus provisioned concurrency each do. What does this mean for a latency-sensitive endpoint under a sudden burst of traffic?
Sample Answer
Direct answer
A FaaS platform (functions-as-a-service: you upload a function and the provider runs it once per event) scales by creating more execution environments. An execution environment is a small isolated sandbox with your runtime and code loaded, and it handles one request at a time. So 600 requests in flight at the same moment need 600 environments. When a request arrives and no idle environment exists, Lambda builds a new one first. That is a cold start. Growth is bounded by two different limits:
- a per-function scaling rate: how fast new environments can be created
- a Regional account concurrency quota: how many can exist at once, shared by every function in the account
Reserved concurrency gives a function its own slice of that quota and caps it there. Provisioned concurrency keeps environments already initialized, so requests that land on them skip the cold start. For a latency-sensitive endpoint, the cold starts and throttles all arrive in the same first seconds of a burst. The fix is to pre-warm the endpoint with provisioned concurrency sized to the burst and make sure the quota has headroom before the burst starts.
How a new environment gets provisioned
- Routing. A request arrives. If an idle, already-initialized ("warm") environment exists, Lambda sends the request there. No setup cost.
- Init phase (the cold start). If there is no idle environment, Lambda creates one: it loads your code package, starts the language runtime and any extensions, then runs your top-level code. That is everything outside the handler: imports, SDK clients, configuration loading.
- Invoke phase. The handler runs.
- Freeze and reuse. After the response, the environment is frozen and kept for later requests. How long it is kept is unspecified. It can be reclaimed at any time, so you cannot rely on it staying warm.
Concurrency means the number of requests being processed at the same instant, and it is also the number of execution environments Lambda needs at that instant. You can compute it with Little's law: concurrency = arrival rate (RPS) x the average time each request spends in the system (duration in seconds). That gives you environments directly; there is no hard per-environment throughput ceiling. AWS's own conceptual scaling guide warns against exactly the framing that sounds intuitive here: "it's incorrect to say that each Lambda execution environment can handle only a maximum of 10 requests per second. Instead of observing the load on any individual execution environment, Lambda only considers overall concurrency and overall requests per second when calculating your quotas." A single warm environment reused back to back for a fast function easily clears 10 requests per second in practice (a 20 ms handler run continuously on one environment serves 50 requests per second, not 10).
What Lambda actually enforces alongside the concurrency quota is a separate REQUEST-RATE quota: RPS must stay at or below 10 times whichever concurrency quota is in force (10,000 RPS against the default 1,000-unit account quota; 10 times a function's reserved concurrency if it has one; 10 times its provisioned concurrency for the units running on it). This is a policy ceiling tied to the quota number, not a physical property of any one environment. For a function whose average duration is at or above 100 ms, Little's law alone already keeps the request rate inside that 10x ceiling, so it never binds. It matters specifically for the sub-100-ms case: a 20 ms function serving 30,000 RPS needs a concurrency, and so an environment count, of only 600, comfortably under a 1,000-unit account quota, but its request rate of 30,000 is three times the 10,000 RPS the default quota allows, so it throttles on the rate ceiling even though the environment count looks fine.
environments (concurrency)=RPS×durationswith a second, independent check for functions under about 100 ms average duration:
RPS≤10×concurrency quota (account default, or the function’s reserved/provisioned concurrency)The limits
| Limit | Scope | Default | What happens when you hit it |
|---|---|---|---|
| Concurrency quota | Account, per Region, shared by all functions | 1,000 (new accounts start lower); can be raised to tens of thousands through Service Quotas (the AWS console and API where you request a higher account limit) | Requests beyond it get a throttling error (HTTP 429) |
| Concurrency scaling rate | Per function, per Region | 1,000 new environments per 10 seconds, refilled continuously (picture a token bucket that starts full at 1,000: creating an environment spends one token, and tokens refill steadily, but the bucket cannot hold more than 1,000 at once); unused capacity does not accumulate beyond that 1,000-token cap | Requests arriving faster than environments can be created are throttled (429) |
| Unreserved floor | Account | 100 units always stay unreserved | You cannot reserve or provision more than (quota minus 100) |
The effect of a throttle depends on who called the function:
- Synchronous callers (API Gateway, a direct invoke) get the error immediately. Nothing retries for you.
- Asynchronous sources (S3 notifications, SNS, Amazon Simple Notification Service, a managed pub/sub messaging service) go through Lambda's internal queue, which retries throttled events for up to 6 hours by default.
- Queue pollers (Amazon SQS, Simple Queue Service) leave the messages in the queue to be retried.
Reserved versus provisioned concurrency
| Reserved concurrency | Provisioned concurrency | |
|---|---|---|
| What it does | Guarantees this function N units and also caps it at N | Keeps N environments initialized ahead of time; init code runs at allocation |
| Removes cold starts? | No. It only decides who gets capacity | Yes, for requests that land on those N environments |
| Cost | No extra charge | Billed per GB-second for as long as it is configured, used or not |
| Applies to | The function | A published version (an immutable, numbered snapshot of the function's code and configuration) or alias (a named pointer, like prod, that you can repoint to a different version), never $LATEST (the mutable pointer to whatever code is currently deployed, which is why it cannot be pinned to provisioned concurrency) |
| Above the setting | Throttled (429) | Overflow uses normal on-demand environments, which cold start |
| Typical use | Protect a critical function from being starved; stop a function from flooding a database | Interactive, latency-sensitive endpoints |
If both are set, provisioned concurrency cannot exceed reserved concurrency. Setting reserved concurrency to 0 is the documented way to stop a function completely.
Worked example
Assume an endpoint whose handler takes 120 ms. It normally sees 100 RPS with 12 environments warm, and the account quota is the default 1,000.
# Environments needed = RPS x duration (Little's law: this alone gives the concurrency,
# i.e. the environment count). The separate 10x-quota request-rate ceiling only binds
# for average durations under about 100 ms, which this 120 ms example never reaches.
duration_s = 0.120 # assumed average handler duration for the endpoint
bucket = 1000 # scaling rate: up to 1,000 new environments per function...
refill_per_s = 100 # ...refilled continuously (1,000 per 10 s)
warm_now = 12
def report(rps, account_limit):
need = rps * duration_s
cold = max(0, min(need, account_limit) - warm_now)
wait = max(0, cold - bucket) / refill_per_s
short = max(0, need - account_limit)
print(f"{rps:>6} RPS, quota {account_limit:>5}: need {need:>5.0f}; new (cold) environments {cold:>5.0f}; "
f"seconds beyond the first 1,000 new: {wait:>4.1f}; throttled capacity gap: {short:.0f}")
for rps in (100, 5_000, 15_000):
report(rps, 1_000) # default Regional concurrency quota
report(15_000, 3_000) # after a quota increase
pc_units, mem_gb, price_pc = 600, 1.0, 0.0000041667 # USD per GB-second, us-east-1, x86
hour = pc_units * mem_gb * 3600 * price_pc
print(f"provisioned concurrency {pc_units} x {mem_gb} GB: ${hour:.2f}/hour, ${hour * 730:,.0f}/month if always on")
100 RPS, quota 1000: need 12; new (cold) environments 0; seconds beyond the first 1,000 new: 0.0; throttled capacity gap: 0
5000 RPS, quota 1000: need 600; new (cold) environments 588; seconds beyond the first 1,000 new: 0.0; throttled capacity gap: 0
15000 RPS, quota 1000: need 1800; new (cold) environments 988; seconds beyond the first 1,000 new: 0.0; throttled capacity gap: 800
15000 RPS, quota 3000: need 1800; new (cold) environments 1788; seconds beyond the first 1,000 new: 7.9; throttled capacity gap: 0
provisioned concurrency 600 x 1.0 GB: $9.00/hour, $6,570/month if always on
What the numbers mean:
- Burst to 5,000 RPS. You need 600 environments. The scaling rate is not the problem: its token bucket starts full at 1,000 (see above), so all 588 new environments can be created immediately from that reserve, with no need to wait for the refill. The problem is that 588 requests each wait for a cold start at the same moment, and that is what p99 latency (the latency 99% of requests beat) will show. Init time depends on runtime and package size. Read it from the
Init DurationLambda logs rather than guessing. - Burst to 15,000 RPS on the default quota. You need 1,800 environments but only 1,000 can exist. About 800/1,800, or 44%, of the load is throttled.
- Same burst after raising the quota to 3,000. The first 1,000 new environments appear immediately. The remaining 788 arrive at the refill rate of about 100 per second, so over about 7.9 seconds. Requests above capacity during those seconds are still throttled.
- Cost of pre-warming 600 x 1 GB: $9.00 an hour, or about $6,570 a month if it is left on all the time. That is why you schedule it rather than leave it on.
What this means for a latency-sensitive endpoint
- Provisioned concurrency on the alias the API actually invokes (never on
$LATEST, which cannot hold provisioned concurrency). Size it to the expected burst plus a buffer. Lambda's own guidance is +10%, so 600 becomes 660. If the burst is predictable, raise it on a schedule. - Reserved concurrency at or above that number. This stops other functions in the account from starving the endpoint. Without it, a noisy batch job (an unrelated function in the same account that suddenly scales hard, for a backfill or a retry storm) in the same Region can use up the shared 1,000.
- Quota headroom requested ahead of time. Check the layers in front of Lambda too. API Gateway (AWS's managed HTTP front door) has its own default account throttle of 10,000 RPS per Region.
- Make cold starts cheaper for the overflow. Keep the package small, create SDK clients at top level so warm invocations reuse them, and defer rarely used clients. For supported runtimes, snapshot restore (Lambda SnapStart) is a cheaper alternative to keeping environments warm.
- For bursts beyond anything you pre-warmed, decide the behaviour explicitly. Either return a fast 429 and have clients retry with jittered backoff (each retry waits longer than the last, with a bit of randomness mixed in so many clients do not all retry at the same instant), or, if the work does not need an immediate answer, accept it into a queue.
Pitfalls
- Invoking
$LATESTor the wrong alias. Provisioned concurrency sits unused, you still pay for it, and cold starts continue. - Treating reserved concurrency as a performance feature. It warms nothing.
- Expecting target-tracking auto scaling (a controller that watches a metric and adds or removes capacity to hold it near a target value) to catch a spike. Application Auto Scaling on
ProvisionedConcurrencyUtilizationneeds the load to last about 3 minutes (three data points) before it adds capacity. It handles slow drift, not a sudden burst. - Forgetting the separate request-rate ceiling for sub-100-ms functions. Little's law alone gives the right environment count even for a fast function (a 20 ms function at 30,000 RPS needs only 600 environments), but request rate can still hit the platform's 10x-of-quota ceiling before concurrency does: at the default 1,000-unit quota that ceiling is 10,000 RPS, so the 30,000-RPS case above throttles despite having plenty of environment headroom.
- Scale-out has side effects downstream. 600 new environments can mean 600 new database connections. Plan the downstream protection together with the scaling.
Design an observability architecture for a serverless platform: end-to-end distributed tracing from the API gateway through the function to whatever it calls downstream, plus service-level metrics and anomaly detection, all while keeping the observability bill under control. What sampling strategy would you use, where do traces and metrics get stored, and how do you correlate telemetry across an async hop to debug one specific failed request?
Sample Answer
Direct answer
Instrument every hop with OpenTelemetry (the open standard and SDKs for traces, metrics and logs), propagate one trace context through the API gateway, the functions and every message across async hops, and put a correlation ID in every log line. Keep costs bounded with low head sampling for successful traffic plus guaranteed capture of failures, cheap aggregated metrics for SLOs (service-level objectives) and anomaly detection, and logs with short hot retention and cheap archive. To debug one failed request, walk from the request ID the client saw, to the trace ID in its logs, to the trace, across the queue via its link to the consumer's span.
Requirements I am designing to
- 100 requests per second average at the gateway (259.2M requests per month), each producing a sync function call and an async message to a worker.
- p99 (the 99th-percentile latency: the value only the slowest 1% of requests exceed) latency SLO on the API; error-budget alerting (paging when the service has spent too much of the failure rate its SLO allows, rather than on every individual error; the full mechanism is below).
- Find any specific failed request within minutes, including failures that happen after the async hop.
- Observability spend should be a small fraction of compute spend, with arithmetic below.
Architecture
flowchart LR
C[Client] --> G[API gateway]
G --> F1[API function]
F1 -->|message plus trace context| Q[Queue]
Q --> F2[Worker function]
F2 --> D[Downstream API or DB]
F1 -.spans, EMF metrics, logs.-> T[Telemetry pipeline]
F2 -.spans, EMF metrics, logs.-> T
T --> TR[Trace store]
T --> M[Metrics store]
T --> L[Log store plus archive]
Components
- Tracing: the AWS Distro for OpenTelemetry Lambda layer (AWS's own supported build of the open-source OpenTelemetry instrumentation, attached to a function without changing its code) or native AWS X-Ray (AWS's distributed tracing service) on each function. Spans (timed records of one unit of work) cover the gateway, handler, each downstream call, and the enqueue.
- Metrics: SLO metrics (requests, errors, latency histograms) emitted as structured logs in the CloudWatch embedded metric format (EMF), which the platform turns into metrics without a synchronous API call inside the function; or a Prometheus-compatible managed store (Prometheus is a widely used open-source metrics system; a managed store that speaks its query language) if the organization standardizes on it.
- Logs: structured JSON with
request_id,trace_id,function_version, outcome. Kept in hot retention (the fast, queryable store, as opposed to cheap cold archive) for 14 days, then archived to object storage. - Anomaly detection: statistical bands (a normal range computed from a metric's own recent history, so an alert fires only once it moves outside that range) on a few high-value series (error rate, p99, throughput per route), plus multi-window burn-rate alerts: an SLO like 99.9% availability allows a fixed amount of failure over its measurement window, the error budget (here, 0.1% of requests over 30 days); a burn-rate alert pages when errors are consuming that budget faster than a sustainable rate, checked over both a short window (to catch a real incident fast) and a long window (so a brief blip does not page anyone) at once, which is why it is "multi-window" (for example, page when 2% of the monthly error budget is consumed in one hour). Anomaly detection runs on aggregated metrics, never on raw traces, which keeps it cheap.
Propagating context across the async hop
The trace context (a trace ID plus parent span ID, the ID of the span that caused this one, in the W3C (World Wide Web Consortium, the standards body) traceparent header or AWS's X-Amzn-Trace-Id) must ride inside the message, because there is no HTTP connection between producer and consumer.
- SQS (Amazon Simple Queue Service) to Lambda on AWS: SQS carries the X-Ray trace header in the reserved
AWSTraceHeadermessage system attribute, and a Lambda consumer picks it up automatically; the console shows the producer's trace linked to the consumer's. - Other brokers (EventBridge, Kafka (Apache Kafka, a distributed event-streaming log), SNS fan-out, one SNS message delivered to every subscriber at once): inject
traceparentinto message attributes or headers at publish and extract it in the consumer. - Batches: one consumer invocation may process 10 messages from 10 different traces. Model the consumer's work as its own span with span links (references from one span to other related spans that are not its direct parent or children, so one span can point back to many origins) to each message's producing span, rather than pretending it has a single parent.
- Redundant safety net (belt and braces): also put a business correlation ID (order ID, request ID) in the message body and in every log line, so the chain can be reconstructed even for unsampled traces.
Sampling strategy and the cost arithmetic
Prices: X-Ray records traces at $5.00 per million, and CloudWatch Logs standard ingestion is $0.50 per GB (US East, current list).
N=100×2,592,000=259,200,000 traces per month 100% sampling=259.2×5.00=$1,2965%=$64.801%=$12.96Decision: head-sample 5% of successful requests (the decision is made at the entry point and propagated, so a trace is complete or absent, never half-recorded), and capture 100% of errors and slow requests. Capturing all errors needs tail sampling: deciding after the trace finishes. A function cannot do that alone because it sees only its own spans, so either route spans through an OpenTelemetry Collector gateway (a standalone process that receives every function's spans and applies rules to them centrally, before they reach the trace store) running tail-sampling rules (errors, latency above the SLO threshold, specific tenants), or, if you stay on head sampling only, guarantee that every error log line carries the trace ID and full context, so unsampled failures are still debuggable from logs.
Logs: 1 KB per request is 259.2 GB per month, $129.60 of ingestion. Log at INFO for outcomes only, DEBUG sampled, errors in full.
Metrics cardinality is where observability bills explode. Each unique combination of metric name and dimension values is billed as a separate custom metric ($0.30 per metric per month for the first 10,000, $0.10 for the next tier). Adding a customer_id dimension across 10,000 customers for 3 metrics creates 30,000 metrics:
That is more than all tracing at 5%. Per-customer analysis belongs in logs or traces (queried on demand), not metric dimensions.
Where telemetry is stored
| Data | Store | Retention |
|---|---|---|
| Traces | X-Ray or an OpenTelemetry-compatible trace backend | 7 to 30 days; long-term value is low |
| SLO metrics | CloudWatch or managed Prometheus | 15 months; cheap because aggregated |
| Logs | Log service, hot | 14 days, then object-storage archive queried on demand |
Debugging one specific failed request
- Client reports failure and returns the
request_idfrom the error response (always return it). - Log query on
request_idfinds the API function's line and itstrace_id. - Open the trace: gateway span, handler span, enqueue span, status OK. The failure is after the hop.
- Follow the link from the enqueue span to the worker's span (automatic for SQS to Lambda; via span links for batches).
- The worker span shows a 5 s downstream timeout; its log lines, filtered by the same
trace_id, show the payload that triggered it; the message is in the dead-letter queue, ready to redrive (resend through the same processing path for another attempt) after the fix.
If the request was not in the 5% sample and tail sampling is not deployed, steps 3 and 4 fall back to logs by trace_id and correlation ID, which is why the log discipline is non-negotiable.
Pitfalls
- Head sampling only, then discovering the failure you need was in the 95% dropped.
- Losing trace context at the queue because the producer never injected it.
- High-cardinality metric dimensions.
- Synchronous telemetry exports inside the handler that add latency and billed duration to every request.
Unlock Full Question Bank
Get access to all 15 Serverless and Function-as-a-Service Architecture interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.