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 event-driven design patterns are commonly used in serverless architectures? Walk through a concrete example: a pipeline that needs to kick off a downstream job whenever a new file lands in object storage. What components and events would you wire together, and how would you make sure the trigger is reliable and doesn't fire the job twice for the same file?
Sample Answer
Direct answer
Serverless systems are usually built by wiring managed services together with events, not by writing servers that poll. The common patterns are:
- event notification (a service announces "something happened")
- queue-based load leveling (a queue sits between producer and consumer)
- publish/subscribe fan-out (one event, many independent consumers)
- orchestration (a workflow engine drives the steps)
- the claim-check pattern (pass a pointer to large data, not the data)
- dead-letter handling (failures go somewhere you can see them)
For "a file lands, so run a job" I would wire it like this:
- The bucket emits an Object Created event to an event router (Amazon EventBridge, a managed service that receives events from many sources and routes each one to whichever targets match its filtering rules).
- A rule filtered on the input prefix (the folder-like portion of the object key that events are matched against, such as
incoming/) sends it to a queue. - A small function starts a workflow (Step Functions Standard, one of two execution modes: Standard keeps a full execution history and can run for up to a year; Express, mentioned below, is cheaper and higher-throughput but keeps no long history, and suits short executions better) whose name is derived from the object's identity.
- The workflow runs the job.
Every hop is at-least-once (each event may be delivered more than once, though never fewer), so reliability comes from queues with dead-letter queues and alarms. "Not twice" comes from a deterministic execution name. A second start with the same name does not start a second job.
The patterns, briefly
| Pattern | What it is | Use it when |
|---|---|---|
| Event notification | A service emits "this happened" (object created, row changed) | Something should react to a change without the producer knowing who |
| Queue-based load leveling | A queue between producer and consumer | The consumer is slower, rate-limited or sometimes down |
| Pub/sub fan-out | One event delivered to many independent consumers (an Amazon SNS, Simple Notification Service, topic; EventBridge rule targets) | Several teams react to the same fact |
| Orchestration | A workflow engine calls the steps and holds the state | Multi-step jobs with retries, waits and branching |
| Choreography | Each service reacts to the previous one's events; no central controller | Loosely coupled, short chains |
| Claim check | Put the large payload in object storage; pass only its location | Payloads bigger than event or message limits |
| Dead-letter queue (DLQ) | Where messages go after repeated failures | Always, on every async hop |
The pipeline
flowchart LR
up[Upload to incoming/] --> bucket[(Object storage bucket)]
bucket -->|Object Created event| router[EventBridge rule: prefix incoming/]
router --> q[Queue]
q --> starter[Starter function]
starter -->|StartExecution, deterministic name| wf[Workflow: Step Functions Standard]
wf --> job[Batch or data-processing job]
wf --> done[Completion event]
q -.->|after 5 failures| dlq[DLQ + alarm]
- Why EventBridge rather than a direct bucket-to-function trigger. Rules can filter on prefix and suffix, send one event to several targets, and archive and replay events. A direct S3-to-Lambda notification also works, but it is an asynchronous invoke (Lambda queues the event internally and retries it on failure without the caller waiting for a response) with Lambda's own retry queue (a separate, less visible retry mechanism than a queue you configure and can alarm on yourself), and you get fewer controls.
- Why a queue before the starter. The queue gives a buffer, a retry policy you control, a DLQ, and a visible metric (age of oldest message) to alarm on.
- Why a workflow rather than running the job inside the function. A Lambda invocation lasts at most 15 minutes. A Standard workflow can wait on a job for far longer, and it records every step, so retries and failures are visible.
- Multipart uploads (large files uploaded to object storage in separate chunks that are only assembled into the final object once every part has arrived) emit one event, when the upload completes, so the job never sees a half-written file.
Making the trigger reliable
- Assume duplicates and delays. S3 documents its event notifications as delivered at least once, usually within seconds but sometimes a minute or longer. The event router and the queue are also at-least-once.
- Every async hop gets a DLQ and an alarm. Alarm on DLQ depth above 0, and on the age of the oldest message in the main queue.
- Reconcile. A scheduled sweep compares objects under
incoming/with the set of files the workflow has processed. It re-triggers anything missing. This catches the rare lost event, a misconfigured rule, or an outage longer than the retry windows. - Avoid recursion. If the job writes output back into the same bucket, write it under a different prefix (or bucket) than the rule listens on. Otherwise every output file triggers another job.
Making sure the job fires once per file
Derive the workflow's execution name from the object's identity: bucket + key + version id (enable versioning on the bucket first: with it on, every overwrite of the same key is kept as a separate, uniquely identified version instead of replacing the object in place, and it is that per-write version id, not the key alone, that changes on a genuine re-upload). For a Standard workflow, a second StartExecution (the API call that starts a workflow execution) with the same name and input returns the existing execution while it is running, and returns ExecutionAlreadyExists once it has closed. Either way, no second job starts. Names can be reused 90 days after an execution closes.
import hashlib
def execution_name(bucket, key, version_id):
# Same object version -> same name; a re-upload (new version) -> new name.
digest = hashlib.sha256(f"{bucket}/{key}#{version_id}".encode()).hexdigest()
return f"ingest-{digest[:40]}" # 47 chars, within the 80-char limit, no banned characters
class FakeStandardWorkflow:
"""Models documented StartExecution semantics for STANDARD workflows."""
def __init__(self):
self.executions = {} # name -> (input, status)
def start(self, name, payload):
if name in self.executions:
prev_input, status = self.executions[name]
if status == "RUNNING" and prev_input == payload:
return "same execution returned (idempotent)"
raise RuntimeError("ExecutionAlreadyExists")
self.executions[name] = (payload, "RUNNING")
return "started"
def handle(event, sfn):
d = event["detail"]
name = execution_name(d["bucket"]["name"], d["object"]["key"], d["object"]["version-id"])
payload = f'{d["bucket"]["name"]}/{d["object"]["key"]}'
try:
return name, sfn.start(name, payload)
except RuntimeError as e:
return name, f"{e}: already handled, acknowledge the message"
sfn = FakeStandardWorkflow()
evt = {"detail": {"bucket": {"name": "raw-landing"},
"object": {"key": "incoming/2026-09-27/orders.csv", "version-id": "v1"}}}
print(handle(evt, sfn)) # first delivery
print(handle(evt, sfn)[1]) # duplicate while running
sfn.executions[execution_name("raw-landing", "incoming/2026-09-27/orders.csv", "v1")] = (
"raw-landing/incoming/2026-09-27/orders.csv", "SUCCEEDED")
print(handle(evt, sfn)[1]) # duplicate after it finished
evt["detail"]["object"]["version-id"] = "v2"
print(handle(evt, sfn)[1]) # genuine re-upload
('ingest-f5772e2d0a15754e5cd838f6fdd74a26602f48ad', 'started')
same execution returned (idempotent)
ExecutionAlreadyExists: already handled, acknowledge the message
started
- Duplicate while the job is running: the same execution is returned.
- Duplicate after it finished:
ExecutionAlreadyExists, which the starter treats as "already handled" and acknowledges. - A genuine re-upload (new version id) gets a new name and correctly starts a new job.
Two edges to handle deliberately:
- A retry after a FAILED execution needs a new name (for example, append an attempt number after checking the old execution's status). Otherwise
ExecutionAlreadyExistsblocks the legitimate retry. - The job itself should also be idempotent. It writes its output to a deterministic path and overwrites, so a manual re-run can't double-count.
Pitfalls
- Hashing the event id instead of the object identity. Duplicates carry different event ids, so the dedupe never matches.
- Dropping the version id and deduping on key alone. A legitimate re-upload of
orders.csvwould be silently ignored. - No DLQ alarm. Failed files wait unseen until someone asks where the report is.
How do FaaS platforms scale as traffic increases rapidly? Using AWS Lambda as an example, explain how new execution environments get provisioned, what account or regional concurrency limits exist, and what reserved versus provisioned concurrency each do. What does this mean for a latency-sensitive endpoint under a sudden burst of traffic?
Sample Answer
Direct answer
A FaaS platform (functions-as-a-service: you upload a function and the provider runs it once per event) scales by creating more execution environments. An execution environment is a small isolated sandbox with your runtime and code loaded, and it handles one request at a time. So 600 requests in flight at the same moment need 600 environments. When a request arrives and no idle environment exists, Lambda builds a new one first. That is a cold start. Growth is bounded by two different limits:
- a per-function scaling rate: how fast new environments can be created
- a Regional account concurrency quota: how many can exist at once, shared by every function in the account
Reserved concurrency gives a function its own slice of that quota and caps it there. Provisioned concurrency keeps environments already initialized, so requests that land on them skip the cold start. For a latency-sensitive endpoint, the cold starts and throttles all arrive in the same first seconds of a burst. The fix is to pre-warm the endpoint with provisioned concurrency sized to the burst and make sure the quota has headroom before the burst starts.
How a new environment gets provisioned
- Routing. A request arrives. If an idle, already-initialized ("warm") environment exists, Lambda sends the request there. No setup cost.
- Init phase (the cold start). If there is no idle environment, Lambda creates one: it loads your code package, starts the language runtime and any extensions, then runs your top-level code. That is everything outside the handler: imports, SDK clients, configuration loading.
- Invoke phase. The handler runs.
- Freeze and reuse. After the response, the environment is frozen and kept for later requests. How long it is kept is unspecified. It can be reclaimed at any time, so you cannot rely on it staying warm.
Concurrency means the number of requests being processed at the same instant, and it is also the number of execution environments Lambda needs at that instant. You can compute it with Little's law: concurrency = arrival rate (RPS) x the average time each request spends in the system (duration in seconds). That gives you environments directly; there is no hard per-environment throughput ceiling. AWS's own conceptual scaling guide warns against exactly the framing that sounds intuitive here: "it's incorrect to say that each Lambda execution environment can handle only a maximum of 10 requests per second. Instead of observing the load on any individual execution environment, Lambda only considers overall concurrency and overall requests per second when calculating your quotas." A single warm environment reused back to back for a fast function easily clears 10 requests per second in practice (a 20 ms handler run continuously on one environment serves 50 requests per second, not 10).
What Lambda actually enforces alongside the concurrency quota is a separate REQUEST-RATE quota: RPS must stay at or below 10 times whichever concurrency quota is in force (10,000 RPS against the default 1,000-unit account quota; 10 times a function's reserved concurrency if it has one; 10 times its provisioned concurrency for the units running on it). This is a policy ceiling tied to the quota number, not a physical property of any one environment. For a function whose average duration is at or above 100 ms, Little's law alone already keeps the request rate inside that 10x ceiling, so it never binds. It matters specifically for the sub-100-ms case: a 20 ms function serving 30,000 RPS needs a concurrency, and so an environment count, of only 600, comfortably under a 1,000-unit account quota, but its request rate of 30,000 is three times the 10,000 RPS the default quota allows, so it throttles on the rate ceiling even though the environment count looks fine.
environments (concurrency)=RPS×durationswith a second, independent check for functions under about 100 ms average duration:
RPS≤10×concurrency quota (account default, or the function’s reserved/provisioned concurrency)The limits
| Limit | Scope | Default | What happens when you hit it |
|---|---|---|---|
| Concurrency quota | Account, per Region, shared by all functions | 1,000 (new accounts start lower); can be raised to tens of thousands through Service Quotas (the AWS console and API where you request a higher account limit) | Requests beyond it get a throttling error (HTTP 429) |
| Concurrency scaling rate | Per function, per Region | 1,000 new environments per 10 seconds, refilled continuously (picture a token bucket that starts full at 1,000: creating an environment spends one token, and tokens refill steadily, but the bucket cannot hold more than 1,000 at once); unused capacity does not accumulate beyond that 1,000-token cap | Requests arriving faster than environments can be created are throttled (429) |
| Unreserved floor | Account | 100 units always stay unreserved | You cannot reserve or provision more than (quota minus 100) |
The effect of a throttle depends on who called the function:
- Synchronous callers (API Gateway, a direct invoke) get the error immediately. Nothing retries for you.
- Asynchronous sources (S3 notifications, SNS, Amazon Simple Notification Service, a managed pub/sub messaging service) go through Lambda's internal queue, which retries throttled events for up to 6 hours by default.
- Queue pollers (Amazon SQS, Simple Queue Service) leave the messages in the queue to be retried.
Reserved versus provisioned concurrency
| Reserved concurrency | Provisioned concurrency | |
|---|---|---|
| What it does | Guarantees this function N units and also caps it at N | Keeps N environments initialized ahead of time; init code runs at allocation |
| Removes cold starts? | No. It only decides who gets capacity | Yes, for requests that land on those N environments |
| Cost | No extra charge | Billed per GB-second for as long as it is configured, used or not |
| Applies to | The function | A published version (an immutable, numbered snapshot of the function's code and configuration) or alias (a named pointer, like prod, that you can repoint to a different version), never $LATEST (the mutable pointer to whatever code is currently deployed, which is why it cannot be pinned to provisioned concurrency) |
| Above the setting | Throttled (429) | Overflow uses normal on-demand environments, which cold start |
| Typical use | Protect a critical function from being starved; stop a function from flooding a database | Interactive, latency-sensitive endpoints |
If both are set, provisioned concurrency cannot exceed reserved concurrency. Setting reserved concurrency to 0 is the documented way to stop a function completely.
Worked example
Assume an endpoint whose handler takes 120 ms. It normally sees 100 RPS with 12 environments warm, and the account quota is the default 1,000.
# Environments needed = RPS x duration (Little's law: this alone gives the concurrency,
# i.e. the environment count). The separate 10x-quota request-rate ceiling only binds
# for average durations under about 100 ms, which this 120 ms example never reaches.
duration_s = 0.120 # assumed average handler duration for the endpoint
bucket = 1000 # scaling rate: up to 1,000 new environments per function...
refill_per_s = 100 # ...refilled continuously (1,000 per 10 s)
warm_now = 12
def report(rps, account_limit):
need = rps * duration_s
cold = max(0, min(need, account_limit) - warm_now)
wait = max(0, cold - bucket) / refill_per_s
short = max(0, need - account_limit)
print(f"{rps:>6} RPS, quota {account_limit:>5}: need {need:>5.0f}; new (cold) environments {cold:>5.0f}; "
f"seconds beyond the first 1,000 new: {wait:>4.1f}; throttled capacity gap: {short:.0f}")
for rps in (100, 5_000, 15_000):
report(rps, 1_000) # default Regional concurrency quota
report(15_000, 3_000) # after a quota increase
pc_units, mem_gb, price_pc = 600, 1.0, 0.0000041667 # USD per GB-second, us-east-1, x86
hour = pc_units * mem_gb * 3600 * price_pc
print(f"provisioned concurrency {pc_units} x {mem_gb} GB: ${hour:.2f}/hour, ${hour * 730:,.0f}/month if always on")
100 RPS, quota 1000: need 12; new (cold) environments 0; seconds beyond the first 1,000 new: 0.0; throttled capacity gap: 0
5000 RPS, quota 1000: need 600; new (cold) environments 588; seconds beyond the first 1,000 new: 0.0; throttled capacity gap: 0
15000 RPS, quota 1000: need 1800; new (cold) environments 988; seconds beyond the first 1,000 new: 0.0; throttled capacity gap: 800
15000 RPS, quota 3000: need 1800; new (cold) environments 1788; seconds beyond the first 1,000 new: 7.9; throttled capacity gap: 0
provisioned concurrency 600 x 1.0 GB: $9.00/hour, $6,570/month if always on
What the numbers mean:
- Burst to 5,000 RPS. You need 600 environments. The scaling rate is not the problem: its token bucket starts full at 1,000 (see above), so all 588 new environments can be created immediately from that reserve, with no need to wait for the refill. The problem is that 588 requests each wait for a cold start at the same moment, and that is what p99 latency (the latency 99% of requests beat) will show. Init time depends on runtime and package size. Read it from the
Init DurationLambda logs rather than guessing. - Burst to 15,000 RPS on the default quota. You need 1,800 environments but only 1,000 can exist. About 800/1,800, or 44%, of the load is throttled.
- Same burst after raising the quota to 3,000. The first 1,000 new environments appear immediately. The remaining 788 arrive at the refill rate of about 100 per second, so over about 7.9 seconds. Requests above capacity during those seconds are still throttled.
- Cost of pre-warming 600 x 1 GB: $9.00 an hour, or about $6,570 a month if it is left on all the time. That is why you schedule it rather than leave it on.
What this means for a latency-sensitive endpoint
- Provisioned concurrency on the alias the API actually invokes (never on
$LATEST, which cannot hold provisioned concurrency). Size it to the expected burst plus a buffer. Lambda's own guidance is +10%, so 600 becomes 660. If the burst is predictable, raise it on a schedule. - Reserved concurrency at or above that number. This stops other functions in the account from starving the endpoint. Without it, a noisy batch job (an unrelated function in the same account that suddenly scales hard, for a backfill or a retry storm) in the same Region can use up the shared 1,000.
- Quota headroom requested ahead of time. Check the layers in front of Lambda too. API Gateway (AWS's managed HTTP front door) has its own default account throttle of 10,000 RPS per Region.
- Make cold starts cheaper for the overflow. Keep the package small, create SDK clients at top level so warm invocations reuse them, and defer rarely used clients. For supported runtimes, snapshot restore (Lambda SnapStart) is a cheaper alternative to keeping environments warm.
- For bursts beyond anything you pre-warmed, decide the behaviour explicitly. Either return a fast 429 and have clients retry with jittered backoff (each retry waits longer than the last, with a bit of randomness mixed in so many clients do not all retry at the same instant), or, if the work does not need an immediate answer, accept it into a queue.
Pitfalls
- Invoking
$LATESTor the wrong alias. Provisioned concurrency sits unused, you still pay for it, and cold starts continue. - Treating reserved concurrency as a performance feature. It warms nothing.
- Expecting target-tracking auto scaling (a controller that watches a metric and adds or removes capacity to hold it near a target value) to catch a spike. Application Auto Scaling on
ProvisionedConcurrencyUtilizationneeds the load to last about 3 minutes (three data points) before it adds capacity. It handles slow drift, not a sudden burst. - Forgetting the separate request-rate ceiling for sub-100-ms functions. Little's law alone gives the right environment count even for a fast function (a 20 ms function at 30,000 RPS needs only 600 environments), but request rate can still hit the platform's 10x-of-quota ceiling before concurrency does: at the default 1,000-unit quota that ceiling is 10,000 RPS, so the 30,000-RPS case above throttles despite having plenty of environment headroom.
- Scale-out has side effects downstream. 600 new environments can mean 600 new database connections. Plan the downstream protection together with the scaling.
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.
Serverless functions can scale out fast enough to exhaust a relational database's connection limit. How would you solve this? What connection-pooling or proxy approaches exist for a serverless environment, and what trade-offs do they carry (added network hops, proxy scaling, cold-versus-warm behavior)? How would you size and place the pooling layer to respect the database's connection limit while keeping latency low?
Sample Answer
Direct answer
Each concurrent function environment usually opens its own database connection and keeps it across warm invocations. At 1,000 concurrent functions that is about 1,000 connections, against a relational database configured for a few hundred. (Examples below use AWS: Amazon RDS is the managed relational database service, Aurora its cloud-native engine, and a VPC, Virtual Private Cloud, is the private network both run in.) The fix is a connection pooler between the functions and the database: it accepts many cheap client connections and multiplexes them onto a small, fixed pool of real database connections. Pair it with a cap on function concurrency, so the queue at the pooler cannot grow without bound; size that cap to the assumed peak concurrency (1,000 in the worked example below), not to the pool's connection count. The pooler already handles multiplexing connections; the concurrency cap's job is only to stop a runaway retry storm or a bug from spinning up unbounded environments and overwhelming the pooler's own queue.
- On AWS the managed option is RDS Proxy.
- The self-managed option is PgBouncer (PostgreSQL) or ProxySQL (MySQL) running on containers.
- Connectionless alternatives are HTTP data APIs (for example the Aurora Data API, which runs SQL over an HTTPS call with no persistent connection at all) and serverless-native database drivers (for example the Neon or PlanetScale serverless drivers, which speak a connection protocol over HTTP or WebSocket instead of a raw TCP connection).
Size the pool from the database's real work (Little's law), not from function concurrency. I would use RDS Proxy for RDS or Aurora, plus reserved concurrency as a hard ceiling. I would switch to PgBouncer only if session pinning or cost made the managed proxy a poor fit.
Why serverless exhausts connections
- One connection per environment. Environments don't share memory, so an in-process pool of size 10 per function makes things worse, not better. It just multiplies connections.
- Frozen environments hold their connections. Between invocations an environment is frozen but its TCP connection stays open until the environment is reclaimed or the database's idle timeout kills it. The database sees many idle "zombie" connections.
- Connection storms. A burst creates hundreds of new environments at once, and each performs a TCP + TLS + authentication handshake. PostgreSQL also starts a backend process (it forks a dedicated OS process for each connection, rather than using lightweight threads) per connection. The database spends its CPU on logins, not queries.
The options
| Option | How it works | Extra hop? | Who scales and operates it | Main gotcha |
|---|---|---|---|---|
| RDS Proxy (managed) | Transaction-level multiplexing: a database connection returns to the pool after each transaction | Yes, inside the VPC | AWS; spans the DB's Availability Zones and handles failover | Pinning: once a client issues session state (state that only makes sense for the life of one connection, such as SET, the most common trigger, issued by ORMs and drivers to configure session-level settings, PREPARE, a compiled query the driver caches on that connection, temporary tables, session advisory locks, or cursors on PostgreSQL), the proxy cannot hand that underlying DB connection to a different client until the session ends, which ties one client to one DB connection for the whole session and removes the benefit |
| PgBouncer / ProxySQL (self-managed) | Same idea; PgBouncer's transaction mode (returns a connection to the pool after each transaction commits, the same multiplexing RDS Proxy does above) is the one that multiplexes, as opposed to its session mode (one client keeps one DB connection for its whole session, which avoids pinning but saves nothing) | Yes | You: at least 2 tasks behind a load balancer, patching, monitoring | Session features need care in transaction mode; the pooler becomes your own highly available tier |
| Concurrency cap only | Reserved concurrency set to the DB's connection budget | No | Nobody | Excess requests are throttled; wastes capacity when queries are short |
| HTTP data API / serverless drivers | Queries over HTTPS; no persistent connection per environment | Yes, HTTP | Provider | Per-request overhead, API rate limits, fewer driver features |
| In-function pool | Pool inside each environment | No | You | Doesn't solve the problem: pools multiply by environment count |
Sizing the pool
Assumptions:
max_connections = 500on the database- peak function concurrency 1,000
- 3,000 queries per second averaging 4 ms each
db_max_connections = 500 # set in the DB parameter group (assumption for this example)
lambda_peak_concurrency = 1_000
queries_per_s, avg_query_s = 3_000, 0.004
busy = queries_per_s * avg_query_s # Little's law: connections in use on average
burst_factor = 3 # assumed ratio of short-burst to average load
needed = busy * burst_factor
with_headroom = needed * 1.3 # 30% headroom above peak usage
max_pct = 20
pool_cap = db_max_connections * max_pct // 100
print(f"direct connections at peak: {lambda_peak_concurrency} vs max_connections {db_max_connections}")
print(f"average busy DB connections = {queries_per_s} x {avg_query_s} = {busy:.0f}")
print(f"burst need = {busy:.0f} x {burst_factor} = {needed:.0f}; with 30% headroom = {with_headroom:.1f}")
print(f"MaxConnectionsPercent {max_pct} -> pool cap {pool_cap}; client:DB multiplexing {lambda_peak_concurrency / pool_cap:.0f}:1; "
f"left for admin, migrations and other apps: {db_max_connections - pool_cap}")
direct connections at peak: 1000 vs max_connections 500
average busy DB connections = 3000 x 0.004 = 12
burst need = 12 x 3 = 36; with 30% headroom = 46.8
MaxConnectionsPercent 20 -> pool cap 100; client:DB multiplexing 10:1; left for admin, migrations and other apps: 400
- Only about 12 connections are busy on average. A query holds a connection for 4 ms, and at 3,000 per second the average number in use is 3,000 x 0.004 = 12. That is Little's law, and it is why a pool far smaller than 1,000 works.
- Burst allowance x3 = 36, plus the 30% headroom AWS recommends above peak usage = about 47.
MaxConnectionsPercent = 20(20% of 500 = 100) covers that comfortably. It is also AWS's minimum recommended value for instance classes of db.t3.medium (a small/mid-sized RDS instance class; the letters and number describe the instance family and size, similar to EC2 instance types) and larger. It leaves 400 connections for migrations, admin sessions and other applications. The proxy also reserves a few connections for itself, so read the effective cap from theMaxDatabaseConnectionsAllowedmetric. - Upper bound from the database, not the proxy. A database with N vCPUs can only run about N queries truly in parallel. A pool far above a small multiple of the core count just moves the queue from the proxy into the database, where it costs more.
- Borrow timeout. When all 100 are busy, clients wait at the proxy.
ConnectionBorrowTimeoutdefaults to 120 s. That is longer than any API latency budget, so lower it (for example to 5 s) and fail fast instead of piling up waiting functions.
Placement and latency
- Same Region and VPC as the database, with proxy endpoints in each of the database's Availability Zones. Functions run in private subnets (network segments with no direct route to the public internet) of that VPC. Readers use the proxy's read-only endpoint (a separate address that routes to read replicas instead of the primary, the one instance that accepts writes).
- The added hop is one in-VPC network round trip per query. Measure it by load-testing with and without the proxy rather than assuming a figure. It usually matters less than what it removes: connection setup on cold starts, and connection errors during bursts.
- Cold versus warm.
- Open the connection once per environment (at top level or lazily on first use) and reuse it on warm invocations.
- A cold start still pays TCP + TLS + authentication, but to the proxy, which is much cheaper than a database backend starting up.
- If you use IAM (AWS Identity and Access Management) database authentication, generate the token once and reuse it. Tokens are valid for 15 minutes.
- Close nothing per invocation. Opening and closing per request brings back the storm.
Pitfalls
- Assuming the proxy removes the need for a concurrency cap. Without a cap, the queue simply moves to the proxy's borrow wait.
- Pinning. Watch
DatabaseConnectionsCurrentlySessionPinned. Move identical per-connectionSETstatements into the proxy's initialization query, and avoid session-level state in handler code. - Pool sized to function concurrency ("1,000 functions, so 1,000 connections") instead of to query concurrency.
- Failover (the database promoting a standby to primary after the original primary becomes unavailable). The proxy keeps client connections open while it reconnects to the new primary. Test that your queries get errors and retries, not hangs, during a failover drill.
What does 'serverless' and Functions-as-a-Service (FaaS) mean in production? Compare FaaS to running the same workload as containers, covering lifecycle, typical billing model, and operational overhead. When is FaaS a good fit versus a poor one?
Sample Answer
Direct answer
"Serverless" means you give a cloud provider your code plus a rule for when to run it, and the provider owns the machines: provisioning, scaling, patching and idle capacity. FaaS (functions-as-a-service) is the most common form. You deploy one function (AWS Lambda, Azure Functions, Google Cloud Run functions, Cloudflare Workers), it runs when an event arrives (an HTTP request, a queue message, a file landing in storage), and you pay per request and per millisecond of running time, with zero cost while idle. Compared with running the same code as containers, FaaS trades control and steady-state cost efficiency for near-zero operations and pay-for-use billing. It fits spiky, event-driven, short tasks; it fits poorly for steady high-volume traffic, long jobs, and anything that needs a long-lived process.
A plain-language picture: containers are like leasing a car (you pay every month whether you drive or not, and you look after it); FaaS is like a taxi (you pay only for trips, someone else maintains it, but a lot of trips every day costs more than the lease, and sometimes you wait for one to arrive).
How FaaS and containers actually differ
| Dimension | FaaS (AWS Lambda as the example) | Containers (Kubernetes, Amazon ECS, Cloud Run services, Cloud Run's always-on container mode, distinct from the Cloud Run functions mentioned above) |
|---|---|---|
| Lifecycle | The platform creates an execution environment (a small isolated sandbox with your code loaded) when a request needs one. Creating it is the cold start. It is reused for later requests while "warm", frozen between requests, and destroyed whenever the platform decides (Lambda recycles environments every few hours even under steady traffic). One environment handles one request at a time. | You start long-lived processes that run until you stop them. You choose how many replicas run and when to add more (autoscaling rules). One process usually serves many requests concurrently. |
| Billing | Per request plus duration in GB-seconds (memory configured in GB multiplied by seconds of run time), measured to 1 ms. Lambda in US East (N. Virginia), x86: $0.20 per million requests and $0.0000166667 per GB-second. Idle costs nothing. | Per vCPU-hour (one virtual CPU core running for one hour) and GB-hour of whatever you provisioned, busy or idle. You usually need at least two replicas for availability, so there is a cost floor. |
| Operational overhead | No servers, OS patching, cluster upgrades or capacity planning. You still own: code, permissions (a least-privilege IAM role, where IAM is AWS Identity and Access Management, per function), timeouts, concurrency limits, retries, logs and metrics. | You own image patching, cluster and node management (less on managed options such as AWS Fargate, which runs containers without you managing servers), health checks, rollout strategy and scaling policy. |
| Hard limits | Lambda: 15-minute maximum run time, 128 MB to 10,240 MB memory, 6 MB request and 6 MB response payload for synchronous calls, 250 MB unzipped package (10 GB as a container image), 1,000 concurrent executions per Region by default (raisable). | Effectively your cluster's size. Jobs can run for days; processes can hold WebSocket connections open (a WebSocket is a persistent, two-way network connection that stays open between messages, unlike a normal request/response HTTP call). |
Worked example: where the cost lines cross
An HTTP API whose handler takes 100 ms on average with 512 MB (0.5 GB) of memory. A 30-day month has 2,592,000 seconds. Cost per month at a steady rate of r requests per second:
cost(r)=r×2,592,000×(106$0.20+0.1s×0.5GB×$0.0000166667)| Steady load | Requests / month | Request charge | GB-seconds | Duration charge | Total |
|---|---|---|---|---|---|
| 1 req/s | 2,592,000 | $0.52 | 129,600 | $2.16 | $2.68 |
| 50 req/s | 129,600,000 | $25.92 | 6,480,000 | $108.00 | $133.92 |
So every 1 request/second of sustained load costs about $2.68 a month on Lambda, and the bill scales linearly. Now suppose (an assumed figure; substitute your real quote) a pair of small always-on containers that can comfortably serve 50 req/s costs $30 a month. The break-even is $30 / $2.68 per req/s, about 11.2 req/s sustained. Below that, FaaS is cheaper and you also skip the operations work; well above it, the containers win on cost. (This ignores the Lambda free tier of 1 million requests and 400,000 GB-seconds a month, and extras common to both, such as the API gateway, the managed service that receives HTTP requests and routes them to your function, billed per request, and logging charges.)
Most real traffic is not flat: an internal tool busy 2 hours a day and idle 22 costs FaaS almost nothing during the idle hours, while the containers bill all 24. That idle ratio, more than the peak rate, is what usually decides it.
When FaaS is a good fit versus a poor one
Good fit
- Event glue: react to an uploaded file, a queue message, a database change stream, a schedule (a nightly report), or a database change stream (a feed of row-level insert, update and delete events a database emits as they happen).
- Spiky or unpredictable traffic with long idle periods, where paying for idle replicas is waste.
- Low-to-moderate volume APIs where a few hundred ms of occasional cold-start latency is acceptable.
- Small teams that would rather not run a cluster.
Poor fit
- Steady, high-volume traffic above the break-even: you pay a premium for elasticity you are not using.
- Work longer than 15 minutes, or that needs a long-lived process (WebSocket servers, streaming consumers holding state, in-memory caches you rely on).
- Strict tail-latency targets where a cold start in the p99 (the 99th-percentile latency: the value only 1% of requests exceed) breaks the SLO (service-level objective), unless you pay to keep environments warm.
- GPU work, or large in-memory datasets that every environment would load separately.
My default: start event-driven and low-traffic workloads on FaaS, and move a component to containers when its measured sustained load passes the break-even, it hits a hard limit, or cold starts break its latency target.
Trade-offs and pitfalls
- "Serverless" still has servers, you just do not manage them. You gain speed and lose knobs: no choosing the OS, limited control over networking, CPU tied to the memory setting.
- Scaling can hurt what sits behind you. 1,000 concurrent functions can mean 1,000 database connections, and most relational databases cap total connections in the low hundreds (each one holds memory and overhead on the database server), so that alone can take the database down before it ever drops a request for load reasons. Relational databases need a connection proxy (a lightweight service that sits between many function instances and the database, holding a small pool of real database connections open and multiplexing many callers onto them) or a concurrency cap on the function (a hard ceiling on how many copies run at once, so the connection count never exceeds what the database can hold).
- Retries are part of the model. Asynchronous and queue triggers deliver at least once (a message may arrive more than once), so handlers must be idempotent: running twice has the same effect as once.
- Hidden line items: API gateway fees, log ingestion, NAT gateway (network address translation gateway: the managed component that lets resources inside a private network reach the internet, billed per hour and per GB) traffic for functions inside a private network. Price the whole path, not just the function.
- Vendor lock-in comes mostly from the triggers, permissions and managed services around the function, not the function code. Keeping business logic in plain modules the handler calls keeps a later move to containers cheap.
Unlock Full Question Bank
Get access to all 17 Serverless and Function-as-a-Service Architecture interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.