Serverless and Function-as-a-Service Architecture Questions
Building applications on managed, event-triggered compute: functions-as-a-service (AWS Lambda, Azure Functions, Google Cloud Functions, Cloudflare Workers) and serverless containers. Covers the invocation lifecycle and cold starts (init vs handler work, provisioned concurrency, packaging, layers and container images), statelessness and externalizing state, execution limits (timeouts, memory, payload and /tmp size), concurrency and scaling behavior (account limits, burst scaling, protecting downstream databases with connection proxies and throttling), event sources and trigger semantics (at-least-once delivery, retries, idempotent handlers, dead-letter handling), composing functions with managed services and workflow orchestrators (Step Functions and equivalents), and serverless-specific observability, security (per-function IAM, secrets) and pay-per-invocation cost modeling. Includes when serverless fits versus containers or VMs, and vendor lock-in trade-offs. General compute selection, generic messaging patterns, and general idempotency theory are covered by their own topics.
Explain stateless versus stateful function design in a serverless architecture. When should a function be fully stateless, and when is holding state (session context, aggregated results, a warm cache) actually justified? Where does that state live once it's outside the function, and what latency or consistency trade-offs come with each option?
Sample Answer
Direct answer
A stateless function keeps nothing it depends on between invocations: everything it needs arrives in the event or is read from an external store, and everything worth keeping is written back out. That is the default in serverless, because the platform runs many copies in parallel, routes each request to whichever copy is free, and destroys copies whenever it likes. Holding state inside the function is justified only as a disposable optimization: a warm cache of read-mostly data or a reused connection, where losing it costs a slower request but never a wrong answer. Anything that must be correct or durable (sessions, running totals, workflow progress) lives outside the function, and you pick the store by the latency and consistency you need.
Why "in-memory state" breaks in FaaS
Three properties of the platform, each enough on its own:
- Many copies. At 50 concurrent requests there are about 50 separate execution environments (sandboxes), each with its own memory. A counter in one is invisible to the others.
- No affinity. A user's second request can land on a different environment than their first, so an in-memory session is simply missing.
- No lifetime guarantee. Environments are frozen when idle, recycled every few hours even under load, and reset after a crash. Memory contents vanish without warning.
The simulation below routes 1,000 click events to environments the way a platform might (any environment, new ones added under load), and has the platform recycle one environment part-way through. Each environment keeps a local counter; the "external" counter stands in for an atomic counter in a database (one whose increments cannot partially overlap: two simultaneous +1s always land as +2, never silently lose one).
import random
random.seed(7)
EVENTS = 1000
envs = {} # env_id -> in-memory click count (what a "stateful" function would keep)
external_total = 0 # stands in for an atomic counter in an external store
next_env = 0
def pick_env():
global next_env
# the platform routes to any idle environment, and adds new ones under load
if not envs or random.random() < 0.01:
envs[next_env] = 0
next_env += 1
return random.choice(list(envs))
for i in range(EVENTS):
e = pick_env()
envs[e] += 1 # in-memory aggregation
external_total += 1 # externalized aggregation
if i == 600: # the platform recycles one environment mid-stream
victim = min(envs)
lost = envs.pop(victim)
print("environments created:", next_env)
print("any single environment's count:", envs[min(envs)])
print("sum of surviving in-memory counts:", sum(envs.values()))
print("counts lost when env", victim, "was recycled:", lost)
print("external counter:", external_total)
Output:
environments created: 15
any single environment's count: 163
sum of surviving in-memory counts: 792
counts lost when env 0 was recycled: 208
external counter: 1000
No single environment knows the true total (163 is one environment's view), the in-memory sum is short by the 208 clicks held in the recycled environment, and only the externalized counter is right.
When holding state is justified
| State kept in the function | Justified? | Condition |
|---|---|---|
| Reused database or HTTP client connection | Yes | Reconnect if it has gone stale after a freeze. |
| Cache of read-mostly data (config, feature flags, meaning switches that turn a feature on or off without a deploy, reference tables, a loaded model) | Yes | Has a TTL (time-to-live, an expiry) or version check; a miss just means one slower request. |
| Per-user session context | No | Another environment will serve the next request. Put it in an external store keyed by session ID. |
| Aggregated results (counters, running sums, batches being built) | No | Copies split the data and recycling loses it. Aggregate in the store, or stream events to something built to aggregate. |
| Progress of a multi-step job | No | A crash or timeout loses it. Use a workflow orchestrator (for example AWS Step Functions, a managed state machine that records each step's result) or a job table. |
The test: if this state disappeared right now, would the next request be slower, or wrong? Slower is acceptable for an in-function cache. Wrong means it belongs outside.
Where externalized state lives, and what each option costs you
| Store | Typical use | Latency (order of magnitude) | Consistency to know about |
|---|---|---|---|
| Key-value database (Amazon DynamoDB, Azure Cosmos DB, Firestore) | Sessions, idempotency records (a stored marker of which request IDs have already been processed, so a retry can be detected and skipped), counters via atomic update | Single-digit milliseconds within the Region | DynamoDB reads are eventually consistent by default (a read right after a write can be stale); request a strongly consistent read when you must see your own write. Atomic ADD/conditional updates let many copies update one counter without losing increments. |
| In-memory cache (Redis or Memcached, as a managed service such as Amazon ElastiCache) | Hot session data, rate-limit counters, shared cache | Sub-millisecond to low milliseconds, network hop included | Replication to replicas is asynchronous, so a failover can lose recent writes. Treat it as a cache unless you've configured and tested durability. On AWS it runs inside a VPC (Virtual Private Cloud, a private network), so the function must join that network. |
| Object storage (Amazon S3) | Large blobs, intermediate files, batch outputs | Tens of milliseconds per request | S3 gives strong read-after-write consistency for objects, but it is not built for small, frequent updates to the same key. |
| Relational database (PostgreSQL, MySQL) | Transactional state across entities | Low milliseconds, plus connection set-up | Strong consistency and transactions; the risk is connection count, since each concurrent environment wants its own connection. Use a connection proxy (such as Amazon RDS Proxy) or cap function concurrency. |
| Workflow orchestrator (Step Functions, Azure Durable Functions) | Multi-step progress, retries, waiting for humans | Per-step overhead, well above a single function call | The orchestrator owns the state machine, so a failed step resumes rather than restarting from zero. |
Worked example: a click-counting API
Requirement: count clicks per article per minute, 2,000 clicks per second at peak, dashboard reads the counts. Assume a lightweight handler, about 15 ms per click (just an increment call): by Little's Law (the number of requests in flight equals the arrival rate times the time each spends being handled), 2,000/s x 0.015s = 30, which is where the "~30 environments in flight" below comes from.
- Wrong: each function keeps
counts[article] += 1in memory and writes it out "every minute". With ~30 environments in flight (the arithmetic above), 30 partial counts race to overwrite each other, and a recycled environment loses its last minute. - Right, simple: each click performs an atomic increment on a key such as
article#42#2026-09-27T10:15in DynamoDB. 2,000 writes per second is fine for the table as a whole, but a single viral article sends all its writes to one key; spread that hot key (a single partition key taking disproportionate traffic) across N sub-keys (#shard0to#shardN) and sum them on read. - Right, at larger scale: put clicks on a stream (a managed, ordered, replayable log of events that many independent readers can consume, such as Amazon Kinesis or Apache Kafka) instead of writing straight to the table. A stream is split into shards, in this context a partition of the stream that one reader handles at a time (a different sense of "shard" from the DynamoDB sub-keys just above, which split a hot row, not a stream); let one consumer, a process reading a shard in order, aggregate clicks per minute and write the result once. Aggregation in a stream consumer is safe because the stream, not the function's memory, is the source of truth: if a consumer crashes partway through a minute, a new one picks up the shard from the last committed position and can be replayed, meaning it re-reads events the stream already has instead of losing them.
- The justified warm state: each function keeps a 60-second in-memory cache of the article metadata it needs to validate clicks. Losing it costs one extra read.
Trade-offs and pitfalls
- Latency versus correctness. Every external read or write adds a network hop. Cache reads locally when stale data is acceptable; never cache anything you then use to make an authoritative decision (balances, inventory).
- Globals leak across requests. Module-level variables survive between invocations in the same environment, so per-request data stored there can bleed into the next user's request. Keep request data local.
/tmpis memory-adjacent state too. Files there survive between warm invocations and vanish on recycle. Same rule: cache only.- Retries make external writes happen twice. Event sources deliver at least once, so a retried invocation can double-increment. Where exactness matters, record a per-event ID with a conditional write (a database write that only succeeds if a stated condition holds, here "this event ID is not already recorded") and skip duplicates.
A deployment artifact you need to run in Lambda is 800MB, well past the deployment-package limit and too big to comfortably fit in /tmp. Compare architectures for serving it: mounting EFS, streaming it from S3 at cold start, packaging it as a container image, or moving it to a managed endpoint outside Lambda entirely. For each, discuss cold-start latency, throughput, cost, and operational complexity.
Sample Answer
Direct answer
For an 800 MB artifact that changes with the code, package the function as a container image: it lifts the size limit from 250 MB to 10 GB, needs no private network, and Lambda loads image contents on demand from a cache, so cold starts track what init actually reads. Choose Amazon EFS (Elastic File System, a shared network file system) when the artifact changes independently of the code or is shared by several functions. Avoid downloading from S3 at every cold start: the arithmetic below shows 800 MB alone takes over 10 seconds per cold start. Move to a managed always-on endpoint outside Lambda when traffic is steady enough that you pay for idle capacity anyway, when you need a GPU, or when no cold start is acceptable.
First, a correction to the premise: /tmp on Lambda is configurable from 512 MB up to 10,240 MB, so 800 MB can fit there (extra ephemeral storage is billed per GB-second). The real problems are getting 800 MB there on every cold start, and the memory needed if the artifact is then loaded into RAM.
The constraints that decide it
- Package limits. A zip deployment, including layers, may be at most 250 MB unzipped; a container image may be up to 10 GB uncompressed.
- Init time limit. On-demand Init (module-level set-up) gets 10 seconds; if it overruns, Lambda retries Init inside the first invocation, bounded by the function timeout.
- Network bandwidth. Lambda's documented network bandwidth per execution environment is 625 Mbps (megabits per second, 10^6 bits). Anything fetched over the network at cold start is bounded by it.
- Memory. If the artifact must sit in RAM, configured memory must hold it plus the runtime and working space, and you pay for that memory on every invocation.
Worked example: how long does 800 MB take to fetch?
Lambda's "MB" is 2^20 bytes, so 800 MB = 800 x 1,048,576 x 8 = 6,710,886,400 bits. At the 625 Mbps ceiling:
625×106 bits/s6,710,886,400 bits=10.74 sThat is the best case, before any decompression or parsing, and it already exceeds the 10-second Init cap. Every new environment pays it, so a burst that needs 50 new environments downloads 50 x 800 MB = 40,000 MB.
The four options compared
| Cold-start latency | Throughput once warm | Cost | Operational complexity | |
|---|---|---|---|---|
Stream from S3 into /tmp at cold start | Worst: at least 10.74 s of transfer per new environment (above), plus unpacking | Fine once loaded | Init time is billed; extra /tmp above 512 MB billed per GB-second; S3 request costs trivial | Low to build, but fragile: sits on the 10 s Init cap; each environment repeats the download |
| Mount Amazon EFS | Depends on read pattern. Reading all 800 MB eagerly is also a network read, so expect the same order as S3. Reading only the parts needed is much faster: memory-mapping (mapping the file so pages load into memory only as your code actually touches them, instead of reading the whole file upfront) or indexed access (seeking straight to the record you need instead of scanning) | Good for reads served from the environment's page cache, the operating system's own in-memory copy of recently read file blocks, which sticks around until the environment is recycled; first reads pay network latency | EFS storage plus throughput charges; the throughput mode you pick, bursting (earns credits while idle and spends them under load), elastic (scales automatically with actual usage) or provisioned (a fixed throughput you pay for whether you use it or not), must sustain N environments reading at once | Highest: function must join a VPC (Virtual Private Cloud, an isolated private network you control) with mount targets, the network endpoints EFS exposes inside a subnet so anything there can attach the file system, in each Availability Zone (an isolated data-center group inside the Region) it runs in, and security groups, the firewall rules attached to those mount targets, allowing NFS (Network File System, the protocol EFS speaks, port 2049); a separate process has to update the files |
| Container image (artifact baked in) | Good: Lambda splits images into chunks, deduplicates them (stores one copy of any chunk shared across images instead of a separate copy per image) and caches them, then fetches chunks as the code reads them (described in AWS's 2023 USENIX ATC paper, USENIX ATC being a peer-reviewed systems-research conference, titled "On-demand Container Loading in AWS Lambda"). Cold start depends on bytes read during init, not image size. Deploys and long-idle functions warm the cache again | Same as zip | Registry storage (Amazon ECR, Elastic Container Registry); no VPC or EFS cost; Init billed as with any image | Moderate: image build pipeline; every artifact change is a new image and deploy |
| Managed endpoint outside Lambda (a container service such as Amazon ECS on Fargate, or a model-hosting endpoint, a managed, always-running service built specifically to serve a loaded ML model over an API, such as Amazon SageMaker's real-time inference endpoints) | None for users once running; the artifact loads once per replica | Highest: long-lived processes, concurrency per replica, GPUs available | Pay per replica-hour, busy or idle | Moderate to high: scaling policy, health checks, deployments; Lambda (if kept) calls it over the network |
flowchart TD
A[800 MB artifact] --> B{Changes with code releases?}
B -- yes --> C{Traffic steady or GPU needed?}
B -- no, updated separately or shared --> E[EFS mount, read lazily]
C -- no, spiky --> D[Container image]
C -- yes --> F[Managed always-on endpoint]
Recommendation and what would change it
Default: container image. It is the only option that removes the size limit without adding a network dependency at start-up that you have to operate. Put the artifact in an early image layer that rarely changes and your code in the last layer, so ordinary code changes don't re-upload the artifact.
- Switch to EFS if the artifact updates on its own schedule (for example daily data refreshes) and rebuilding an image each time is unacceptable, or several functions share it. Structure access to read only what each request needs, and provision throughput for peak concurrency.
- Switch to a managed endpoint once sustained load makes always-on replicas cheaper than per-invocation billing, or when the artifact needs a GPU or must stay in memory without per-environment duplication.
- Use S3 download only for rare background jobs where a slow cold start does not matter, and then fetch during the invocation (subject to the function timeout) rather than squeezing it into the 10-second Init.
Pitfalls
- RAM, not just disk. If the 800 MB is fully deserialized, meaning converted from the file's on-disk bytes into in-memory objects your code works with directly, you may need well over 1 GB configured, paid on every invocation. Memory-mapping keeps resident memory closer to what is actually touched.
- EFS throughput exhaustion. Many environments starting at once can exhaust burst capacity, the reserve of extra throughput EFS's bursting mode grants based on file-system size and lets you spend down temporarily; the symptom is init times that stretch only during scale-outs.
- Inactive container functions. A container-image function not invoked for weeks becomes inactive; the next call fails while Lambda re-optimizes the image. Scheduled invocations or monitoring the function state avoids surprise.
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.
Walk through what actually determines your bill for a workload running on a serverless platform, then use it: given a request rate, average execution duration, and memory size, estimate the monthly cost. Which levers would you tune first to bring the cost down without hurting your latency SLOs?
Sample Answer
Direct answer
On a FaaS (functions-as-a-service) platform such as AWS Lambda you pay for two things per function: a per-request fee and a compute fee measured in GB-seconds (memory allocated in GB multiplied by billed execution time in seconds). Memory is also the CPU dial, so memory and duration trade against each other. Around the function you also pay for the front door (API gateway), logs, and data transfer, and those often rival the function itself. The first levers are: cut billed duration (especially time spent waiting on I/O), right-size memory by measurement, move to the cheaper ARM architecture, and cut log volume, checking p99 (99th-percentile) latency against your SLO (service-level objective, the latency target you have committed to) after each change.
What determines the bill
Prices below are AWS Lambda, US East (N. Virginia), from the current public price list.
| Component | Unit price | Driven by |
|---|---|---|
| Requests | $0.20 per 1M requests | Invocation count |
| Compute, x86 | $0.0000166667 per GB-second (first tier) | Memory size multiplied by billed duration (rounded up to 1 ms) |
| Compute, ARM (Graviton, AWS's own ARM-based processor family) | $0.0000133334 per GB-second (first tier) | Same, about 20% cheaper per GB-second |
| Free tier | 1M requests and 400,000 GB-seconds per month | Applies once per account |
| Init (cold start: the one-time setup work, code download, runtime start-up, and your own init code, that only the first request on a new execution environment pays) time | Billed as duration | Since 1 August 2025, INIT is billed for on-demand zip functions (functions deployed as a plain code archive rather than a container image, the default and simplest packaging) on managed runtimes (AWS's built-in language runtimes, as opposed to a custom one you bring yourself) too |
| Provisioned concurrency (paying to keep a set number of environments already initialized and idle, so even the first request to each hits a warm environment) | $0.0000041667 per GB-second reserved, plus a lower duration rate | Only if you pre-warm environments |
Ephemeral /tmp beyond 512 MB | $0.0000000309 per GB-second | Rarely material |
Outside the function: an HTTP API on API Gateway is $1.00 per million requests for the first 300M, and log ingestion into CloudWatch Logs is $0.50 per GB at the standard rate.
The formula
GB-s=N×d×1024M Cost=106N−106×0.20+(GB-s−400,000)×pGB-swhere N is requests per month, d is average billed duration in seconds, M is memory in MB, and pGB-s is the per GB-second price.
Worked estimate
Inputs: 50 requests per second on average, 200 ms average duration, 512 MB memory, x86, 30-day month.
N=50×2,592,000=129,600,000 requests GB-s=129,600,000×0.2×0.5=12,960,000 Compute=(12,960,000−400,000)×0.0000166667=$209.33 Requests=(129.6−1)×0.20=$25.72Function total: about $235 per month. Add an HTTP API front door at 129.6M multiplied by $1.00 per million = $129.60, so the API gateway alone is more than half of the function bill. If each invocation writes 1 KB of logs, that is 129.6 GB, or about $65 of ingestion at $0.50 per GB.
This estimate correctly subtracts the free tier once, because the formula is exact billing math for one account. Do not let the free tier itself drive a design decision: at this example's 50 requests per second, 400,000 GB-s is about 3.1 percent of the 12,960,000 GB-s used, worth roughly $6.67 of compute at the x86 rate, not the well-under-half-a-percent rounding error it becomes once traffic reaches roughly 300 requests per second or higher, where the same fixed 400,000 GB-s free allowance is a shrinking share of a much larger GB-second total. Account for it once for precision at whatever scale you are estimating, and do not let its exact size change which lever you pull first.
Which levers to pull first, and their latency risk
| Lever | Effect in the example | Latency risk |
|---|---|---|
| Cut billed duration (reuse connections created outside the handler, so opening one at module scope during Init means later warm requests skip connection setup and pay only for the request itself; parallelize downstream calls; stop waiting synchronously on slow services) | 200 ms to 120 ms drops compute to (129.6M × 0.12 × 0.5 − 400,000) × 0.0000166667 = $122.93 | None; usually improves latency |
| Switch to ARM | Same GB-seconds at $0.0000133334 gives $167.47 (20% less compute) | Low, but native dependencies (compiled libraries, not pure interpreted code) must be rebuilt for the new CPU architecture, a compiled binary built for x86 will not run on ARM, and benchmarked |
| Right-size memory by measurement | If the work is CPU-bound, 1024 MB may halve duration to 100 ms: 129.6M × 0.1 × 1.0 GB-s costs the same $209.33 but p99 improves | Going down in memory on CPU-bound code raises duration and p99; going up can be free |
| Cut log volume (sample debug logs, drop full-event dumps) | 1 KB to 200 bytes per call saves about $52 of the $65 | None for latency; keep error logs complete |
| Replace the front door where possible (HTTP API, API Gateway's newer, cheaper, simpler product, instead of REST API, its older, more feature-rich and more expensive one, or a direct function URL, a dedicated HTTPS endpoint Lambda can generate for a function that bypasses API Gateway entirely, for internal callers) | Up to the $129.60 line | Check you are not dropping features such as caching or request validation |
| Batch for asynchronous sources (process 10 queue messages per invocation) | Divides request count and per-invocation overhead | Adds per-message latency, fine off the user path |
The ordering principle: duration first because it is almost always free latency-wise, architecture second, memory by measurement (a power-tuning sweep: run the same workload at several memory settings and plot cost and latency at each, for example with the open-source AWS Lambda Power Tuning tool, to find the cheapest setting that still meets your latency target), then the non-function lines.
Pitfalls
- Lowering memory to save money. Because CPU scales with memory (1,769 MB is one full vCPU, virtual CPU, one full CPU core's worth of compute, on Lambda), halving memory on CPU-bound code roughly doubles duration: no saving and a worse p99.
- Ignoring the non-function lines. Engineers optimize GB-seconds while the gateway, logs, NAT (network address translation) gateway data processing, or cross-region transfer dominate.
- Paying for idle waiting. A function that polls a job for 30 seconds is billed for 30 seconds of memory. Hand waiting to a workflow orchestrator or an event instead.
- Forgetting that the free tier is per account, so it is noise at production scale and should not be used to justify a design.
Design a serverless architecture for a latency-sensitive API with a p99 SLO around 50ms, steady traffic of about 100 requests/sec with bursts to 1000 rps for short periods. Describe the components (gateway, functions, caches, CDN), how you'd meet the latency and concurrency requirements (provisioned concurrency, local caches, warm pools), and the cost-versus-latency trade-offs of each choice. If cost pressure rules out running everything at full provisioned capacity, how would you degrade gracefully under a burst rather than blowing the SLO?
Sample Answer
Direct answer
Put a CDN (content delivery network) and edge cache in front for anything cacheable, an HTTP API gateway in front of functions pinned to pre-warmed capacity (provisioned concurrency, AWS's name for what the question calls a warm pool: a set of environments kept initialized and ready before traffic arrives) sized to the burst, not the average, and serve data from an in-region cache so the handler's own work stays in single-digit to low tens of milliseconds. The one thing that breaks a 50 ms p99 on serverless is cold starts, which cost from under 100 ms to over a second each, and bursts concentrate them. If the budget will not pay for burst-sized pre-warming, degrade deliberately: serve stale from the edge, pre-warm on a schedule for predictable bursts, and shed low-priority traffic with fast 429s instead of letting it queue behind cold starts.
Requirements
- p99 (99th percentile) latency at about 50 ms, which allows at most 1 in 100 requests to exceed it.
- 100 requests per second steady, bursts to 1,000 for short periods.
- Assume the handler does a key lookup and a small computation: about 30 ms average at 1 GB memory. This is an average, not the handler's own p99; a p99 SLO really needs the handler's own p99 (usually higher than its average, since it must also cover the occasional slow cache read), but I use the average as a stand-in for this budget sketch. Confirm the handler's real p99 fits its slice once you have production data. I use the 30 ms assumption throughout; measure yours.
Components
flowchart LR
U[Client] --> E[CDN edge cache]
E -->|miss or uncacheable| G[HTTP API gateway]
G --> F[Function alias with provisioned concurrency]
F --> L1[In-memory L1 per environment]
F --> R[Regional cache]
R -->|miss| DB[Primary datastore]
| Component | Role | Latency and cost note |
|---|---|---|
| CDN edge cache | Serves cacheable GETs near the user with a short TTL (time-to-live) and stale-while-revalidate (serve the cached copy at once while fetching a fresh one in the background) | A hit never touches the function; the cheapest latency there is |
| HTTP API gateway | Auth, routing, throttling per route | HTTP API (API Gateway's lighter, newer API type) at $1.00 per million requests is cheaper than a REST API (API Gateway's older, more feature-rich type, at $3.50 per million); it has no built-in response cache, which the CDN covers |
Function alias (a named pointer, such as live, to one published version of the function) with provisioned concurrency | Pre-initialized environments, no cold start while within the provisioned count | The main latency control and the main cost line |
| L1 in global scope | Hot keys cached per environment for seconds | Free, but hit rate falls as concurrency rises |
| Regional cache (managed Redis, or a cache purpose-built to sit in front of one database and speed up its exact query pattern, such as DynamoDB Accelerator (DAX) for DynamoDB) | Shared cache for all environments | Sub-millisecond to low single-digit ms reads in-region |
| Datastore | Source of truth | Must itself be sized for the miss rate at burst |
Latency budget to design against (targets to verify, not measured figures): edge plus gateway plus network 15 ms, handler 30 ms, leaving about 5 ms of margin. Anything outside this budget, such as a cold start, fails the SLO for that request.
Concurrency: how many warm environments you need
By Little's law, concurrency equals arrival rate multiplied by time in system:
Csteady=100×0.030=3Cburst=1000×0.030=30The small absolute numbers are misleading. What matters is how many requests land on cold environments during a burst. Assume a 500 ms cold start (the platform documents a range of under 100 ms to over a second) and only 3 warm environments when a burst begins at 1,000 requests per second:
arrivals during one init window=1000×0.5=500Within that roughly 500 ms window, every arrival that cannot land on one of the 3 already-warm environments has to start a brand-new one and pay a full cold start, because Lambda gives each concurrent invocation its own execution environment rather than queueing it behind an existing one. The 3 warm environments, reused one request after another, can only push through so many requests in that window: 3 environments divided by 0.030 s per request is their combined throughput (100 requests/second), so over the 0.5 s window they serve:
served warm=0.0303×0.5=50cold≈500−50=450The other 450 arrivals each spin up their own new environment and pay the full cold start. For a 10-second burst of 10,000 requests, 450 cold requests is 4.5%, far above the 1% a p99 can absorb. Each function can add up to 1,000 environments per 10 seconds, so the platform scales fast enough; the problem is purely that each new environment's first request pays the cold start. Hence: provision for the burst, 30 plus headroom, say 40.
Cost versus latency of each choice
AWS Lambda prices, US East, x86, 1 GB, 30-day month (2,592,000 s). Provisioned concurrency is $0.0000041667 per GB-second reserved plus $0.0000097222 per GB-second of execution; on-demand execution is $0.0000166667 per GB-second.
PC reservation (40)=40×1×2,592,000×0.0000041667=$432.00 Steady execution=100×2,592,000×0.030×1=7,776,000 GB-s| Line (per month) | PC = 40 (burst-sized) | PC = 10 (steady plus margin) | On-demand only |
|---|---|---|---|
| PC reservation | $432.00 | $108.00 | $0 |
| Execution, 7,776,000 GB-s | $75.60 at PC rate | $75.60 at PC rate | $129.60 |
| Requests, 259.2M at $0.20 per million | $51.84 | $51.84 | $51.84 |
| HTTP API, 259.2M at $1.00 per million | $259.20 | $259.20 | $259.20 |
| Total | $818.64 | $494.64 plus burst spillover | $440.64 |
| p99 at a burst | Held | Held only if the burst is scheduled or edge-absorbed | Blown during bursts |
(Burst traffic adds a little execution on top of these lines; it is small because bursts are short.)
Is PC = 10 worth its $54.00 premium over on-demand ($494.64 vs $440.64, before spillover)? Only partly. Its 10 pre-warmed environments outrun the 3 that on-demand happens to keep warm at steady state, so in the same opening 0.5 s of a burst they serve 10 / 0.030 x 0.5 = 167 of the first 500 arrivals instead of 50, cutting that window's cold requests from 450 to about 333 (still 3.3% of a 10,000-request burst, above the 1% budget). That is why the table already marks its p99 row "held only if the burst is scheduled or edge-absorbed": PC = 10 softens an organic burst, it does not hold the SLO through one. Pay for it only if that softer landing is worth $54 a month on its own; if the SLO must hold through an unscheduled burst, PC = 40 or the degrade-gracefully steps below are what actually do it. Other choices:
- L1 cache: free; improves hit rate only while concurrency is low.
- Regional cache: a fixed monthly node cost; converts datastore p99 into cache p99. Worth it whenever the datastore p99 alone would eat most of the handler budget.
- Bigger memory: more CPU, shorter handler time; at 1 GB versus 512 MB the per-ms price doubles, so only worth it if duration falls by close to half.
- SnapStart (Lambda restores new environments from a snapshot of an already-initialized one): cheaper than provisioned concurrency and shortens cold starts, but a restored start is still a start; not enough on its own for a 50 ms p99 during bursts.
If cost rules out burst-sized provisioning: degrade gracefully
Commit to this order:
- Absorb at the edge. Make as many responses cacheable as possible with short TTLs and stale-while-revalidate; a burst of reads mostly never reaches the function.
- Pre-warm on a schedule when bursts are predictable (a daily job, a marketing send): scale provisioned concurrency up minutes before and back down after, paying for 40 only for the hours that need it.
- Provision for steady plus margin (10) and let spillover run on-demand, accepting cold starts only for traffic you have classified as tolerant.
- Shed, do not queue. Per-route throttles at the gateway reject low-priority traffic with an immediate HTTP 429 (Too Many Requests) and a
Retry-After, keeping warm capacity for critical routes. A fast, explicit rejection that the client retries with backoff (waiting longer between each successive retry, instead of hammering the service again immediately) is better than a slow timeout. - Serve a degraded response for non-critical fields (cached or default values) when the regional cache or datastore is slow, with a short internal timeout.
What would change the design
If the 100 requests per second baseline is essentially constant, a small always-on container service (two or three tasks behind a load balancer) has no cold starts at all and may cost less than provisioned concurrency plus gateway; I would price that alternative before committing, and choose serverless when idle periods and burst elasticity are real.
Pitfalls
- Sizing provisioned concurrency to the average (3) and discovering the burst's first half-second is all cold starts.
- Forgetting that the gateway line can exceed the function line.
- Letting spillover requests queue behind cold starts instead of shedding them.
- A cache miss storm at burst that moves the bottleneck to the datastore.
Unlock Full Question Bank
Get access to all 27 Serverless and Function-as-a-Service Architecture interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.