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.
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.
What practical strategies would you use to reduce vendor lock-in when designing a serverless deployment? Consider your options around portable packaging, workflow-orchestration choice, infrastructure-as-code portability, and abstraction layers between your code and the platform, and weigh those against the added operational complexity, latency, or delayed feature access that comes with staying portable.
Sample Answer
Direct answer
I would not try to make a serverless system fully portable. That costs a lot and throws away most of what serverless offers. Instead I keep the business logic portable and let the edges be native: put domain code behind a thin handler adapter, ship functions as standard container images, keep data in open formats, and choose portable tools only where a move would otherwise mean a rewrite (mainly workflow orchestration). Then I write down an exit plan with a cost estimate, so lock-in is a known, priced risk instead of a vague fear.
Terms:
- Vendor lock-in: the cost (time, money, risk) of moving off a provider. It is never zero; the goal is to keep it proportional to the value you get.
- Serverless / FaaS (functions as a service): provider-run functions triggered by events and billed per invocation, for example AWS Lambda, Azure Functions, Google Cloud Run functions.
- IaC (infrastructure as code): declaring cloud resources in files that a tool applies, for example Terraform or AWS CloudFormation.
- Workflow orchestrator: a service that runs multi-step processes with retries and state, for example AWS Step Functions.
Where lock-in actually lives
Rank the layers by how expensive they are to move, because that is where portability effort pays off:
| Layer | Typical lock-in | Cost to move |
|---|---|---|
| Data (databases, queues, event history) | Proprietary APIs and data models (for example the key design of DynamoDB, AWS's managed key-value database), large data volumes to transfer | Highest |
| Workflow definitions | Step Functions uses Amazon States Language (ASL), a JSON workflow format only AWS runs | High: rewrite every workflow |
| Event wiring and identity | Trigger configuration, event payload shapes, IAM (AWS Identity and Access Management) policies | Medium |
| Function code | Handler signature, SDK calls | Low if the logic is separated from the handler |
| Packaging | Zip formats and layers are provider-specific | Low if you use container images |
The four levers, and my choice for each
1. Portable packaging
- Package functions as OCI container images (OCI, the Open Container Initiative image format that Docker produces). Lambda, Google Cloud Run and Azure Functions (on hosting plans that support custom containers) all run container images, and the same image runs locally for tests.
- For HTTP services, the open-source AWS Lambda Web Adapter lets an ordinary web app (Flask, FastAPI, Express, Spring Boot) run on Lambda unchanged, so the same image also runs on a container platform such as Fargate (AWS's serverless container runtime) or Kubernetes (an open-source system for running and scaling containers across a cluster of machines).
- Cost: depending on image size, container images can have slower cold starts than small zip packages (the platform has to fetch and start a larger artifact), so keep images slim, and measure.
- Choice: container images for anything non-trivial; zip packages only for tiny glue functions where a rewrite would take an afternoon anyway.
2. Workflow orchestration
- Step Functions is excellent (visual, managed, deeply integrated with AWS services) and the definitions are AWS-only.
- A portable alternative is Temporal, an open-source workflow engine where workflows are ordinary code; it runs self-hosted or as a managed cloud service and on any provider. The cost is that you operate a cluster (or pay for the managed offering), and you lose Step Functions' built-in, no-code integrations with many AWS services.
- Choice: Step Functions for short, glue-like workflows (a handful of states, mostly calling AWS services), where a rewrite would be small. Temporal (or equivalent code-first engine) when workflows are the core of the business (long-running order or claims processes with dozens of steps), because rewriting those is the single largest item in any exit plan.
3. IaC portability
- An important nuance candidates often miss: Terraform (or its open-source fork OpenTofu) makes the tool and the workflow portable, not the resources. An
aws_lambda_functionresource does not become an Azure function by changing the provider. What you gain is one language, one plan/apply workflow (write the desired resources, preview the changes the tool would make, then apply them) and one state model (the tool's own record of what it has already created, so it knows what to change versus create) across clouds, so the team's skills transfer. - AWS CDK (a framework that generates CloudFormation from TypeScript or Python) and CloudFormation are AWS-only.
- Choice: Terraform/OpenTofu if multi-cloud is a real possibility or the organization already uses it; otherwise use whatever the team is fastest with, and accept that IaC gets rewritten on a move regardless. It is rarely the expensive part.
4. Abstraction layers between code and platform
- Ports and adapters (hexagonal architecture, named because the domain sits in the middle of the diagram with an adapter hanging off each face): domain logic depends on interfaces you own (
OrderRepository,EventPublisher); a thin adapter per platform implements them. The handler just parses the provider's event, calls the domain, and formats the response. Concretely:
# handler (adapter): one version per platform, knows only the event shape
def lambda_handler(event, context):
order_id = event["pathParameters"]["orderId"]
order = create_order(order_id, OrderRepository(), EventPublisher())
return {"statusCode": 200, "body": order.to_json()}
# domain (portable): knows nothing about Lambda, API Gateway, or AWS
def create_order(order_id, repo, publisher):
order = repo.save(order_id)
publisher.publish("order.created", order)
return order
Move to a container: write a new container_handler(request) that unpacks an HTTP request instead of a Lambda event and calls the same create_order. create_order itself, and its tests, do not change.
- Standard event envelope: wrap events in CloudEvents (a CNCF, Cloud Native Computing Foundation, specification for describing events in a common format) so consumers do not depend on each provider's payload shape.
- Where to stop: do not wrap managed services in lowest-common-denominator abstractions (a "generic queue" that hides SQS's (Amazon Simple Queue Service, AWS's managed message queue) visibility timeout, how long a delivered message is hidden from other consumers before it is treated as failed and redelivered, and FIFO, first-in first-out, groups). You lose the features you chose the service for, and you still have to rewrite semantics on a move because two queues never behave identically.
- Choice: adapters around your own code, always. Abstraction over managed services, only for the two or three you would realistically swap.
Worked example: an exit-cost inventory
A team runs 30 Lambda functions, 3 Step Functions workflows (8, 12 and 40 states), 4 DynamoDB tables, SQS and SNS (AWS's managed queue and pub/sub topic services), and API Gateway (AWS's managed HTTP front door). An exit plan lists each item with a move strategy and a rough effort, estimated by the team:
| Item | Portable already? | Move strategy | Effort (team estimate, illustrative engineer-days) |
|---|---|---|---|
| 30 functions as container images, logic behind adapters | Mostly | New adapters per function; same images | Small per function, about 0.5 day each (15 days total) |
| 8- and 12-state workflows | No | Rewrite in the target orchestrator | Days each (3 and 4 days) |
| 40-state claims workflow | No | Rewrite, plus re-test every failure path | Weeks, highest risk (about 15 days) |
| 4 DynamoDB tables | No | Re-model keys and access patterns for the target database, then migrate data with dual writes (writing every change to both the old and new database during the migration, then cutting traffic over once they agree) | Weeks, plus migration risk (about 20 days) |
| SQS/SNS | Semantically close equivalents exist | Adapter change plus retry and ordering testing | Days (about 3) |
| API Gateway | No | Replace routes and auth configuration | Days (about 2) |
Those figures are the team's own planning estimate, not a measurement, and total about 62 engineer-days. The inventory makes the decision concrete: two items, the 40-state workflow (about 15 days) and the DynamoDB migration (about 20 days), are 35 of those 62 days, 56%, most of the exit cost. That is where portability spending pays: moving that one workflow to a code-first engine and keeping the data access behind a repository interface, while leaving the small workflows and glue native.
Weighing the cost of staying portable
| Cost of portability | What it looks like | How to keep it small |
|---|---|---|
| Operational complexity | Running Temporal or Kubernetes-based FaaS (for example Knative, an open-source layer that adds scale-to-zero functions on top of Kubernetes) yourself | Use managed versions; apply only to the highest-exit-cost items |
| Latency | Extra adapter layers are negligible; an extra network hop (a self-hosted gateway, a sidecar, a helper container that runs alongside your service in the same pod and intercepts or augments its traffic) is not | Keep abstractions in-process, not as extra services |
| Delayed feature access | A generic layer cannot use new provider features (new event sources, native integrations) until you extend it | Let adapters expose provider-specific options instead of hiding them |
| Engineering time | Building and maintaining abstractions nobody uses unless you move | Build adapters for your code; skip abstractions over services you will never swap |
Trade-offs and pitfalls
- "Multi-cloud from day one" usually doubles the work for a move that never happens. Portability should be proportional to a real probability of moving (regulation, acquisition, price leverage, a customer requirement).
- Treating Terraform as portability. It is a skills and workflow benefit, not a resource-migration tool.
- Ignoring data gravity, the tendency for code and services to cluster near a large dataset because moving the data, not the code, is the expensive part of a move. Code moves in weeks; terabytes of data in a proprietary data model are the real anchor. Open formats (Parquet, a column-oriented file format for structured data that many query engines can read directly, in object storage) and a repository interface do more for portability than any compute abstraction.
- Forgetting the exit plan is a living document. Revisit it when a new proprietary service is adopted, because each one adds a line to the exit cost.
Write pseudo-code for a serverless function that consumes from a message queue and batches incoming items into groups of up to 16, or after a 50ms wait, whichever comes first, before processing the batch. How is this safe when multiple instances of the function are running concurrently, and what assumptions are you making about the queue's semantics (visibility timeout, deletion)?
Sample Answer
Direct answer
Each consumer builds its own batch from messages it has received. It flushes when the batch reaches 16 items or when 50 ms have passed since the first item arrived, whichever comes first. It processes the batch, then deletes only the messages that succeeded, using each message's latest receipt handle (a one-time token the queue hands back on every receive; a delete must present the receipt from the most recent receive, not an older one, or it is rejected as stale).
Running many consumers at once is safe because of three things the code relies on:
- The queue hides a received message from other consumers for the visibility timeout, so instances work on disjoint messages without any lock.
- A message is deleted only after it has been processed.
- Processing is idempotent (running it twice on the same message has the same effect as running it once). The queue is at-least-once, meaning a message can be delivered more than once, so a message can still arrive twice.
No batch state is shared between instances, and none needs to be.
One practical catch: on AWS Lambda's managed trigger for Amazon SQS (Simple Queue Service) you cannot configure "16 or 50 ms". A batch size above 10 requires a batching window of at least 1 second, and the window is set in whole seconds. So you either accept a 1 s window (configuration only), or you run the 16-or-50 ms loop yourself as a poller. The loop is what the question asks for, so that is what the code shows.
Approach
State per consumer: batch (list) and first_at (when the first item of the current batch arrived).
- Receive up to
min(10, 16 - len(batch))messages. One receive call returns at most 10, so a 16-item batch always needs at least two calls. - If this is the first item, start the 50 ms clock.
- Flush if
len(batch) == 16(reason: size) ornow - first_at >= 50 ms(reason: time). - Process the batch. For each success, write the result with an idempotent upsert (insert-or-update: write the row if it does not exist, overwrite it if it does, so writing the same result twice leaves the same final state as writing it once) keyed by message id or business key, then delete with that message's receipt handle.
- Anything not deleted becomes visible again after the visibility timeout and is retried. After
maxReceiveCount(a threshold on how many times a message can be received before it is given up on) failures it moves to a dead-letter queue (DLQ: a separate queue that catches messages nobody could process, so one bad message does not block or endlessly retry against the main queue).
Runnable simulation
It runs deterministically on a simulated clock, so it needs no AWS account. A fake queue models the two properties that matter: a received message is hidden for vis_ms, and a delete only works with the latest receipt handle. Three consumers compete for 500 messages. In the second run, one batch takes 1,500 ms, longer than the 1,000 ms visibility timeout.
import random
from collections import Counter
class FakeQueue:
"""Minimal SQS-like queue: receive hides a message for vis_ms, delete needs the LATEST receipt."""
def __init__(self):
self.msgs = {} # id -> dict(body, visible_at, receipt, receives)
self.next_receipt = 0
def send(self, mid, body, now):
self.msgs[mid] = {"body": body, "visible_at": now, "receipt": None, "receives": 0}
def receive(self, now, max_n, vis_ms):
out = []
for mid in sorted(self.msgs):
m = self.msgs[mid]
if m["visible_at"] <= now and len(out) < max_n:
self.next_receipt += 1
m["receipt"], m["visible_at"] = self.next_receipt, now + vis_ms
m["receives"] += 1
out.append((mid, m["body"], self.next_receipt))
return out
def delete(self, mid, receipt):
m = self.msgs.get(mid)
if m is None or m["receipt"] != receipt:
return False # already gone, or a newer receive owns it (stale handle)
del self.msgs[mid]
return True
class Consumer:
MAX_BATCH, MAX_WAIT_MS = 16, 50
def __init__(self, name, q, sink, vis_ms, work_ms):
self.name, self.q, self.sink, self.vis_ms, self.work_ms = name, q, sink, vis_ms, work_ms
self.batch, self.first_at, self.busy_until = [], None, -1
self.flushes, self.stale_deletes, self.dup_writes = Counter(), 0, 0
self.pending = []
def tick(self, now):
if now < self.busy_until:
return
if self.pending: # processing finished: write, then delete
for mid, body, rc in self.pending:
if mid in self.sink:
self.dup_writes += 1
self.sink[mid] = body # idempotent upsert keyed by message id
if not self.q.delete(mid, rc):
self.stale_deletes += 1
self.pending = []
want = self.MAX_BATCH - len(self.batch)
got = self.q.receive(now, min(10, want), self.vis_ms) # one receive returns at most 10
if got and self.first_at is None:
self.first_at = now
self.batch += got
full = len(self.batch) == self.MAX_BATCH
timed_out = self.batch and now - self.first_at >= self.MAX_WAIT_MS
if full or timed_out:
self.flushes["size" if full else "time"] += 1
self.pending, self.batch, self.first_at = self.batch, [], None
work = self.work_ms(self.name, self.flushes)
self.busy_until = now + work
def run(stall):
rng = random.Random(7)
q, sink = FakeQueue(), {}
arrivals = sorted(rng.randint(0, 999) for _ in range(400)) # 400 msgs in 1 s, uniform
arrivals += sorted(rng.randint(1500, 1600) for _ in range(100)) # burst of 100 in 100 ms
def work(name, flushes):
if stall and name == "c1" and sum(flushes.values()) == 3:
return 1500 # one batch takes longer than the 1000 ms visibility timeout
return 20
cs = [Consumer(f"c{i}", q, sink, vis_ms=1000, work_ms=work) for i in range(3)]
i = 0
for now in range(0, 6000):
while i < len(arrivals) and arrivals[i] == now:
q.send(i, f"item-{i}", now); i += 1
for c in cs:
c.tick(now)
flushes = sum((c.flushes for c in cs), Counter())
print(f"stall={stall}: sent={len(arrivals)} unique_written={len(sink)} "
f"left_in_queue={len(q.msgs)} flushes={dict(sorted(flushes.items()))} "
f"duplicate_writes={sum(c.dup_writes for c in cs)} "
f"stale_deletes={sum(c.stale_deletes for c in cs)}")
run(stall=False)
run(stall=True)
stall=False: sent=500 unique_written=500 left_in_queue=0 flushes={'size': 18, 'time': 27} duplicate_writes=0 stale_deletes=0
stall=True: sent=500 unique_written=500 left_in_queue=0 flushes={'size': 21, 'time': 20} duplicate_writes=5 stale_deletes=5
Reading the output:
- No stall. All 500 items are written exactly once. 18 batches flushed because they reached 16 items, and 27 because the 50 ms timer fired (the quieter stretches). No duplicates.
- One slow batch. Its messages became visible again after 1,000 ms, and another consumer received and processed them. That stalled batch happened to be a small, time-triggered flush of 5 messages, not a full 16-item batch (it was consumer c1's third flush overall, and the 50 ms timer fired on it before 16 items had arrived), so 5 items were processed twice (
duplicate_writes=5). When the slow consumer finally tried to delete them, its receipt handles were stale and the deletes did nothing (stale_deletes=5). The final state is still correct (500 unique items, empty queue), but only because the write was an idempotent upsert. If processing had charged a card or incremented a counter, 5 customers would have been hit twice.
The same logic against real SQS (production shape, not executed here)
import time
def collect_batch(sqs, queue_url, max_items=16, max_wait_s=0.050, visibility_s=60):
batch, deadline = [], None
while len(batch) < max_items:
if deadline is not None and time.monotonic() >= deadline:
break
resp = sqs.receive_message(
QueueUrl=queue_url,
MaxNumberOfMessages=min(10, max_items - len(batch)),
WaitTimeSeconds=20 if deadline is None else 0, # long-poll only while the batch is empty
VisibilityTimeout=visibility_s,
)
msgs = resp.get("Messages", [])
if msgs and deadline is None:
deadline = time.monotonic() + max_wait_s
batch += msgs
if not msgs and deadline is not None:
time.sleep(0.005) # WaitTimeSeconds is whole seconds, so poll briefly instead
return batch
def process_and_ack(sqs, queue_url, batch, handle_one):
done = [m for m in batch if handle_one(m)] # handle_one must be idempotent
for i in range(0, len(done), 10): # DeleteMessageBatch takes at most 10 entries
sqs.delete_message_batch(QueueUrl=queue_url, Entries=[
{"Id": str(j), "ReceiptHandle": m["ReceiptHandle"]} for j, m in enumerate(done[i:i + 10])])
Walking through the polling loop: the first receive_message call (before anything is in the batch, deadline is None) uses WaitTimeSeconds=20, a long-poll (SQS holds the connection open and waits up to that many seconds for a message, instead of returning immediately): if the queue is empty, an idle consumer is not making thousands of empty calls a minute. As soon as that first call returns anything, the code sets the 50 ms deadline, and every later call for the same batch uses WaitTimeSeconds=0, because WaitTimeSeconds is an integer and the deadline can be only a few milliseconds away, so a 1-second long-poll would blow straight through it. With waiting turned off, an empty response comes back immediately, and the loop instead sleeps 5 ms itself before trying again: a short-poll (calling receive immediately and repeatedly, accepting the extra request-per-call cost) until either the batch fills or the 50 ms deadline passes.
On the Lambda-managed trigger (BatchSize 16, batching window 1 s), the poller does the collecting and the handler only processes. It reports failures by returning {"batchItemFailures": [{"itemIdentifier": "<messageId>"}]} with ReportBatchItemFailures (a per-event-source-mapping setting that turns this partial-failure reporting on) enabled. Lambda then deletes the successful messages for you.
Assumptions about queue semantics
- Visibility timeout > max wait + processing time + margin. The 50 ms wait counts against it, because the clock starts at receive. For the managed trigger, AWS recommends a visibility timeout of at least 6x the function timeout plus the batching window. If a batch might run long, extend visibility with
ChangeMessageVisibility(the API that resets a message's visibility-timeout clock without touching its content) as a heartbeat: call it periodically while still working, so the message does not reappear out from under you. - Delete after success, never before. Deleting first turns a crash into lost messages.
- At-least-once delivery. Standard queues can deliver a message more than once even without a timeout. Idempotency is required, not optional.
- No ordering on a standard queue. On a FIFO (first-in first-out) queue, ordering holds only within a message group (FIFO's own grouping key: all messages sharing one
MessageGroupIdare delivered in order to one consumer at a time, while messages in different groups can be processed in parallel). A failed message must also stop later messages from the same group in that batch, or they will be processed out of order.
Complexity
- Per batch: O(b) processing and memory, where b is 16 or less.
- At least ceil(16/10) = 2 receive calls and 2 delete-batch calls per full batch.
- The time trigger bounds added latency to 50 ms plus one receive round trip.
- The simulation's fake queue scans all messages on each receive, which is fine for a demo. Real SQS does not.
Edge cases
- Empty queue: long-poll (20 s) while the batch is empty, so an idle consumer does not spin.
- Partial failure: delete only the successes. Failures return after the visibility timeout.
- Poison message:
maxReceiveCount(for example 5) moves it to the DLQ so it cannot block the queue forever. - Batch payload size: 16 large messages can exceed the 6 MB synchronous invocation payload (Lambda's hard cap on the total request size for a synchronous invocation, which includes SQS event-source-mapping batches). The managed trigger then sends fewer records than the configured batch size.
- Shutdown mid-batch: unprocessed messages simply reappear after the visibility timeout. Nothing is lost, and nothing needs special cleanup.
A greenfield service needs to choose between serverless functions and containers managed by Kubernetes. What practical criteria would you use to decide: think about latency and cold starts, traffic pattern, cost model, operational overhead, vendor lock-in, and your team's existing skills. In what kind of scenario does one option clearly win?
Sample Answer
Direct answer
Default to serverless functions when traffic is low, bursty or unpredictable, the work is short and stateless, and the team has no Kubernetes platform already running. Default to Kubernetes-managed containers when traffic is steady and high, requests need consistently low latency, the work is long-running or needs special hardware, or the organization already operates a Kubernetes platform with people to run it. For a typical greenfield service with no existing platform, I would start serverless and write down the traffic level at which I would move.
Two terms first:
- Serverless functions (FaaS, functions as a service), for example AWS Lambda: you deploy a function; the provider starts copies on demand, scales them to zero when idle, and bills per request plus per millisecond of run time.
- Containers on Kubernetes: you package the service as a container image and Kubernetes (a container orchestrator: it runs your containers as pods, one or more containers scheduled and scaled together, on nodes, the physical or virtual machines that make up the cluster) keeps a chosen number of copies running on servers you pay for whether or not they are busy. On AWS the managed version is EKS (Amazon Elastic Kubernetes Service).
The criteria
| Criterion | Serverless functions | Kubernetes containers | Question to ask |
|---|---|---|---|
| Latency and cold starts | A cold start (booting a new function environment on first request or during scale-up) adds latency to some requests; mitigated by provisioned concurrency (paying to keep environments warm) | Pods are already running, so no per-request cold start; scaling up new pods and nodes is slower | Does the p99 (99th percentile) latency target tolerate an occasional slow request? |
| Traffic pattern | Scales to zero and up quickly; ideal for spiky or idle-most-of-the-day traffic | Needs capacity running for the baseline; autoscaling reacts more slowly | What is the ratio of peak to average traffic? |
| Cost model | Pay per request and per GB-second (memory allocated, in GB, times run time, in seconds; the unit Lambda's execution price is billed in); nothing when idle | Pay for provisioned capacity (servers kept running and billed 24x7, whether or not they are doing work) plus the cluster itself | What is the average utilization? |
| Operational overhead | No servers, OS patching or cluster upgrades | Cluster upgrades, node patching, autoscaler tuning, networking | Who will be on call for the platform? |
| Vendor lock-in | Handler signatures, event formats and triggers are provider-specific | Container images and Kubernetes manifests move between clouds fairly easily | How likely is a move, and what would it cost? |
| Team skills | Needs event-driven design (structuring the system around reacting to events rather than direct calls) skills and distributed tracing (following one request's path across multiple services to debug it) | Needs Kubernetes operations skills | What does the team already run well? |
Two hard limits also decide it on their own: AWS Lambda caps one invocation at 15 minutes and 10,240 MB of memory, and it has no GPUs. Work that exceeds those goes to containers.
Worked example: where the cost lines cross
Compare Lambda with one always-on container sized at 1 vCPU (one virtual CPU core, a unit of allocated compute) and 2 GB, using AWS us-east-1 list prices (Lambda $0.0000166667 per GB-second plus $0.20 per million requests; Fargate, AWS's serverless container runtime, $0.000011244 per vCPU-second and $0.000001235 per GB-second):
How to read the code before running it: LAMBDA_GBS/LAMBDA_REQ are Lambda's per-GB-second and per-request prices; FG_VCPU_S/FG_GB_S are Fargate's per-vCPU-second and per-GB-second prices; H = 730 is the average hours in a billing month, used to turn an hourly or per-second rate into a monthly one. per_req prices one 100 ms, 1 GB request: 0.1*1.0*LAMBDA_GBS is 100 ms (0.1 s) times 1 GB, i.e. 0.1 GB-seconds of execution, priced at LAMBDA_GBS, plus the flat LAMBDA_REQ per-request fee. The container's monthly price, task, sums its vCPU cost and its memory cost, each a rate times seconds in the month.
LAMBDA_GBS, LAMBDA_REQ = 0.0000166667, 0.20/1e6
FG_VCPU_S, FG_GB_S = 0.000011244, 0.000001235
H = 730
task = (1*FG_VCPU_S + 2*FG_GB_S) * 3600 * H
per_req = 0.1*1.0*LAMBDA_GBS + LAMBDA_REQ # 100 ms at 1 GB
print(f"1 vCPU/2 GB Fargate task 24x7: ${task:.2f}/month")
print(f"Lambda per request (100 ms, 1 GB): ${per_req:.8f}")
be = task/per_req
print(f"breakeven: {be/1e6:.1f}M requests/month = {be/(H*3600):.1f} req/s average")
print(f"EKS control plane: ${0.10*H:.2f}/month")
1 vCPU/2 GB Fargate task 24x7: $36.04/month
Lambda per request (100 ms, 1 GB): $0.00000187
breakeven: 19.3M requests/month = 7.3 req/s average
EKS control plane: $73.00/month
How to read it:
- Below about 7 requests per second on average, Lambda is cheaper than even one always-on container. A new internal API doing 50,000 requests a day (about 0.6 requests/s) costs roughly 1.5M x $0.00000187, under $3 a month, on Lambda.
- On Kubernetes you would also pay $73 a month for each EKS cluster's control plane (the managed pieces that run the cluster itself, scheduling and API server, separate from and in addition to the nodes that run your pods), run at least two copies for availability, and spend engineer time on the cluster.
- Above the breakeven, containers win on raw compute price, and the gap widens as steady traffic grows, because a busy container is cheaper per unit of work than the same work billed by the millisecond.
The example is deliberately simple: it ignores the free tier, assumes 100 ms per request, and assumes one container could serve that load. Rerun it with your own duration and memory.
Scenarios where one option clearly wins
- Serverless clearly wins: a webhook receiver, a scheduled nightly report, or an image thumbnailer triggered by uploads. Traffic is bursty or idle most of the day, each task takes seconds, there is no platform team, and scale-to-zero means paying almost nothing when idle.
- Kubernetes clearly wins: a high-traffic API steady at around 2,000 requests/s with a strict 20 ms p99 target, maintaining long-lived WebSocket connections (persistent two-way connections), at a company that already runs a Kubernetes platform. Utilization is high, cold starts are unacceptable, and the operational cost is already paid.
Trade-offs and pitfalls
- Counting only the compute bill. The larger cost of Kubernetes for a small team is people: upgrades, security patching, on-call. The larger hidden cost of serverless at scale is the per-millisecond premium on steady traffic.
- Assuming cold starts always matter. For asynchronous work (queues, file uploads) a few hundred extra milliseconds is invisible; they only matter for user-facing, latency-sensitive requests.
- Treating the decision as permanent. Packaging the function as a container image and keeping business logic out of the handler keeps a later move cheap.
- Ignoring the downstream database. Functions can scale to hundreds of copies quickly and exhaust a relational database's connection limit, so plan a connection proxy (a lightweight service, such as RDS Proxy, that pools and limits database connections on functions' behalf) or a concurrency cap.
What would you monitor for a serverless service in production? Cover infrastructure-level signals (invocations, duration, errors), a function-level breakdown (time spent in initialization versus in the handler), and any service-specific output you'd want visibility into. For each category, explain why it matters.
Sample Answer
Direct answer
Monitor three layers. Platform signals tell you whether requests are arriving, succeeding, being throttled, and how long they take. Function-level lifecycle signals separate time spent initializing a new execution environment (a cold start) from time spent in your handler, because they have different causes and different fixes. Service-specific output tells you whether the function is doing the right thing, which platform metrics cannot see: a function can return HTTP 200 all day with wrong answers.
1. Infrastructure-level signals
Names below are AWS Lambda's CloudWatch metrics; other platforms expose equivalents.
| Signal | Metric | Why it matters |
|---|---|---|
| Traffic | Invocations | Baseline for every ratio; a sudden drop often means the trigger broke, not the function |
| Failures | Errors, alert on Errors / Invocations | Includes your exceptions and runtime errors such as timeouts |
| Rejections | Throttles | Requests refused because no concurrency was available. They are not counted in Invocations or Errors, so an error-rate alarm alone misses them |
| Latency | Duration at p50, p95 and p99 | The p99 (99th percentile, the slowest 1 in 100) is what users complain about; averages hide it |
| Capacity | ConcurrentExecutions against the account or reserved limit (a per-function ceiling on concurrency you carve out of the shared account limit, guaranteeing that function its own capacity) | Tells you how close you are to throttling before it happens |
| Pre-warmed capacity | ProvisionedConcurrencySpilloverInvocations | Requests that overflowed pre-warmed environments into cold on-demand ones |
| Backlog (queues and streams: an ordered, append-only log of records, such as Kinesis or DynamoDB Streams, that a function reads sequentially instead of receiving pushed one at a time) | IteratorAge (how far behind the current time the function's read position, its iterator, or bookmark, into the stream has fallen) for streams, AsyncEventAge for asynchronous invocations, queue depth and age of oldest message | A function can look healthy while falling further behind |
| Lost work | Dead-letter queue depth, AsyncEventsDropped, DeadLetterErrors | Events that failed all retries. A DLQ (dead-letter queue) that grows silently is data loss in slow motion |
2. Function-level breakdown: initialization versus handler
A single invocation's time is:
- Init: a new environment is created, the runtime starts and your global-scope code runs (imports, SDK clients, loading a model).
- Handler: your function body for this request.
They must be separated because Lambda's Duration metric excludes cold-start time. The init time appears as Init Duration on the REPORT log line of the invocation that paid it, and only on those invocations. So:
- Cold-start rate = invocations whose REPORT line carries
Init Duration, divided by all invocations. Compute it from logs (for example with a CloudWatch Logs Insights query, a query language and console for searching and aggregating over your CloudWatch log data directly, over REPORT lines) or with CloudWatch Lambda Insights (a monitoring add-on that automatically collects a function's CPU, memory and cold-start metrics without you writing the queries yourself). - Init duration distribution (p50 and p99), watched per deploy: a new dependency that adds 800 ms of imports shows up here and nowhere else.
- Handler duration broken down further with tracing spans (the individual timed segments, for example one downstream call, that a distributed tracing tool such as AWS X-Ray stitches together into one request's timeline): time in downstream calls versus your own computation.
- Memory:
Max Memory Usedagainst configured memory, from the same REPORT line. Near the limit means out-of-memory risk; far below means you may be over-paying.
Worked example: a function shows p99 Duration of 120 ms, yet users see 1.4 s spikes (about the 1,200 ms Init Duration plus the 120 ms handler time, plus the normal network and invocation overhead neither metric captures on its own). Logs show 0.8% of invocations carry Init Duration of about 1,200 ms. The spikes are cold starts, invisible in Duration, because Duration only ever measures handler time and excludes Init.
Here is why the percentile hides them. Sort every invocation's user-facing latency (Init plus handler, for the ones that pay Init) from fastest to slowest. The slowest 0.8% of that list are exactly the cold ones, so they occupy the top 0.8% of the distribution: from the 99.2nd percentile up to the 100th. The 99th percentile sits at the 99.0 mark, still just below where the cold cluster starts at 99.2, so p99 lands on a warm value, about 120 ms, even though 0.8% of real users are waiting over a second. Since 0.8% is under 1%, the p99 of user latency sits right at the edge: if the cold-start rate crept up past 1% (more traffic, a new dependency, fewer warm environments), the cold cluster would grow to cover the 99th percentile itself, and the reported p99 would jump from about 120 ms to roughly 1,200 to 1,300 ms in one step, even though no individual request got any slower. The fix is on the init side (trim imports, pre-warm), not in the handler.
3. Service-specific output
Emit these yourself as custom metrics (for example with the CloudWatch embedded metric format, which turns structured log lines into metrics):
- Business outcome counts: orders accepted, payments declined, messages delivered. A drop with flat
Invocationsmeans requests arrive but fail logically. - Output quality: for a validation or scoring function, the distribution of outputs (share of rejects, score histogram). For an ML inference function, prediction distribution and confidence; a shift means input drift (the real-world data the model now sees has statistically changed shape from what it was trained or validated on) or a bad model version.
- Downstream dependency health: latency and error rate per dependency, so a slow database is distinguishable from slow code.
- Idempotency or duplicate signals: duplicates detected and skipped, since event sources deliver at least once (the same event may arrive more than once).
Keep dimensions (the labels, such as function version or region, you attach to a metric so you can slice and filter it) low-cardinality (built from few distinct values): tag by function version or region, never by user ID, because each unique combination of dimension values is stored and billed as its own separate metric time series, so a high-cardinality dimension like user ID can silently create millions of them.
Why each category matters, in one line each
- Platform signals answer "is it up and keeping up?"
- Init versus handler answers "is latency coming from environment start-up or from my code?", which decides between pre-warming and code optimization.
- Service output answers "is it right?", the only layer that catches silent correctness failures.
Pitfalls
- Alarming on error rate but not on
Throttles, so a saturated function looks healthy. - Reading average
Durationand concluding there is no cold-start problem. - No alarm on DLQ depth.
- Putting request IDs or user IDs into metric dimensions and receiving a large bill for millions of metrics.
Unlock Full Question Bank
Get access to all 28 Serverless and Function-as-a-Service Architecture interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.