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 long-running job (say, a Kubernetes job, or a managed batch or training service) needs to be triggered, tracked, and retried from your serverless layer. How do you pass parameters in, track progress, handle retries and idempotency if it fires twice, and notify on completion? Where does the workflow's own state actually live?
Sample Answer
Direct answer
The serverless function should start the job and then get out of the way. It should never wait for the job. A durable workflow engine (AWS Step Functions Standard, or equivalents such as Azure Durable Functions or Google Workflows) owns the run. The workflow's execution holds the state: the input parameters, the current step, retry counts and results are all stored in its execution history, not in any function's memory.
- A starter (a function or an event rule) starts an execution named after the request id, which makes a duplicate trigger harmless.
- The workflow submits the job through a "run a job and wait" integration, or a callback token (a one-time credential the workflow hands an external worker so that worker, not the workflow, decides when the step is done; covered in detail below).
- It retries defined failures with backoff (each retry waits longer than the last, instead of hammering the dependency again immediately).
- It publishes a completion or failure event that notifies whoever needs to know.
Why not keep this in a function
- A Lambda invocation lasts at most 15 minutes. Training and batch jobs run for hours.
- A function that polls for hours is paying to wait.
- If the environment is recycled, whatever it held in memory is gone.
A Standard workflow can run for up to a year, and it records every state transition.
Passing parameters in
- The execution input (JSON, up to 256 KiB: a kibibyte is 1,024 bytes, so about 256,000 bytes) carries the request id, the job type, and pointers to the data: input and output URIs.
- Large configuration or datasets travel by claim check: store them in object storage and pass the URI.
- The workflow maps the input into the job's own parameters (container environment variables, a Kubernetes Job spec, training hyperparameters).
Tracking progress
| Signal | Mechanism | Granularity |
|---|---|---|
| Which step the run is on | The workflow's execution status and history | Coarse, always available |
| Did the job finish | A .sync integration (the .sync suffix appended to the Resource ARN, shown below, tells Step Functions to submit the job and then wait, instead of firing it and moving straight to the next step): Step Functions waits and moves on when the job reaches a final state | Coarse |
| Percent complete, current epoch | The job writes a progress record (a key-value table item keyed by request id) that the UI reads | Fine |
| Is the job still alive | Callback pattern with a task token (a unique string Step Functions generates for this step and hands to whoever will eventually finish it; the workflow pauses right there until that same token is handed back): the job calls SendTaskHeartbeat (an API meaning "still working, do not time me out") on a schedule, and HeartbeatSeconds (the longest gap Step Functions allows between heartbeats) fails the task if heartbeats stop | Liveness |
Integration details matter.
- Step Functions' Amazon EKS (Elastic Kubernetes Service, managed Kubernetes)
runJob.syncintegration detects completion by polling: about once a minute at first, slowing to about once every 5 minutes. So completion can be noticed several minutes late. - The EKS integration does not support the callback pattern (the task-token approach above), and it only works with clusters whose Kubernetes API endpoint is public.
- For a private cluster, use callback instead. The workflow sends a message containing its task token to a queue:
sqs:sendMessage.waitForTaskTokenis the Resource suffix that tells Step Functions "send this message, then pause the state machine right here until someone calls back with this token." An in-cluster worker (something running inside the private cluster, able to reach it) picks the message off the queue, runs the Kubernetes job, and callsSendTaskSuccessorSendTaskFailure, passing the same token back, to tell Step Functions which paused execution to resume and how. - AWS Batch (a managed batch-job scheduler) and Amazon SageMaker (a managed machine learning platform) training jobs support
.syncdirectly.
Retries
- Infrastructure failures (spot capacity reclaimed: the cloud provider taking back the cheaper, interruptible compute it lent you, or a node lost) are retried closest to the job: AWS Batch's job
retryStrategy(how many times Batch itself resubmits the same job attempt before giving up), or KubernetesbackoffLimit(the same idea for a Kubernetes Job: how many failed pod attempts it tolerates). - Workflow-level
Retrycovers failures of the task itself, withIntervalSeconds,BackoffRateandMaxAttempts. - Bad input is not retried. A
Catchroutes it to the failure notification. - A
TimeoutSecondson the job state turns a job that hangs silently into a visible failure.
This is written in the Amazon States Language, the JSON-based language Step Functions state machines are defined in. A few conventions used below: a field ending in .$ (like JobName.$) takes a JSONPath expression instead of a literal value, so "$.requestId" means "read the requestId field out of this state's input," not the literal string $.requestId. Resource names the action to call using an ARN (Amazon Resource Name: AWS's standard way of pointing at one specific resource or action); the .sync on the end of arn:aws:states:::batch:submitJob.sync is what makes this state submit the job and wait, as described above. ResultPath: "$.job" tells Step Functions to write this state's output into a new job field alongside the existing input, instead of replacing the input outright, so later states can still read $.requestId and everything else. In plain terms, the numbers below mean: give the job up to TimeoutSeconds: 43200 (12 hours) to finish; on a States.TaskFailed error, wait IntervalSeconds: 60 (1 minute) and retry, and if it fails again wait 60 x BackoffRate: 2.0 = 120 seconds before the second and last retry (MaxAttempts: 2); anything else (States.ALL) skips retrying and goes straight to NotifyFailure. The two NotifySuccess/NotifyFailure states each publish to an SNS topic (Amazon Simple Notification Service, a managed pub/sub notification service; TopicArn is that topic's ARN).
{
"Comment": "Run one job per request and notify",
"StartAt": "RunJob",
"States": {
"RunJob": {
"Type": "Task",
"Resource": "arn:aws:states:::batch:submitJob.sync",
"Parameters": {
"JobName.$": "$.requestId",
"JobQueue": "arn:aws:batch:us-east-1:111122223333:job-queue/training",
"JobDefinition": "arn:aws:batch:us-east-1:111122223333:job-definition/train:3",
"ContainerOverrides": {
"Environment": [
{ "Name": "INPUT_URI", "Value.$": "$.inputUri" },
{ "Name": "OUTPUT_URI", "Value.$": "$.outputUri" }
]
}
},
"ResultPath": "$.job",
"TimeoutSeconds": 43200,
"Retry": [
{ "ErrorEquals": ["States.TaskFailed"], "IntervalSeconds": 60, "BackoffRate": 2.0, "MaxAttempts": 2 }
],
"Catch": [
{ "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "NotifyFailure" }
],
"Next": "NotifySuccess"
},
"NotifySuccess": {
"Type": "Task",
"Resource": "arn:aws:states:::sns:publish",
"Parameters": {
"TopicArn": "arn:aws:sns:us-east-1:111122223333:job-events",
"Message.$": "States.Format('request {} succeeded', $.requestId)"
},
"End": true
},
"NotifyFailure": {
"Type": "Task",
"Resource": "arn:aws:states:::sns:publish",
"Parameters": {
"TopicArn": "arn:aws:sns:us-east-1:111122223333:job-events",
"Message.$": "States.Format('request {} failed', $.requestId)"
},
"Next": "Failed"
},
"Failed": { "Type": "Fail" }
}
}
Idempotency when the trigger fires twice
Handle it at three levels:
- The execution name is the request id. For Standard workflows, starting an execution with a name and input that match a running execution returns that same execution. If the execution has already closed, the call fails with
ExecutionAlreadyExists, which the starter treats as "already done". Express workflows (a cheaper, higher-throughput Step Functions mode built for short-lived, high-volume executions, with at-least-once semantics and no long execution history) do not give this guarantee, which is one more reason to use Standard here. - The job name or output path is deterministic. Reusing the request id as the job name (and as the output prefix) means a manual re-run overwrites rather than duplicates. Some services enforce this for you: a SageMaker training job name must be unique in the account and Region, so a second create with the same name is refused.
- Consumers of the completion event can deduplicate on the request id, because the notification itself can also arrive twice.
Notifying on completion
- The final states publish to a topic or event bus, as in the definition above.
- Step Functions also emits execution status-change events to EventBridge, so downstream systems can subscribe without the workflow knowing about them.
- Notify on failure as well as success. A job that fails silently is the common incident.
Where the state actually lives
| State | Lives in |
|---|---|
| Request record (who asked, for what) | A database table keyed by request id, for API lookups |
| Workflow progress, retries, step results | The workflow execution's history |
| Job-internal progress and checkpoints | The job's own storage (object storage checkpoints) plus the progress record |
| Logs | The job's log stream |
| In any function | Nothing that must survive the invocation |
sequenceDiagram
participant API as Starter function
participant WF as Workflow execution
participant JOB as Batch or Kubernetes job
participant BUS as Topic or event bus
API->>WF: StartExecution(name = requestId, input)
WF->>JOB: submit job and wait
JOB-->>WF: final state SUCCEEDED or FAILED
WF->>BUS: publish completion or failure
Pitfalls
- A function polling job status in a loop. It costs money, times out at 15 minutes, and loses its state.
- Random execution names. Every duplicate trigger then starts a new, expensive job.
- Retrying everything, including jobs that failed on bad input.
- Stopping the workflow and assuming the job stopped. Step Functions only makes a best-effort attempt to cancel
.syncjobs, so a stopped execution can leave a job running and billing.
Write language-agnostic pseudo-code for a wrapper that measures and emits two metrics per invocation: time spent in initialization (cold-start setup), and time spent in the handler itself. How does your wrapper tell a cold invocation apart from a warm one, and how would it push these metrics to a monitoring backend?
Sample Answer
Direct answer
Record a timestamp at the very first line of module-level code, record another when module-level setup finishes, and keep a module-level flag cold = true. Module-level code runs exactly once per execution environment, so the first invocation that sees cold == true is the cold one: it reports init duration (the two timestamps' difference) and flips the flag; every later invocation in that environment is warm. Around the handler, time from entry to exit in a finally block so failures are measured too. To push metrics, don't call a metrics API synchronously from the request path; write one structured log line per invocation in a format the backend turns into metrics (on AWS, CloudWatch, the account's monitoring and log service, reads log lines written in its Embedded Metric Format, EMF, and turns them into metrics on its own), or hand the data to a local agent that ships it asynchronously.
Pseudo-code (language-agnostic)
# ---- module scope: runs once per execution environment ----
INIT_START = monotonic_now()
COLD = true
... imports, clients, config, large dependency ...
INIT_END = monotonic_now()
function wrap(handler):
return function(event, context):
start = monotonic_now()
was_cold = COLD
COLD = false # every later call in this environment is warm
try:
return handler(event, context)
finally: # measured on success and on exception
metrics = { HandlerDuration: ms(monotonic_now() - start) }
if was_cold:
metrics.InitDuration = ms(INIT_END - INIT_START)
metrics.InitToFirstInvokeGap = ms(start - INIT_END)
emit(metrics, dimensions = { FunctionName, ColdStart: was_cold })
Use a monotonic clock (one that never jumps when the system clock is corrected) for durations, and wall-clock time only for the metric's timestamp.
Runnable implementation
The wrapper takes the clock as a parameter so the demo can use a fake, deterministic clock; in production you pass time.monotonic_ns. emit prints an EMF document: a JSON log line with an _aws block telling CloudWatch which fields are metrics and which are dimensions (the labels a metric is grouped by).
import json, os, time
class FakeClock:
"""Deterministic clock for the demo. In production pass time.monotonic_ns."""
def __init__(self):
self.ns = 0
def __call__(self):
return self.ns
def advance_ms(self, ms):
self.ns += int(ms * 1_000_000)
class ColdStartMetrics:
def __init__(self, namespace, function_name, clock=time.monotonic_ns,
wall_ms=lambda: int(time.time() * 1000), sink=print):
self.clock, self.wall_ms, self.sink = clock, wall_ms, sink
self.namespace, self.function_name = namespace, function_name
self.init_type = os.environ.get("AWS_LAMBDA_INITIALIZATION_TYPE", "on-demand")
self.init_start = clock() # first line of module scope
self.init_end = None
self.cold = True # module scope runs once per environment
def init_done(self):
self.init_end = self.clock()
def wrap(self, handler):
def wrapped(event, context):
start = self.clock()
was_cold, self.cold = self.cold, False
try:
return handler(event, context)
finally: # runs on success and on exceptions
handler_ms = (self.clock() - start) / 1e6
fields = {"HandlerDuration": round(handler_ms, 3)}
if was_cold:
fields["InitDuration"] = round((self.init_end - self.init_start) / 1e6, 3)
fields["InitToFirstInvokeGap"] = round((start - self.init_end) / 1e6, 3)
self.emit(fields, was_cold)
return wrapped
def emit(self, fields, was_cold):
doc = {
"_aws": {
"Timestamp": self.wall_ms(),
"CloudWatchMetrics": [{
"Namespace": self.namespace,
"Dimensions": [["FunctionName", "ColdStart"]],
"Metrics": [{"Name": k, "Unit": "Milliseconds"} for k in fields],
}],
},
"FunctionName": self.function_name,
"ColdStart": "true" if was_cold else "false",
"InitType": self.init_type, # logged property, not a dimension
**fields,
}
self.sink(json.dumps(doc, separators=(",", ":")))
# ---- demo driver: simulate one environment's life with a pinned clock ----
clock = FakeClock()
metrics = ColdStartMetrics("MyApp", "resize-images", clock=clock, wall_ms=lambda: 1767225600000)
clock.advance_ms(850) # module-scope work: imports, SDK clients, config load
metrics.init_done()
def handler(event, context):
clock.advance_ms(event["work_ms"])
if event.get("fail"):
raise RuntimeError("downstream timeout")
return {"ok": True}
h = metrics.wrap(handler)
clock.advance_ms(2) # time between init finishing and the first request
h({"work_ms": 120}, None) # cold
clock.advance_ms(5000) # environment frozen, then thawed
h({"work_ms": 95}, None) # warm
try:
h({"work_ms": 40, "fail": True}, None) # warm, handler raises
except RuntimeError as e:
print("handler error propagated:", e)
Output:
{"_aws":{"Timestamp":1767225600000,"CloudWatchMetrics":[{"Namespace":"MyApp","Dimensions":[["FunctionName","ColdStart"]],"Metrics":[{"Name":"HandlerDuration","Unit":"Milliseconds"},{"Name":"InitDuration","Unit":"Milliseconds"},{"Name":"InitToFirstInvokeGap","Unit":"Milliseconds"}]}]},"FunctionName":"resize-images","ColdStart":"true","InitType":"on-demand","HandlerDuration":120.0,"InitDuration":850.0,"InitToFirstInvokeGap":2.0}
{"_aws":{"Timestamp":1767225600000,"CloudWatchMetrics":[{"Namespace":"MyApp","Dimensions":[["FunctionName","ColdStart"]],"Metrics":[{"Name":"HandlerDuration","Unit":"Milliseconds"}]}]},"FunctionName":"resize-images","ColdStart":"false","InitType":"on-demand","HandlerDuration":95.0}
{"_aws":{"Timestamp":1767225600000,"CloudWatchMetrics":[{"Namespace":"MyApp","Dimensions":[["FunctionName","ColdStart"]],"Metrics":[{"Name":"HandlerDuration","Unit":"Milliseconds"}]}]},"FunctionName":"resize-images","ColdStart":"false","InitType":"on-demand","HandlerDuration":40.0}
handler error propagated: downstream timeout
The first line is the cold invocation (850 ms init, 2 ms gap before the first request, 120 ms handler). The next two are warm and carry only HandlerDuration. The third invocation raised an exception, and its metric was still emitted before the error propagated. Notice what the _aws.CloudWatchMetrics[0].Dimensions list is doing: [["FunctionName", "ColdStart"]] tells CloudWatch to turn those two fields into metric labels you can filter and group a graph by. InitType sits outside that list, so CloudWatch stores it as a plain property on the log entry, searchable in Logs Insights but not usable to split a metric.
How cold versus warm detection works, and where it breaks
- Why the flag works. The runtime imports your module once per environment. If the environment crashes or times out, Lambda resets it and re-runs module code, so the flag correctly resets to
true. - Provisioned concurrency and pre-initialization. Provisioned concurrency is a Lambda setting that pays to keep a chosen number of environments already initialized and sitting idle, ready before any request arrives, instead of only initializing one when a request shows up needing it. So an environment can be initialized long before the first request. The first request is then "first in this environment" but the user did not wait for init. That is why the wrapper also emits
InitToFirstInvokeGapand logsAWS_LAMBDA_INITIALIZATION_TYPE(on-demand, meaning an environment created on demand by an incoming request;provisioned-concurrency;snap-start, covered next; orlambda-managed-instances, an instance type where Lambda runs your function on capacity you provision and one execution environment can serve more than one concurrent invocation). A user-visible cold start isColdStart=truewith a gap near zero. - SnapStart. SnapStart is a Lambda feature that initializes one environment fully, freezes a snapshot of its memory and disk state once that init finishes, and boots every later environment for that function by restoring from that snapshot instead of re-running your module code. Because module code never runs again in a restored environment, the
COLDflag is lefttrueinside the snapshot itself (init ran once, before the snapshot was taken), so every environment that restores from it starts already believing it is cold, and reports the same staleInitDurationthe original environment measured, not its own. Worse,INIT_STARTandINIT_ENDwere read from a monotonic clock (a clock that only measures elapsed time going forward on the machine that reads it, never wall time) running on the environment that made the snapshot, so a reading taken before the snapshot cannot say anything about how long this restored environment took to come up; the clock's origin point is frozen into the snapshot along with everything else. Lambda gives you an escape hatch for this: an after-restore runtime hook, a callback the runtime invokes once a restore finishes and before the handler runs again, where you can reset the timers. Then take the real start-up cost from the platform instead of your own clock: for SnapStart functions, theREPORTlog line AWS writes after each invocation carries aRestore Durationfield (the time to thaw the snapshot and run your after-restore hook), and AWS defines the user-visible cold-start duration for these functions asRestore DurationplusDuration(the handler's own run time). - What the wrapper cannot see. Code download, sandbox start and runtime boot happen before your first line runs. The platform's own
Init Durationfield on theREPORTlog line covers the whole Init phase, and theDurationmetric excludes init, so compare the two: platform init minus your init is the part you cannot optimize from code. - Timeouts. When a function times out, the runtime is stopped before
finallyruns, so no metric is emitted. Detect those from the platform'sREPORTline (it carriesStatus: timeout) or theErrorsmetric.
Pushing to a monitoring backend
| Option | How | Trade-off |
|---|---|---|
| Structured log line (EMF on AWS) | Print the JSON; CloudWatch Logs extracts metrics asynchronously. | No network call in the request path and no extra API cost per call. Metrics appear with log-ingestion delay; delivery is at least once, so rare duplicates are possible. |
Synchronous metrics API call (for example CloudWatch PutMetricData) | Call the API before returning. | Adds a network round trip to every invocation's latency and bill, and a failed call can fail the request. Avoid in the hot path. |
| Local agent or extension (an OpenTelemetry collector, OpenTelemetry being the open standard for traces, metrics and logs, running as a Lambda extension; or a vendor extension) | Send to a local process that batches and flushes. | Keeps vendor neutrality and batching; costs extra init time and memory, and flush time at shutdown. |
Cardinality. Every distinct combination of dimension values becomes a separate billed metric. FunctionName and ColdStart (two values) are safe; putting request IDs or user IDs in dimensions creates millions of metrics. High-cardinality fields go in the log line as properties (like InitType here), not dimensions.
Complexity and edge cases
- Cost: O(1) time per invocation and one log line; memory O(1).
- Edge cases: exceptions (handled by
finally); timeouts (not visible to the wrapper, use platform logs); SnapStart restores (reset timers after restore); provisioned concurrency (use the gap and init type to separate "first in environment" from "user waited"); clock adjustments (monotonic clock only for durations).
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.
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 are your options for packaging a runtime and its dependencies into a serverless function: a plain zip deployment, layers, or a container image? For a large dependency, when would you prefer a container image over the other two, and how does image size affect cold-start time?
Sample Answer
Direct answer
On AWS Lambda there are three ways to ship a function's runtime and dependencies: a zip archive (code plus dependencies, up to 250 MB unzipped), layers (separately versioned zip archives, up to five, attached to a zip function and counted inside the same 250 MB), or a container image (your own image, up to 10 GB). For a large dependency I prefer the container image once the dependency pushes the unzipped total past about 250 MB, needs operating-system packages or native libraries (compiled, OS-specific binary libraries, unlike pure-language packages that run anywhere the language does) you can't easily bundle, or when the team already builds, scans and tests containers. Image size by itself affects cold start less than intuition suggests: Lambda loads image contents in chunks as the code reads them and caches them, so what drives cold start is how much of the image your initialization actually reads, plus runtime start-up.
The three options
| Zip archive | Zip + layers | Container image | |
|---|---|---|---|
| What it is | One .zip with your code and dependencies | Your code in the function zip; shared dependencies in up to 5 layer zips, extracted under /opt | An OCI (Open Container Initiative, the standard container format) image in Amazon ECR (Elastic Container Registry), same Region as the function |
| Size limit | 50 MB zipped for direct upload (larger via S3); 250 MB unzipped | 250 MB unzipped for function plus all layers combined | 10 GB uncompressed |
| Sharing | None; each function carries its own copy | A layer version can be attached to many functions | Shared base images and layers within the registry |
| Update model | Redeploy the zip | Publish a new immutable layer version, then point each function at it | Rebuild and push the image; Lambda optimizes it (function is Pending, then Active) before it can be invoked |
| Local testing | Simulated | Simulated | Run the same image locally (AWS base images include a runtime interface emulator, a small local server that mimics Lambda's own invoke API so you can send the image a test event over plain HTTP on your laptop) |
| Best for | Small functions, fast iteration | Several zip functions sharing a common dependency, or pinning a library version | Large or native dependencies, custom runtimes, container-based toolchains |
Two rules of thumb: layers are a sharing and organization tool, not a way around the size limit (their contents count toward the same 250 MB), and layers cannot be used with container images (bake dependencies into the image instead). AWS also recommends against layers for Go and Rust, where the compiled binary should include its dependencies.
One naming collision to flag now, because the word comes back later in this answer: a container image has its own, unrelated thing also called a "layer." An image is built from a Dockerfile, a script of instructions (FROM a base image, then steps like RUN or COPY), and each instruction adds one filesystem layer stacked on the one before it. Docker caches each built layer by its inputs and reuses that cache unchanged across builds; the moment one instruction's inputs change, that instruction's layer and every layer stacked after it must rebuild. These image layers are what "one early layer" and "layer order in the Dockerfile" mean further down. They are a build-caching detail of how an image is assembled, not the Lambda layers just described, and the two never interact: an image layer is never one of the five zip layers a function can attach.
When a container image wins for a large dependency
- It doesn't fit. A dependency stack such as a scientific library plus native math libraries easily passes 250 MB unzipped. Here, the image is the only packaging option inside Lambda (the alternatives are fetching at start-up or mounting a file system).
- It needs system packages (a specific
glibc, the GNU C library most Linux programs are compiled against, where different base images ship different versions; image codecs; a headless browser, a full browser engine such as Chromium run with no visible window, often used to render pages to PDF or screenshots). An image lets you install them with the package manager at build time. - You want one artifact from laptop to production, scanned by the same container security tooling as your other services.
Stick with zip when the function is small and the dependency fits comfortably: zip functions are simpler to deploy and have no registry to manage.
How image size affects cold start
A cold start has to make your code's files available, start the runtime and run your initialization. For images, AWS has described (USENIX ATC 2023 paper "On-demand Container Loading in AWS Lambda") how Lambda breaks images into chunks, deduplicates chunks shared across images (such as a common base image), caches them in several tiers and fetches only the chunks the process reads. Consequences:
- Unread bytes are nearly free at cold start. A 3 GB image whose init reads 200 MB behaves more like a 200 MB load than a 3 GB one.
- Read bytes still cost. If init imports a 1.5 GB library tree or reads a 1 GB data file, those chunks must be fetched on a cache miss, meaning Lambda's chunk cache does not already hold that piece from a previous invocation on this host; 1 GiB over the documented 625 Mbps per-environment network limit is 8,589,934,592 bits / 625,000,000 bits/s = 13.7 s in the worst case.
- Common image layers are cheaper. AWS base images are cached ahead of time by Lambda, so
FROM-ing one of them (rather than building the same packages yourself) avoids fetching those shared image layers on first use. - Size still matters at deploy time. Bigger images take longer to push and to optimize before the function becomes
Active, and a function unused for weeks goesInactiveand must be re-optimized.
Worked example
A document-processing function needs 150 MB of code and libraries plus a 600 MB OCR (optical character recognition) engine with native libraries.
- Zip + layers: 750 MB exceeds 250 MB unzipped, so it's out.
- Container image on an AWS Python base image:
FROMthe base image, install the native libraries in one early image layer, the 600 MB engine in the next image layer, and application code last. A code change then only invalidates and rebuilds that final layer, reusing the cached native-library and engine layers underneath it (the build-caching behavior explained above, not a Lambda layer). - Cold start check: measure
Init Durationin theREPORTlog line. If init imports the whole engine eagerly, move rarely used language packs behind lazy loading, which cuts the bytes read at start-up.
Pitfalls
- Treating layers as extra capacity. They share the 250 MB unzipped ceiling with the function.
- Image layer order in the Dockerfile. This is about the Docker build-caching layers from above, not Lambda layers. Changing an instruction invalidates its image layer and every image layer built after it, so put the stable, large content first and your frequently changing code last.
- Many small image layers. AWS advises keeping the image manifest, the JSON index that lists every layer and piece of metadata making up the image, small: fewer layers, and fewer annotations (the manifest's own key-value metadata tags), for performance.
- Forgetting the runtime interface client. A non-AWS base image must include a runtime interface client, the runtime-side counterpart to the runtime interface emulator mentioned in the table above: the client is what actually talks to Lambda's Runtime API in production, while the emulator is only for testing the image locally. Without the client baked in, the function cannot receive events.
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.