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.
You're leading a cross-functional evaluation to choose between serverless functions and containerized microservices for a new component, for example a CPU-bound batch or ingestion workload. Build an evaluation framework: what criteria would you weight (cost, latency, cold starts, scalability, operational complexity), how would you weight them, and what's your plan for a short pilot or spike to gather real evidence before committing?
Sample Answer
Direct answer
I would run this as a weighted decision matrix whose weights are agreed before anyone scores the options, followed by a time-boxed two-week pilot that measures the handful of criteria where the options actually differ, with pass/fail thresholds written down in advance. The matrix does not make the decision on its own: its real job is to show which criteria swing the result, so the pilot spends its time measuring those and not the ones that do not matter. For a CPU-bound batch or ingestion workload, the swing factors are almost always cost per unit of work and operational complexity, not cold starts.
Terms:
- Serverless functions (FaaS, functions as a service), for example AWS Lambda: code runs on demand, scales automatically, billed per request and per millisecond; each invocation is capped (15 minutes on Lambda).
- Containerized microservices: the component runs as long-lived containers on an orchestrator such as Kubernetes or a managed container service, billed for the capacity you keep running.
- Cold start: extra latency when the platform creates a new function environment.
- Spike: a short, throwaway experiment built to answer one question with evidence.
Step 1: set up the evaluation (week 0)
Who is in the room and what each owns:
| Stakeholder | Owns the evidence for |
|---|---|
| Engineering lead for the component | Build effort, code shape, team fit |
| SRE / platform (site reliability engineering) | Operational complexity, on-call load, observability |
| Finance or FinOps (cloud cost management) | Cost model at current and 3x volume |
| Security | Isolation, secrets, identity per workload |
| Product | Latency and freshness requirements, what "good enough" means |
Decision rules agreed up front:
- Criteria and weights are fixed before scoring, and signed off by the group. Changing weights after seeing scores is how teams launder a preference into a number.
- Hard constraints are gates, not weights. For example: a single task that needs more than 15 minutes, more than 10,240 MB of memory, or a GPU rules out Lambda regardless of score.
- Each criterion has a 1-5 scale defined in measurable terms (for cost, for example: 5 = under $50 per million records processed, 1 = over $200; every score in between is a number, not a feeling), so two people scoring the same evidence get the same number.
Step 2: criteria and weights
For a CPU-bound batch ingestion workload (say, nightly and hourly files that must be parsed, validated and loaded):
| Criterion | Weight | Why this weight for this workload |
|---|---|---|
| Cost per unit of work | 30 | CPU-bound and recurring, so compute dominates the bill |
| Scalability (fan-out, running many instances of the work in parallel, for backlogs, catch-up after outages) | 20 | Batch backlogs arrive in bursts |
| Operational complexity | 20 | Determines on-call load for years |
| Team fit (skills, existing platform) | 15 | Execution risk |
| Latency | 10 | Batch has a freshness target (how old the newest loaded data is allowed to be, for example "loaded within 1 hour of arriving"), not a per-request target |
| Cold starts | 5 | Almost irrelevant for batch; a few hundred ms on a minutes-long job is noise |
The ordering is itself a finding worth saying out loud to stakeholders: cold starts get most of the attention in serverless debates and deserve the least weight here.
Step 3: score, then find the swing factors
Illustrative scores before any pilot (1-5; these are the team's priors, which the pilot will replace):
weights = {"cost": 30, "latency": 10, "cold_starts": 5, "scalability": 20,
"ops_complexity": 20, "team_fit": 15} # sums to 100
scores = { # 1-5, illustrative until the pilot replaces them
"serverless": {"cost": 3, "latency": 4, "cold_starts": 3, "scalability": 5,
"ops_complexity": 4, "team_fit": 3},
"containers": {"cost": 4, "latency": 4, "cold_starts": 5, "scalability": 3,
"ops_complexity": 3, "team_fit": 4},
}
def total(opt, w): return sum(w[c] * scores[opt][c] for c in w) / 100
for opt in scores:
print(f"{opt}: {total(opt, weights):.2f} / 5")
# sensitivity: shift weight from scalability to cost, 5 points at a time
for shift in range(0, 21, 5):
w = dict(weights, cost=weights["cost"] + shift, scalability=weights["scalability"] - shift)
s, c = total("serverless", w), total("containers", w)
print(f"cost={w['cost']} scalability={w['scalability']}: serverless={s:.2f} containers={c:.2f} "
f"-> {'serverless' if s > c else 'containers' if c > s else 'tie'}")
serverless: 3.70 / 5
containers: 3.65 / 5
cost=30 scalability=20: serverless=3.70 containers=3.65 -> serverless
cost=35 scalability=15: serverless=3.60 containers=3.70 -> containers
cost=40 scalability=10: serverless=3.50 containers=3.75 -> containers
cost=45 scalability=5: serverless=3.40 containers=3.80 -> containers
cost=50 scalability=0: serverless=3.30 containers=3.85 -> containers
What this tells the group: the totals are 0.05 apart, and moving just 5 weight points from scalability to cost flips the winner. A matrix this close has not decided anything. It has told us exactly what to measure: the real cost per million records on each option, and whether serverless's scalability advantage is needed (how big do backlogs actually get?). Latency and cold starts score the same or barely matter, so the pilot should spend no time on them.
Step 4: the pilot (two weeks, time-boxed)
Hypotheses with thresholds, written before the pilot starts:
| Hypothesis | Measurement | Pass threshold (example) |
|---|---|---|
| Cost per million records on each option | Replay one representative day of real input; record billed duration or container-hours | The option within 20% of the cheaper one scores 5 on cost |
| Backlog catch-up | Inject a 6-hour backlog; time to drain | Drains within the 1-hour freshness target |
| Operational complexity | Count steps to deploy, roll back, and diagnose one injected failure; have an engineer outside the pilot team do it | Diagnose the injected failure in under 30 minutes using only the dashboards |
| Hard limits | Largest input file's processing time and memory | Largest task fits in 15 minutes with 30% margin, or it is split |
Build both options as thin as possible, against the same code. Keep the parsing and loading logic in one library; wrap it in a Lambda handler (fanned out with a Step Functions Distributed Map, AWS's managed workflow service's mode for processing large datasets in S3 object storage in parallel, which runs up to 10,000 child executions, separate parallel runs of the same workflow step, one per item or batch of the dataset, concurrently by default) and in a container job (a Kubernetes Job, a Kubernetes workload that runs a container to completion instead of keeping it running indefinitely, or an equivalent managed container task such as an ECS/Fargate task). This makes the comparison about the platform, not about two different implementations.
Guard against pilot bias: replay the same input on both; run each at least three times; report the spread, not the best run; and have the platform team, not the component team, score operational complexity.
Outcome: a one-page decision record (a short written artifact stating what was decided, why, and what would change it) with the measured numbers substituted into the matrix, the resulting scores, the sensitivity check re-run, the decision, and the conditions under which it would be revisited. Utilization is the right kind of trigger because a container's cost is fixed whether or not it is busy, while the FaaS option costs about the same per unit of work regardless of utilization, so above some utilization the fixed-cost container option becomes the cheaper one; the specific crossover is illustrative here (for example, "revisit if volume triples or average utilization of the container option would exceed 50%") and should be replaced, the same way $X and $Y were above, once the pilot has measured each option's real cost per unit of work.
Trade-offs and pitfalls
- Scoring before weighting turns the matrix into a justification for whatever the loudest person already wanted.
- Averaging away a hard constraint. A 15-minute timeout cannot be offset by good scores elsewhere; treat it as a gate or redesign the work into smaller tasks.
- A pilot on toy data. CPU-bound work scales with real file sizes and real skew; a synthetic dataset of uniform small files will flatter serverless.
- Letting the pilot become the production system by default. Time-box it and throw away what does not win.
- Ignoring team fit because it is "soft". A cheaper option the team cannot operate at 3 a.m. is not cheaper.
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.
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 long-running job (say, a Kubernetes job, or a managed batch or training service) needs to be triggered, tracked, and retried from your serverless layer. How do you pass parameters in, track progress, handle retries and idempotency if it fires twice, and notify on completion? Where does the workflow's own state actually live?
Sample Answer
Direct answer
The serverless function should start the job and then get out of the way. It should never wait for the job. A durable workflow engine (AWS Step Functions Standard, or equivalents such as Azure Durable Functions or Google Workflows) owns the run. The workflow's execution holds the state: the input parameters, the current step, retry counts and results are all stored in its execution history, not in any function's memory.
- A starter (a function or an event rule) starts an execution named after the request id, which makes a duplicate trigger harmless.
- The workflow submits the job through a "run a job and wait" integration, or a callback token (a one-time credential the workflow hands an external worker so that worker, not the workflow, decides when the step is done; covered in detail below).
- It retries defined failures with backoff (each retry waits longer than the last, instead of hammering the dependency again immediately).
- It publishes a completion or failure event that notifies whoever needs to know.
Why not keep this in a function
- A Lambda invocation lasts at most 15 minutes. Training and batch jobs run for hours.
- A function that polls for hours is paying to wait.
- If the environment is recycled, whatever it held in memory is gone.
A Standard workflow can run for up to a year, and it records every state transition.
Passing parameters in
- The execution input (JSON, up to 256 KiB: a kibibyte is 1,024 bytes, so about 256,000 bytes) carries the request id, the job type, and pointers to the data: input and output URIs.
- Large configuration or datasets travel by claim check: store them in object storage and pass the URI.
- The workflow maps the input into the job's own parameters (container environment variables, a Kubernetes Job spec, training hyperparameters).
Tracking progress
| Signal | Mechanism | Granularity |
|---|---|---|
| Which step the run is on | The workflow's execution status and history | Coarse, always available |
| Did the job finish | A .sync integration (the .sync suffix appended to the Resource ARN, shown below, tells Step Functions to submit the job and then wait, instead of firing it and moving straight to the next step): Step Functions waits and moves on when the job reaches a final state | Coarse |
| Percent complete, current epoch | The job writes a progress record (a key-value table item keyed by request id) that the UI reads | Fine |
| Is the job still alive | Callback pattern with a task token (a unique string Step Functions generates for this step and hands to whoever will eventually finish it; the workflow pauses right there until that same token is handed back): the job calls SendTaskHeartbeat (an API meaning "still working, do not time me out") on a schedule, and HeartbeatSeconds (the longest gap Step Functions allows between heartbeats) fails the task if heartbeats stop | Liveness |
Integration details matter.
- Step Functions' Amazon EKS (Elastic Kubernetes Service, managed Kubernetes)
runJob.syncintegration detects completion by polling: about once a minute at first, slowing to about once every 5 minutes. So completion can be noticed several minutes late. - The EKS integration does not support the callback pattern (the task-token approach above), and it only works with clusters whose Kubernetes API endpoint is public.
- For a private cluster, use callback instead. The workflow sends a message containing its task token to a queue:
sqs:sendMessage.waitForTaskTokenis the Resource suffix that tells Step Functions "send this message, then pause the state machine right here until someone calls back with this token." An in-cluster worker (something running inside the private cluster, able to reach it) picks the message off the queue, runs the Kubernetes job, and callsSendTaskSuccessorSendTaskFailure, passing the same token back, to tell Step Functions which paused execution to resume and how. - AWS Batch (a managed batch-job scheduler) and Amazon SageMaker (a managed machine learning platform) training jobs support
.syncdirectly.
Retries
- Infrastructure failures (spot capacity reclaimed: the cloud provider taking back the cheaper, interruptible compute it lent you, or a node lost) are retried closest to the job: AWS Batch's job
retryStrategy(how many times Batch itself resubmits the same job attempt before giving up), or KubernetesbackoffLimit(the same idea for a Kubernetes Job: how many failed pod attempts it tolerates). - Workflow-level
Retrycovers failures of the task itself, withIntervalSeconds,BackoffRateandMaxAttempts. - Bad input is not retried. A
Catchroutes it to the failure notification. - A
TimeoutSecondson the job state turns a job that hangs silently into a visible failure.
This is written in the Amazon States Language, the JSON-based language Step Functions state machines are defined in. A few conventions used below: a field ending in .$ (like JobName.$) takes a JSONPath expression instead of a literal value, so "$.requestId" means "read the requestId field out of this state's input," not the literal string $.requestId. Resource names the action to call using an ARN (Amazon Resource Name: AWS's standard way of pointing at one specific resource or action); the .sync on the end of arn:aws:states:::batch:submitJob.sync is what makes this state submit the job and wait, as described above. ResultPath: "$.job" tells Step Functions to write this state's output into a new job field alongside the existing input, instead of replacing the input outright, so later states can still read $.requestId and everything else. In plain terms, the numbers below mean: give the job up to TimeoutSeconds: 43200 (12 hours) to finish; on a States.TaskFailed error, wait IntervalSeconds: 60 (1 minute) and retry, and if it fails again wait 60 x BackoffRate: 2.0 = 120 seconds before the second and last retry (MaxAttempts: 2); anything else (States.ALL) skips retrying and goes straight to NotifyFailure. The two NotifySuccess/NotifyFailure states each publish to an SNS topic (Amazon Simple Notification Service, a managed pub/sub notification service; TopicArn is that topic's ARN).
{
"Comment": "Run one job per request and notify",
"StartAt": "RunJob",
"States": {
"RunJob": {
"Type": "Task",
"Resource": "arn:aws:states:::batch:submitJob.sync",
"Parameters": {
"JobName.$": "$.requestId",
"JobQueue": "arn:aws:batch:us-east-1:111122223333:job-queue/training",
"JobDefinition": "arn:aws:batch:us-east-1:111122223333:job-definition/train:3",
"ContainerOverrides": {
"Environment": [
{ "Name": "INPUT_URI", "Value.$": "$.inputUri" },
{ "Name": "OUTPUT_URI", "Value.$": "$.outputUri" }
]
}
},
"ResultPath": "$.job",
"TimeoutSeconds": 43200,
"Retry": [
{ "ErrorEquals": ["States.TaskFailed"], "IntervalSeconds": 60, "BackoffRate": 2.0, "MaxAttempts": 2 }
],
"Catch": [
{ "ErrorEquals": ["States.ALL"], "ResultPath": "$.error", "Next": "NotifyFailure" }
],
"Next": "NotifySuccess"
},
"NotifySuccess": {
"Type": "Task",
"Resource": "arn:aws:states:::sns:publish",
"Parameters": {
"TopicArn": "arn:aws:sns:us-east-1:111122223333:job-events",
"Message.$": "States.Format('request {} succeeded', $.requestId)"
},
"End": true
},
"NotifyFailure": {
"Type": "Task",
"Resource": "arn:aws:states:::sns:publish",
"Parameters": {
"TopicArn": "arn:aws:sns:us-east-1:111122223333:job-events",
"Message.$": "States.Format('request {} failed', $.requestId)"
},
"Next": "Failed"
},
"Failed": { "Type": "Fail" }
}
}
Idempotency when the trigger fires twice
Handle it at three levels:
- The execution name is the request id. For Standard workflows, starting an execution with a name and input that match a running execution returns that same execution. If the execution has already closed, the call fails with
ExecutionAlreadyExists, which the starter treats as "already done". Express workflows (a cheaper, higher-throughput Step Functions mode built for short-lived, high-volume executions, with at-least-once semantics and no long execution history) do not give this guarantee, which is one more reason to use Standard here. - The job name or output path is deterministic. Reusing the request id as the job name (and as the output prefix) means a manual re-run overwrites rather than duplicates. Some services enforce this for you: a SageMaker training job name must be unique in the account and Region, so a second create with the same name is refused.
- Consumers of the completion event can deduplicate on the request id, because the notification itself can also arrive twice.
Notifying on completion
- The final states publish to a topic or event bus, as in the definition above.
- Step Functions also emits execution status-change events to EventBridge, so downstream systems can subscribe without the workflow knowing about them.
- Notify on failure as well as success. A job that fails silently is the common incident.
Where the state actually lives
| State | Lives in |
|---|---|
| Request record (who asked, for what) | A database table keyed by request id, for API lookups |
| Workflow progress, retries, step results | The workflow execution's history |
| Job-internal progress and checkpoints | The job's own storage (object storage checkpoints) plus the progress record |
| Logs | The job's log stream |
| In any function | Nothing that must survive the invocation |
sequenceDiagram
participant API as Starter function
participant WF as Workflow execution
participant JOB as Batch or Kubernetes job
participant BUS as Topic or event bus
API->>WF: StartExecution(name = requestId, input)
WF->>JOB: submit job and wait
JOB-->>WF: final state SUCCEEDED or FAILED
WF->>BUS: publish completion or failure
Pitfalls
- A function polling job status in a loop. It costs money, times out at 15 minutes, and loses its state.
- Random execution names. Every duplicate trigger then starts a new, expensive job.
- Retrying everything, including jobs that failed on bad input.
- Stopping the workflow and assuming the job stopped. Step Functions only makes a best-effort attempt to cancel
.syncjobs, so a stopped execution can leave a job running and billing.
Serverless functions triggered by an at-least-once delivery system (like SQS or Pub/Sub) can receive the same event more than once. What patterns would you use to make a handler idempotent in that situation, and what are the performance and storage trade-offs between them?
Sample Answer
Direct answer
"At-least-once" means the platform promises never to lose an event but may deliver it more than once. That happens after a timeout, a crash between processing and acknowledging, or a retry. Since duplicates are guaranteed to happen eventually, the handler must make the effect happen once even when the delivery happens twice. There are four patterns, in order of preference:
- make the operation naturally idempotent: a plain
set, an upsert (insert the row if it is missing, otherwise overwrite it, so replaying it twice changes nothing), or a compare-and-set (write a new value only if the current value still equals what you last read, so a stale retry is rejected instead of double-applying) instead of anincrement - record an idempotency key (a value that identifies this one specific delivery, so a lookup can answer "have I already handled this?" before doing the work again) in the same transaction as the effect
- keep an idempotency record with an in-progress lock and a cached result when the effect lives in another system
- pass the key downstream to APIs that accept one
Broker-level deduplication (for example, the 5-minute window on an Amazon SQS FIFO, first-in first-out, queue) helps, but it does not replace any of these. The trade-offs are one extra conditional write per message (a write the store performs only if a condition on the current data holds, for example "only if this key does not already exist", checked and applied atomically so two concurrent writers cannot both succeed), storage that grows with rate x retention window, and correctness gaps that depend on the order in which you record the key and perform the effect.
Choosing the key
- Use a business identity (
orderId + eventType, or the object's bucket + key + version) rather than the broker's message id. A producer that retries a send creates a new message id carrying the same content. - Never hash the whole payload if it contains timestamps or trace ids. Two copies of the same event would produce different keys.
The ordering problem, demonstrated
The dangerous part is not the lookup. It is what happens when the process dies between the two writes. This demo uses a local SQLite database to model three orderings of "record the key" and "apply the effect". The first delivery crashes, and then the event is delivered twice more:
import sqlite3
class Crash(Exception):
pass
def fresh():
db = sqlite3.connect(":memory:", isolation_level=None)
db.execute("CREATE TABLE account (id TEXT PRIMARY KEY, balance INTEGER)")
db.execute("CREATE TABLE processed (msg_id TEXT PRIMARY KEY)")
db.execute("INSERT INTO account VALUES ('A', 0)")
return db
def check_then_mark(db, msg, crash):
if db.execute("SELECT 1 FROM processed WHERE msg_id=?", (msg["id"],)).fetchone():
return
db.execute("UPDATE account SET balance = balance + ? WHERE id='A'", (msg["amount"],))
if crash:
raise Crash() # dies after the side effect, before recording it
db.execute("INSERT INTO processed VALUES (?)", (msg["id"],))
def mark_first(db, msg, crash):
try:
db.execute("INSERT INTO processed VALUES (?)", (msg["id"],))
except sqlite3.IntegrityError:
return
if crash:
raise Crash() # dies after claiming, before the side effect
db.execute("UPDATE account SET balance = balance + ? WHERE id='A'", (msg["amount"],))
def same_transaction(db, msg, crash):
db.execute("BEGIN")
try:
db.execute("INSERT INTO processed VALUES (?)", (msg["id"],))
db.execute("UPDATE account SET balance = balance + ? WHERE id='A'", (msg["amount"],))
if crash:
raise Crash()
db.execute("COMMIT")
except sqlite3.IntegrityError:
db.execute("ROLLBACK") # duplicate: nothing to do
except Crash:
db.execute("ROLLBACK") # models the transaction dying with the process
raise
msg = {"id": "m-1", "amount": 50}
for handler in (check_then_mark, mark_first, same_transaction):
db = fresh()
try:
handler(db, msg, crash=True) # first delivery crashes, so the queue redelivers
except Crash:
pass
handler(db, msg, crash=False) # redelivery
handler(db, msg, crash=False) # plus one ordinary duplicate
print(f"{handler.__name__:17} balance={db.execute('SELECT balance FROM account').fetchone()[0]} (correct: 50)")
rate, window_s, bytes_per_key = 500, 24 * 3600, 100
keys = rate * window_s
print(f"dedup keys held for a 24 h window at {rate}/s: {keys:,} (~{keys * bytes_per_key / 1e9:.1f} GB at {bytes_per_key} B each)")
check_then_mark balance=100 (correct: 50)
mark_first balance=0 (correct: 50)
same_transaction balance=50 (correct: 50)
dedup keys held for a 24 h window at 500/s: 43,200,000 (~4.3 GB at 100 B each)
- Check, then act, then mark: the crash happens after the money moved but before the key was recorded. The redelivery applies it again, so balance 100: double effect.
- Mark first, then act: the key is recorded and then the crash happens. The redelivery sees the key and skips, so balance 0: lost effect. The message was acknowledged as done when it wasn't.
- Key and effect in one transaction: either both happen or neither does, so balance 50: correct. In DynamoDB (Amazon's managed key-value and document database) the equivalent is
TransactWriteItems, which commits several writes as one all-or-nothing operation: a conditional put on the key that only succeeds ifattribute_not_exists(the item is not already there) holds, plus the update.
The patterns and their costs
| Pattern | Extra latency per message | Storage | Remaining gap | Use when |
|---|---|---|---|---|
Natural idempotency (upsert by key, SET status='PAID', or a conditional update on a version number, a form of optimistic concurrency: write only if the row's version still matches the one you read, then bump it) | None | None | None | The operation can be written as "set to X" instead of "add X" |
| Key + effect in one transaction | One extra write inside the same transaction | One row per key for the window | None | The effect is in the same database as the key table |
Idempotency record with lock (conditional put INPROGRESS, do the work, update to COMPLETE with the cached response). Powertools for AWS Lambda, AWS's open-source handler utility library, implements this | Two extra round trips to the store | Key + cached response, for the window | If the external call succeeds and the COMPLETE write fails, the in-progress record eventually expires and the work reruns. The external system must also be idempotent | The effect is an external API or a different datastore |
| Downstream idempotency key (payment and email APIs that accept one) | None for you | Held by the provider, for the provider's window | Only as long as the provider's window | Calling third parties |
Broker dedup (SQS FIFO MessageDeduplicationId) | None | None for you | Only stops duplicate sends within 5 minutes. A redelivery after the visibility timeout (the window a queue hides a message from other consumers while one is working on it; if that consumer does not finish and delete it in time, the message reappears) still happens | Cheap first layer, never the only one |
The lock in the third pattern matters because two copies of the same event can run concurrently on two function instances. The conditional put makes exactly one of them the owner. The other gets "already in progress" and should fail and retry later, not proceed.
The remaining gap, with a timeline. Say the in-progress record expires after 1 hour. At t = 0 min instance A wins the conditional put, marks the record INPROGRESS, and calls the external API. At t = 45 min A is still waiting on a slow call. At t = 60 min the record expires, so at t = 61 min a redelivery lands on instance B, sees no live record, wins a fresh conditional put, and starts the same external call again while A's original call may still be in flight. Sizing the expiry comfortably above your slowest realistic call, and above the external system's own retry window, is what keeps this gap rare rather than routine.
Storage and performance
- Storage grows with rate x window. At 500 events per second with a 24-hour window, that is 43,200,000 keys, about 4.3 GB at 100 bytes each (from the script). Expire keys with a time-to-live (TTL). DynamoDB TTL deletion runs in the background and is not immediate, so filter on the expiry attribute when reading.
- The window must cover the longest possible redelivery, not the typical one. The worst case is the queue's retention (up to 14 days on SQS), async retry age (up to 6 hours on Lambda), or a manual redrive (an operator replaying the stuck messages back onto the source queue) from the dead-letter queue (DLQ: a separate queue a message is moved to once it exhausts its retries, so it can be inspected and replayed by hand instead of being silently dropped) days later. The Powertools default expiry is 1 hour. It is too short if someone redrives a DLQ a day later.
- Latency. A conditional write is one round trip to the key-value store, per message. For batches, pre-filter with one batch read and then do conditional writes only for the unseen keys.
- Hot keys. A hot key is one key taking a disproportionate share of traffic. Here, duplicates of the same event land on the same key, and the lock serializes them (each one waits its turn instead of running in parallel), so that single key shows up as contention (many requests queued behind one item) on dashboards even though the behaviour is correct.
Pitfalls
- Deduplicating on message id. Producer retries slip through.
- An in-memory set of seen ids. Every environment has its own, and it is lost on recycle.
- Recording the key before the effect (the lost-update case above).
- A dedup window shorter than your retry and redrive horizon.
- Returning a different response on the duplicate than on the original. Cache the first result so callers see the same answer both times.
Unlock Full Question Bank
Get access to all 12 Serverless and Function-as-a-Service Architecture interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.