BayLearnBayAreaLa8s

BayLearn Interview Sprints

AWS Serverless Engineer Interview Sprint — Trigger It. Process It. Scale It. Recover It.

Prepare for AWS serverless interviews with Lambda, API Gateway, SQS, EventBridge, DynamoDB, Step Functions, production labs, troubleshooting, and a scored mock interview.

Refund terms are drafted and are not a current offer. Refund policy

4-Hour Live 1:1 Intensive
Lambda + API + SQS + DynamoDB
EVENT + SIGNAL frameworks
Serverless Order Platform Lab
380+ Interview Questions
Mock Interview + Feedback

Curriculum

Short lessons in interview order. The production lab runs on your machine with mocked AWS — BayLearn does not execute candidate AWS accounts.

·

You will

  • See the full lesson path before you book
  • Know this is a Serverless Engineer interview sprint, not a service-definition tutorial

Course overview5 min

Course overview

AWS Serverless Engineer Interview Sprint

Trigger the work. Process it. Scale the hop that needs it. Recover when it fails.

EVENT interview framework Do not start with service logos. Name the user action, the fact, the first async boundary, then failure. EEstablish reqs + facts VVolume / velocity EExecution + state NNeutralize failure TTrace + trade-offE: who acts, do they wait, what fact is published, who is allowed. V: burst, payload, slowest downstream. Second E: first async boundary in ink.N: retries, DLQ, idempotency key, timeout formula, IAM. T: correlation, cost, the design you rejected.Fail phrase: 'We will use Lambda, API Gateway, SQS, EventBridge, DynamoDB, and Step Functions' before requirements. What do you name before you draw the first AWS logo?
EVENT interview framework
Serverless request flow The request path is a contract: auth, validate, mutate, persist, respond — Lambda is one hop, not the architecture. Client API Gatewayauth + limits Lambdavalidate + mutate DynamoDBitem + condition Response200 / 4xxInterview: name the trust boundary (JWT/IAM), the write key, and what happens if DynamoDB throttles. Do not start with 'we use Lambda'.Sync request path stays short. Anything that can retry independently leaves this hop for a queue. What sits in front of Lambda on a user-facing write?
Serverless request flow
Order processing lab LAB-SVL-501: API accepts an order, queue processes it, table stores it, bus notifies, machine recovers — then destroy the stack. HTTP APIPOST /orders Lambdavalidate SQSwork Worker + DDBidempotent EventBridge + SFnnotify / sagaDefault path is local pytest with mocked AWS. Optional Terraform is tagged, budgeted, and destroyed. Cost warning lives in the lab README.Interview: I can draw this, name the idempotency key, the DLQ, and the compensation. I do not leave a lab stack running overnight. What is the cheapest correct default for LAB-SVL-501?
Order processing lab

This BayLearn weekend sprint prepares AWS serverless, backend, and platform engineers to design, implement, and defend production systems built on Lambda, API Gateway, SQS, EventBridge, DynamoDB, and Step Functions. It is not a service-definition tour. You will choose sync versus async boundaries, model access patterns before keys, handle at-least-once delivery, and explain what happens when a write succeeds and the response never returns.

The live spine is four hours. Self-paced lessons are deep dives: each topic walks the mechanism, shows detailed diagrams, uses the order platform as a running example, and ends with how to open, common mistakes, and interview tips.

  • Module 0 — readiness diagnostic (25 scenarios)
  • Module 1 — Lambda + API Gateway: lifecycle, concurrency, contracts, timeout budgets
  • Module 2 — messaging: facts on the bus, work on the queue, orchestration when you need a saga
  • Module 3 — DynamoDB from access patterns
  • Module 4 — reliability, security, observability, cost (EVENT + SIGNAL)
  • Module 5 — LAB-SVL-501 local order platform
  • Module 6 — scored mock
  • Module 7 — feedback and seven-day plan

Practice materials include 380+ questions, 25 coding challenges, 15 architecture reviews, 32 SIGNAL scenarios, 10 DynamoDB exercises, and 40 architecture diagrams. Look up current service limits and prices when you implement; this course will not drill stale quotas.

The completion certificate is a BayLearn course credential. It is not an AWS certification, not an endorsement by Amazon, and not a hiring guarantee.

Start here

Start here

Start here

Trigger the work. Process it. Scale the hop that needs it. Recover when it fails.

EVENT interview framework Do not start with service logos. Name the user action, the fact, the first async boundary, then failure. EEstablish reqs + facts VVolume / velocity EExecution + state NNeutralize failure TTrace + trade-offE: who acts, do they wait, what fact is published, who is allowed. V: burst, payload, slowest downstream. Second E: first async boundary in ink.N: retries, DLQ, idempotency key, timeout formula, IAM. T: correlation, cost, the design you rejected.Fail phrase: 'We will use Lambda, API Gateway, SQS, EventBridge, DynamoDB, and Step Functions' before requirements. What do you name before you draw the first AWS logo?
EVENT interview framework
SIGNAL incident framework Async systems fail in a different hop than they were triggered. Guessing 'Lambda bug' is how you miss a rule mismatch. SScope impact IInspect metrics GGather traces NNarrow domain AApply safe fix LLearn / preventAge without depth = poison. Depth without errors = capacity. TriggeredRules at zero = routing, not the worker.Mitigations that are rarely safe: purge a production queue, raise retries to infinity, leave DEBUG of full events on.Interview: I pick one primary domain before I change three knobs. L is a test + alarm, not 'be more careful'. What do you inspect before you open the worker logs?
SIGNAL incident framework

This is a Serverless Engineer interview sprint, not a service-definition tutorial. Self-paced lessons are deep dives with detailed diagrams. The live session still spends four hours on your highest-risk gaps.

Read EVENT before you draw logos. Use SIGNAL before you guess a Lambda bug. Treat exactly-once as an application invariant, not a platform promise.

Then take the readiness assessment. Write down the two weakest skills. Those two skills decide how the instructor uses the remaining hours.

EVENT framework

EVENT framework

EVENT framework — deep dive

In one sentence: Do not start with service logos. Name the user action, the fact, the first async boundary, then failure.

EVENT interview framework Do not start with service logos. Name the user action, the fact, the first async boundary, then failure. EEstablish reqs + facts VVolume / velocity EExecution + state NNeutralize failure TTrace + trade-offE: who acts, do they wait, what fact is published, who is allowed. V: burst, payload, slowest downstream. Second E: first async boundary in ink.N: retries, DLQ, idempotency key, timeout formula, IAM. T: correlation, cost, the design you rejected.Fail phrase: 'We will use Lambda, API Gateway, SQS, EventBridge, DynamoDB, and Step Functions' before requirements. What do you name before you draw the first AWS logo?
EVENT interview framework
Serverless request flow The request path is a contract: auth, validate, mutate, persist, respond — Lambda is one hop, not the architecture. Client API Gatewayauth + limits Lambdavalidate + mutate DynamoDBitem + condition Response200 / 4xxInterview: name the trust boundary (JWT/IAM), the write key, and what happens if DynamoDB throttles. Do not start with 'we use Lambda'.Sync request path stays short. Anything that can retry independently leaves this hop for a queue. What sits in front of Lambda on a user-facing write?
Serverless request flow
Sync vs async invocation If the caller must wait for the result, stay sync. If work can retry independently, leave the request path. SynchronousAPI Gateway / ALB / Function URL waits AsynchronousSQS / EventBridge / SNS / S3 → LambdaSync owns the user latency budget and the 29s API Gateway ceiling. Async owns retries, DLQ, and at-least-once delivery.Interview: I do not hide a 30-second payment workflow behind a sync Lambda. I enqueue, return 202 + id, and let the worker recover. When must work leave the request path?
Sync vs async
Multi-region serverless Active-active is a data-plane problem. DNS failover is not a DynamoDB story. Region AAPI + Lambda + table + replica source Region Breplica / active-active + idempotencyGlobal tables replicate items, not in-flight SQS. Idempotency keys and conflict strategy are the design. RPO/RTO are spoken first.Interview: I do not say 'we are multi-region' because Route 53 exists. I say what happens to a message that was invisible in region A. What does a global table replicate — and what does it not?
Multi-region serverless

Why this matters

Starting with “we will use Lambda, API Gateway, SQS, EventBridge, DynamoDB, and Step Functions” before requirements is a fail. EVENT exists to stop that sentence. Staff candidates live in the last two letters.

E — Establish requirements and events

Name users, the business action, the facts that must be published, whether the caller waits, latency and consistency, and who is allowed. If you cannot name OrderCreated as a past-tense fact, you are still in requirements.

V — Validate volume, velocity, variability

Steady versus burst, payload size, growth, and the slowest downstream’s safe rate. Campaign traffic without a warehouse number is fiction.

E — Establish execution, eventing, and state

Assign API Gateway, Lambda, SQS, EventBridge, Step Functions, DynamoDB, and S3 only where a requirement demands them. Draw the first async boundary in ink. If a step is one function, you may not need a state machine. If a consumer needs a backlog, do not publish directly to Lambda from the bus.

N — Neutralize failure and secure boundaries

Classify retries, place DLQs, pick idempotency keys, set timeout budgets, authenticate and authorize, encrypt, least privilege. AR-01 through AR-15 are N failures.

T — Trace, tune, and trade off

Correlation, alarms, cost, concurrency, and the alternative you rejected (maybe not serverless). Multi-region is only in play when you can name what a global table does not replicate (in-flight SQS, execution state) and what happens to a message that was invisible in region A.

How to open (say it)

“I will use EVENT. First the user action and whether they wait. Then volume. Then the first async boundary.”

Worked sketch — checkout

  • E: Customer places an order; they wait for an id, not for the warehouse.
  • V: Sale burst 20×; warehouse safe rate is low — reserved concurrency on the worker.
  • E: HTTP create → Dynamo + outbox → EventBridge → SQS fulfillment.
  • N: Idempotency-Key, visibility formula, DLQ, per-function roles.
  • T: One correlation id; age + DLQ alarms; rejected “one Lambda does it all.”

Common mistakes

COMMON MISTAKE: Logo-first architecture.

COMMON MISTAKE: Skipping V so every function shares one reserved pool.

INTERVIEW TIP: Write EVENT down the left margin of the board. Tick the letters as you talk.

SIGNAL framework

SIGNAL framework

SIGNAL framework — deep dive

In one sentence: Guessing “Lambda bug” is how you miss a rule mismatch. SIGNAL keeps you from changing three knobs before you pick a domain.

SIGNAL incident framework Async systems fail in a different hop than they were triggered. Guessing 'Lambda bug' is how you miss a rule mismatch. SScope impact IInspect metrics GGather traces NNarrow domain AApply safe fix LLearn / preventAge without depth = poison. Depth without errors = capacity. TriggeredRules at zero = routing, not the worker.Mitigations that are rarely safe: purge a production queue, raise retries to infinity, leave DEBUG of full events on.Interview: I pick one primary domain before I change three knobs. L is a test + alarm, not 'be more careful'. What do you inspect before you open the worker logs?
SIGNAL incident framework
Observability and tracing A request id must survive the hop from API Gateway to Lambda to DynamoDB to the queue. requestId xray / OTel#f8e7a8 log group metrics / SLI alarm + runbook#dcfce7SIGNAL: Symptom, Impact, Glimpse (recent change), Next hop, Analyze traces, Last control. Do not start with 'restart the function'.Interview: I can jump from a 5xx to the trace, the log line with the item key, and the SQS message id. Dashboards without ids are decoration. Which identifiers do you keep across API Gateway, Lambda, and SQS?
Observability and tracing
Correlation id path Mint or accept one id at the edge. Pass it through every hop. Four uuids is how you cannot operate the system. API GWrequest id Lambdax-correlation-id Dynamo itemsame id Event / SQSattribute Worker logsjoin keyAlso put it on the outbox item and Step Functions state. Dashboards without a join key are decoration.SIGNAL uses this id in G: gather the last span and the item key. Do not DEBUG the full event in production (T-28).Interview: I can jump from a 5xx to the trace, the Dynamo key, and the SQS message id. Which identifiers do you keep across API Gateway, Lambda, and SQS?
Correlation id path

Why this matters

The sprint grades 32 troubleshooting scenarios. Candidates who jump to the worker lose T-14 (routing), T-04 (edge), and T-25 (KMS). SIGNAL is the incident spine.

S — Scope the impact

Who is hurt, which journey, blast radius, start time, whether writes persist. A 403 for one partner is not a 5xx for everyone.

I — Inspect metrics and events

Throttles, duration versus timeout, depth versus age, TriggeredRules, DynamoDB throttles, KMS denies.

  • Age without depth → poison (T-08)
  • Depth without errors → capacity (T-07)

G — Gather logs and traces

Correlation id, last span, REPORT Init Duration, exact table name, exact event source.

N — Narrow the failure domain

Ingress, Lambda, queue, routing, database, IAM, networking, dependency, configuration, code. Pick one primary domain before you change three knobs.

A — Apply a safe mitigation

Rollback an alias, stop a mapping, raise visibility, restore a key policy, disable DEBUG. Purging a production queue is rarely safe. Infinite retries are not a mitigation (AR-15).

L — Learn and prevent

A regression test, an alarm, a design change (outbox, DLQ, contract test). If L is “be more careful,” you are not done.

Worked micro-example (T-14)

Symptom: orders exist, fulfillment silent.

  • S: only fulfillment, all tenants, since 14:10
  • I: PutEvents success, TriggeredRules zero
  • G: sample event source is orders.service, rule still matches app.orders
  • N: routing, not the worker
  • A: dual-match sources, replay from outbox
  • L: contract test on source

Practice T-10 (visibility) and T-25 (KMS) the same way before the mock.

How to open (say it)

“I will scope impact, then metrics, then traces. I will not open the worker first if TriggeredRules is zero.”

Common mistakes

COMMON MISTAKE: Restart the function as step one.

COMMON MISTAKE: Mitigation = purge.

INTERVIEW TIP: Say the six letters, then pick a domain. Interviewers listen for the order.

You will

  • Answer 25 scenario questions
  • Show weak categories to the instructor before the live session

How the assessment works5 min

How the assessment works

How the readiness assessment works — deep dive

In one sentence: The assessment is a map, not a medal. Skill bars decide the live path. Nothing is sent to an employer as a hiring recommendation.

EVENT interview framework Do not start with service logos. Name the user action, the fact, the first async boundary, then failure. EEstablish reqs + facts VVolume / velocity EExecution + state NNeutralize failure TTrace + trade-offE: who acts, do they wait, what fact is published, who is allowed. V: burst, payload, slowest downstream. Second E: first async boundary in ink.N: retries, DLQ, idempotency key, timeout formula, IAM. T: correlation, cost, the design you rejected.Fail phrase: 'We will use Lambda, API Gateway, SQS, EventBridge, DynamoDB, and Step Functions' before requirements. What do you name before you draw the first AWS logo?
EVENT interview framework
Serverless request flow The request path is a contract: auth, validate, mutate, persist, respond — Lambda is one hop, not the architecture. Client API Gatewayauth + limits Lambdavalidate + mutate DynamoDBitem + condition Response200 / 4xxInterview: name the trust boundary (JWT/IAM), the write key, and what happens if DynamoDB throttles. Do not start with 'we use Lambda'.Sync request path stays short. Anything that can retry independently leaves this hop for a queue. What sits in front of Lambda on a user-facing write?
Serverless request flow

Why this exists

Twenty-five scenario items, fifteen minutes. You get a percent, a band, and per-skill bars. Instructors see the same record. A high score is not permission to skip EVENT sketches — interviewers will still ask you to draw. A score here does not mean you will or will not get hired.

Skills

Lambda, API / API Gateway, messaging, event architecture, DynamoDB, reliability, security, observability, system design.

Each item has four choices, one correct index, an explanation, and why-wrong notes. Some include a snippet — many traps live in the code, not the stem.

How instructors use the result

Weak barLive session starts here
MessagingQueue versus bus on a blank board
DynamoDBAccess-pattern worksheet, not single-table folklore
ReliabilityTimeout-after-write until you can name the key
SecurityIsolation walk: JWT → condition → KMS
ObservabilityAge vs depth, then SIGNAL on T-14

If you disagree with an item, write why. The mock tests whether you can defend that disagreement with a design.

How to take it

Do not speed-run. If you finish early, revisit IAM versus KMS and queue versus bus. The later question bank (380+) is separate practice — readiness is the pretest.

Do not paste items onto public solution sites.

After you submit

Write down the two weakest skills. Module 7 turns them into a seven-day plan. Open EVENT and the request-flow diagram before Module 1 if the pretest felt abstract.

Readiness Assessment15 min

Readiness Assessment

Module 0 — Serverless readiness assessment

This module is a 15-minute diagnostic. It is not a certification and not a hiring screen. Twenty-five scenario items map onto Lambda, API Gateway, messaging, DynamoDB, reliability, security, observability, cost, and system design. Your instructor reads the skill bars before a live session. Answer the system you would ship, not a line you memorized. Trigger the work, process it, scale the hop that needs it, and recover when it fails.

What it measures

Whether you can choose sync versus async, spot a missing DLQ, refuse a status partition key, and explain a timeout after a successful write. Formats include architecture choice, failure vignettes, configuration review, and short code or event snippets.

Bands: Foundation, Developing, Interview Capable, Interview Ready, Advanced. They describe practice priority, not your worth as an engineer.

How to take it

Work honestly. A lucky guess hides a gap the mock will still probe. After scoring, do not skip DynamoDB because Lambda trivia went well — the rubric weights data modeling heavily.

Open diagrams/01-serverless-request-flow.svg if a question names an order create path. Write down the two weakest skills; Module 7 will turn them into a seven-day plan.

After you submit

Continue into Module 1 even if the band is Advanced. The sprint is defense practice, not a badge hunt. If the band is Foundation, still run the lab locally; the code is the tutor.

Related: content/lessons/how-the-assessment-works.md.

25 scenario questions. Each card is tagged with the skill it scores. Open a card to read the prompt and the four choices.

  1. Reserved concurrency equal to expected peak, hoping the runtime stays warm
  2. Provisioned concurrency on the alias serving checkout, sized to the sale forecast
  3. Unreserved account concurrency so every function can steal capacity
  4. A recursive async invoke loop to keep environments warm

Scored take: enroll, open Learn, then this same lesson. One question at a time. After 15 you see your band and eight skill scores.

You will

  • Say when Init runs relative to Invoke
  • Choose REST API when you need keys, WAF, private APIs, validation, or cache

Lambda and API Gateway20 min

Lambda and API Gateway

Lambda and API Gateway — deep dive

In one sentence: The request path is a contract — auth, validate, mutate, persist, respond. Lambda is one hop, not the architecture.

Serverless request flow The request path is a contract: auth, validate, mutate, persist, respond — Lambda is one hop, not the architecture. Client API Gatewayauth + limits Lambdavalidate + mutate DynamoDBitem + condition Response200 / 4xxInterview: name the trust boundary (JWT/IAM), the write key, and what happens if DynamoDB throttles. Do not start with 'we use Lambda'.Sync request path stays short. Anything that can retry independently leaves this hop for a queue. What sits in front of Lambda on a user-facing write?
Serverless request flow
Lambda handler shape The handler is a contract pipeline. Clients live outside it. Timeouts on outbound HTTP are tighter than the function timeout. 1. Parseevent + headers 2. Validateschema / 400 3. Authorizetenant + owner 4. Write oncecondition / key 5. Proxy bodystring + statusSDK clients and config load in Init (module scope). The handler must stay deterministic for a given event + collaborators.Interview: I can point to where a 400, 403, 409, and 201 are decided. I never hide a 40-second vendor call in step 4.502 at API Gateway usually means step 5 returned a dict body or a missing statusCode — prove invoke count before you debug Python. Where do you construct the DynamoDB client — and why?
Handler shape
Sync vs async invocation If the caller must wait for the result, stay sync. If work can retry independently, leave the request path. SynchronousAPI Gateway / ALB / Function URL waits AsynchronousSQS / EventBridge / SNS / S3 → LambdaSync owns the user latency budget and the 29s API Gateway ceiling. Async owns retries, DLQ, and at-least-once delivery.Interview: I do not hide a 30-second payment workflow behind a sync Lambda. I enqueue, return 202 + id, and let the worker recover. When must work leave the request path?
Sync vs async

Why this matters

Most serverless interview failures happen in the first five minutes: the candidate starts naming services, then hides a 40-second warehouse call behind POST /orders. Interviewers are testing whether you protect the user latency budget and leave long or fragile work for a queue.

The order platform in this sprint is the running example. Create must return a durable id. Fulfillment must not run inside the HTTP hop.

How the request path actually works

  1. A client calls API Gateway (HTTP API or REST API).
  2. The authorizer answers who is this?
  3. Lambda parses the proxy event, validates the body, and answers may they create this order?
  4. DynamoDB stores the order (and usually an idempotency / outbox item) under a condition.
  5. The function returns a string body and a status code. API Gateway maps that to HTTP.

If step 4 is a vendor workflow, you have the wrong shape. Accept, persist, enqueue, return 201 or 202 with an id.

Handler shape you should be able to recite

StepFail closedTypical status
ParseMalformed JSON / missing path400
ValidateSchema, totals, currency400
AuthorizeTenant and owner from the token403
Write onceCondition / idempotency key201 or 409
RespondstatusCode + string body200-family or mapped 4xx

SDK clients live at module scope so Init pays for them once. Outbound HTTP timeouts must be tighter than the function timeout so you fail before the platform kills you mid-write.

Concurrency in one picture

Lambda concurrency Account concurrency is a shared ceiling. Reserved carves a pool. Provisioned keeps environments warm. Account poolshared burst + limit Reservedguaranteed for this fn Provisionedwarm Init paid forReserved concurrency also caps the function. A reserved=5 checkout function cannot stampede the account — and cannot scale past 5.Interview: I isolate a noisy neighbor with reserved. I buy provisioned only when p99 Init misses the SLA. Quotas are not memorized — I check the current account/region. What does reserved concurrency guarantee — and what does it cap?
Lambda concurrency
  • Account concurrency is a shared ceiling. Checkout and a replay job compete unless you isolate them.
  • Reserved concurrency guarantees a pool and caps that function. Reserved = 5 cannot stampede the account — and cannot scale past 5.
  • Provisioned concurrency is a latency spend: you pay to skip Init on an alias. It does not make a warehouse faster.

Do not share a tiny reserved pool between checkout and a backfill.

How to open (say it)

“I will keep the HTTP hop short: authenticate, authorize, write durable state, return an id. Anything that can retry independently leaves this path for a queue.”

Real world — BayPay checkout

Customer taps Pay. Mobile retries if the radio drops. You accept Idempotency-Key, write ORDER#… once, enqueue fulfillment, return 201. The warehouse worker is a different function with its own reserved concurrency and DLQ. If DynamoDB throttles, you return 429/503 with retry guidance — you do not start a second order id.

If they ask

“Why not one Lambda that does everything?”

Because timeouts, retries, and blast radius differ. The HTTP function owns the contract. The worker owns at-least-once delivery.

“What if the write succeeds and the client never sees 201?”

That is the timeout-after-write story. The next lesson pair (lifecycle + idempotency) is how you survive it.

“HTTP API or REST API?”

Feature choice. See the API Gateway lesson. I will not pick REST “because enterprise” without a named feature.

Common mistakes

COMMON MISTAKE: Starting the whiteboard with six AWS logos and no user action.

COMMON MISTAKE: Treating 502 as “Lambda crashed” when invocations are flat — that is usually an illegal proxy response or an authorizer 403.

INTERVIEW TIP: Number the boxes. Tick the first async boundary in ink before you name SQS.

What to sketch

Client → API Gateway → Lambda → DynamoDB → (optional) queue. Label the trust boundary, the write key, and what happens if DynamoDB throttles.

Lambda lifecycle10 min

Lambda lifecycle

Lambda lifecycle — deep dive

In one sentence: Init runs once per execution environment. Invoke is the billable request. Freeze is reuse — not a new process and not a guaranteed singleton.

Lambda lifecycle Init runs once per execution environment. Invoke is the billable request. Freeze is reuse, not a new cold start. Initruntime + handler import Invokeevent → result Freezeenv kept warm Reuse / dienext event or recycleCold start = new environment (Init + first Invoke). Warm start = Freeze → Invoke. Provisioned concurrency pays to skip Init.Interview: I put SDK clients outside the handler. I do not claim 'Lambda is always cold' — measure p99 Init, do not recite blog ms. When does Init run relative to Invoke?
Lambda lifecycle
Cold start vs slow invoke Interviewers mix these on purpose. Init Duration is a new environment. A 28-second warehouse call is a warm invoke that is just slow. Cold startnew env: Init + first Invoke Slow invokewarm env, outbound / CPU / lockp99 jump after idle or deploy → inspect Init Duration, package size, VPC ENI. Every invoke slow → inspect the last outbound span and memory/CPU.Provisioned concurrency skips Init on the alias you pay for. It does not make a warehouse faster. Reserved concurrency does not warm anything.Interview: I read the REPORT line before I say 'cold start'. Saying cold start for T-01 is how you fail the troubleshooting loop. What evidence tells you the spike is Init Duration versus a dependency?
Cold start vs slow invoke
Timeout budget Every hop has a clock. If the inner clock is longer than the outer clock, you get overlapping work or a 504 with a committed write. API Gatewayintegration ceiling (~29s) Lambda timeoutmust be < integration Outbound HTTPtighter than Lambda SQS visibility> Lambda + bufferSync: Lambda timeout < API Gateway integration. Worker: visibility timeout > function timeout + buffer. Never sleep in the handler to 'backoff'.Interview: I name the formula before I pick a number. I look up the current integration maximum — I do not recite a memorized quota as if it cannot change.T-01 is invoke slowness (warehouse). T-10 is visibility too short. Do not call both 'cold start'. Which timeout must be larger — Lambda or SQS visibility — and why?
Timeout budget

Why this matters

Interviewers mix cold start and slow invoke on purpose. If you call a 28-second warehouse call a cold start, you fail the troubleshooting loop (T-01). If you treat every invoke as a fresh process, you will leak connections and mis-explain p99. If you treat the environment as a guaranteed singleton, you will share request state across customers.

The four states

Init

Top-level code runs when the environment starts: import the handler, create SDK clients, load configuration, fail if required secrets are missing. Init duration appears on the Lambda REPORT line. Huge dependency graphs, VPC ENI attachment, and tiny memory (which also scales CPU) make Init worse.

Put DynamoDB, SQS, and HTTP clients outside the handler.

Invoke

The handler should be deterministic given the event and its collaborators. Log a correlation id at start and a completion line at end so timeouts are obvious. Do not bootstrap a new HTTP session per call unless you have a specific isolation reason.

Freeze / reuse

Globals may survive. That is useful for clients and dangerous for “current user” caches. Cache secrets with a TTL and a rotation story. Never cache authorization without the principal in the key.

Die / recycle

Environments go away. Do not store the only copy of business state in memory.

Cold start versus invoke slowness

SignalLook here first
p99 jumps after idle or a deployInit Duration, package size, VPC ENI
Every invoke is slowLast outbound span, memory/CPU, lock, downstream
Errors with flat durationAuth, validation, IAM, KMS — not Init

Provisioned concurrency skips Init on the alias you pay for. Reserved concurrency does not keep environments warm — it only isolates and caps.

Timeout budget

  • API Gateway integration has a ceiling (confirm the current maximum; historically ~29s for REST/HTTP integrations).
  • Lambda timeout must sit under that ceiling on a sync path.
  • Outbound HTTP timeouts must sit under Lambda timeout.
  • For SQS workers, visibility timeout > function timeout + buffer. If work exceeds visibility, a second worker appears (T-10).

Never sleep in the handler to “backoff” a warehouse. You stall drain (T-31).

How to open (say it)

“Init constructs clients. Invoke handles one event. I will not call a warm, slow dependency a cold start — I will read Init Duration on the REPORT line.”

Real world — after a deploy

Checkout p99 goes from 180ms to 2.1s for ten minutes, then recovers. REPORT shows Init Duration ~1.8s on new environments. Package grew because someone bundled the SDK twice. You shrink the artifact, keep clients in Init, and only then discuss provisioned concurrency for the sale window.

Contrast: p99 is 28s every time. Trace ends in warehouse.charge. That is T-01. Move the charge off the request path.

If they ask

“Where is your DynamoDB client constructed?”

Module scope, during Init.

“What if Init throws?”

The environment never serves. Clients see 5xx until a good environment starts. Fail closed on missing secrets.

“Does async Lambda change this?”

Async retries can run the same event in different environments. Idempotency still applies.

Common mistakes

COMMON MISTAKE: “Lambda is always cold.” Measure; do not recite blog milliseconds.

COMMON MISTAKE: Caching tenantId in a global from the last request.

INTERVIEW TIP: Separate the two stories out loud: Init versus outbound. Interviewers listen for that split.

API Gateway15 min

API Gateway

API Gateway — deep dive

In one sentence: API Gateway is ingress, authn, throttling, and a contract. It is not your domain layer and not a workflow engine.

API Gateway + Lambda HTTP API vs REST API is a feature choice, not a brand preference. HTTP APIlower cost/latency, JWT, auto deploy REST APIAPI keys, WAF, private, validation, cacheChoose REST when you need API keys, AWS WAF association, private APIs, request validation, or caching. Choose HTTP when JWT + cost/latency win.Interview: I do not say 'HTTP is always better'. I name the required features, then pick. Verify current feature matrices at content refresh. When do you still choose REST API over HTTP API?
API Gateway + Lambda
Authorizer vs handler authz The edge answers 'who is this?'. The handler answers 'may they touch this item?'. Both are required. AuthorizerJWT / IAM / Lambda Contextsub, tenant, scopes Handler checkowner + tenant Dynamo conditionPK includes tenantA 403 with flat invocations is an edge problem (WAF, resource policy, authorizer). A 403 with rising invocations is your handler or condition.Interview: I never trust tenantId from the JSON body alone. List queries must Query that tenant's collection — never Scan the table. Who is allowed to call PutItem — the JWT or the function role?
Authorizer vs handler
Timeout budget Every hop has a clock. If the inner clock is longer than the outer clock, you get overlapping work or a 504 with a committed write. API Gatewayintegration ceiling (~29s) Lambda timeoutmust be < integration Outbound HTTPtighter than Lambda SQS visibility> Lambda + bufferSync: Lambda timeout < API Gateway integration. Worker: visibility timeout > function timeout + buffer. Never sleep in the handler to 'backoff'.Interview: I name the formula before I pick a number. I look up the current integration maximum — I do not recite a memorized quota as if it cannot change.T-01 is invoke slowness (warehouse). T-10 is visibility too short. Do not call both 'cold start'. Which timeout must be larger — Lambda or SQS visibility — and why?
Timeout budget

Why this matters

A surprising number of “Lambda is down” incidents are edge problems: authorizer 403, WAF, resource policy, or an illegal proxy response that becomes 502. Senior candidates prove whether the function invoked before they open Python.

HTTP API vs REST API

This is a feature choice. Confirm the current matrix in the account and region — the line moves.

You needLean
JWT / OIDC JSON API, lower latency/costHTTP API
API keys, request validation, edge cache, private API, WAF association you already standardized on RESTREST API

Do not pick REST “because enterprise” without a feature you can name. Do not pick HTTP API if you already depend on a REST-only control you have not replaced.

Authn vs authz

Authorizer vs handler authz The edge answers 'who is this?'. The handler answers 'may they touch this item?'. Both are required. AuthorizerJWT / IAM / Lambda Contextsub, tenant, scopes Handler checkowner + tenant Dynamo conditionPK includes tenantA 403 with flat invocations is an edge problem (WAF, resource policy, authorizer). A 403 with rising invocations is your handler or condition.Interview: I never trust tenantId from the JSON body alone. List queries must Query that tenant's collection — never Scan the table. Who is allowed to call PutItem — the JWT or the function role?
Authorizer vs handler
  • Authorizer: who is this? IAM, JWT, or Lambda authorizer. A 403 here means the function may never have run.
  • Handler: may they touch this order? Tenant and owner come from the token, not only the JSON body.
  • DynamoDB condition: the PK includes tenant. IAM allows PutItem on that table; it does not decide whose row.

Walk the isolation review inward: signature or JWT → authorizer → handler check → condition → least-privilege role.

Errors you must be able to split

Client seesInvocationsFirst hypothesis
403FlatWAF, resource policy, authorizer (T-04)
502RisingIllegal proxy response: dict body, missing statusCode, non-string header (T-05)
504 / timeoutRising, duration ≈ timeoutIntegration vs Lambda budget; or a slow dependency
429RisingStage/method throttle or Lambda reserved cap

Access logs should carry request id and status — not card numbers.

Throttling is not a queue

Stage and method throttles protect you from noisy clients. They are not a substitute for SQS in front of a fragile worker. Know how 429 looks to a mobile client and whether you send Retry-After.

Canaries

Put a canary alias on POST /orders so a bad helper fails a slice instead of 100%. When you debug, prove invoke count first.

How to open (say it)

“I will treat API Gateway as the contract and the trust boundary. I will prove whether Lambda ran before I debug the handler.”

Real world — partner webhook

A partner retries POST /webhooks/pay. You verify the signature at the edge or in the first lines of the handler, map to an internal tenant, then apply the same idempotency key they send. You do not put the partner on a fat IAM role that can Scan the table.

If they ask

“Why not Function URLs?”

Fine for an internal tool. Public checkout usually wants the authorizer, WAF, and throttle story you already operate on API Gateway.

“Where does tenancy live?”

Token → handler → item key. Never tenantId from an untrusted body alone.

Common mistakes

COMMON MISTAKE: Debugging Python on a 403 with zero invocations.

COMMON MISTAKE: Returning a Python dict as body and calling the 502 a platform outage.

INTERVIEW TIP: Say “illegal proxy response” out loud. It signals you have operated this edge.

You will

  • Explain why a bus is not a work queue
  • Report failed item IDs instead of throwing the batch

Messaging and events15 min

Messaging and events

Messaging and event-driven design — deep dive

In one sentence: EventBridge decides who cares. SQS decides how hard they work and how they fail. SNS is simple fan-out when you do not need a rich pattern language.

SQS vs SNS vs EventBridge Queue work. Topic-notify many. Bus-route facts. Mixing the three without a reason is an interview fail. SQScompeting consumers, retries, DLQ SNSfan-out a notification EventBridgepattern routing of factsNeed workers to chew a backlog? SQS. Need many systems to hear one announcement? SNS. Need content-based routing and many producers? EventBridge.Interview: 'we use EventBridge for everything' is not a design. Name the delivery, retry, and consumer-isolation requirement. How do you choose among SQS, SNS, and EventBridge in one sentence each?
SQS vs SNS vs EventBridge
Event choreography Each service reacts to facts it cares about. There is no central conductor — coupling moves into event contracts. OrdersOrderPlaced PaymentsPaymentTaken InventoryStockHeld NotifyEmailSentChoreography scales teams when contracts are stable. It fails when you need a single status, a timeout, or a compensation that spans services.Interview: I choreograph notifications. I orchestrate payment + reserve + capture when I must see the whole saga. When does choreography become harder than orchestration?
Event choreography
Orchestration vs choreography A state machine owns a multi-step business process. A bus fans facts to consumers who do not name each other. ChoreographyEventBridge facts, many subscribers OrchestrationStep Functions owns the pathUse Step Functions when you need waits, branches, different retries, or compensations. Do not wrap a single resize Lambda in a Standard workflow.A saga is local transactions + compensations — not 2PC across a warehouse API. Each step must name its undo.Interview: I draw the first async boundary first. Then I say whether one owner must see the whole path. What belongs in the state machine versus in a Lambda?
Orchestration vs choreography

Why this matters

If you cannot explain why a fact goes on a bus and work goes on a queue, you will fail senior screens. Module 2 is the async boundary of this sprint: trigger the work, process it, scale the hop that needs it, and recover when it fails.

Facts versus work

KindExamplePrimitiveNeeds
FactOrderCreatedEventBridge (or SNS if the pattern is trivial)Many subscribers, versioned envelope
Work“Call the warehouse”SQSBacklog, visibility, DLQ, reserved concurrency
Notification“Email the receipt”SNS → maybe SQSFan-out, not a drain-for-hours queue

Using one primitive for all three is the AR-06 / AR-07 failure.

Choreography

Producers do not name consumers. They publish a past-tense fact with a stable source and detail-type. Consumers filter. You do not delete unknown types in a god-queue because one worker does not understand them.

When one owner must see waits, branches, and compensations, you orchestrate (Step Functions). That is a different lesson — do not hide a saga inside “we use the bus.”

Backpressure

Reserved concurrency on the worker is how you protect the warehouse. Depth is capacity. Age of the oldest message is the customer SLO. After a sale spike, drain time is a first-class metric (T-31).

How to open (say it)

“I will draw the first async boundary before I name a runtime. Facts fan out. Work isolates behind a queue.”

Real world — order created

Create returns 201. OrderCreated hits EventBridge. Email, analytics, and fraud each have a rule. Fulfillment is not a Lambda target on the bus — it is SQS behind a rule so you can backlog, hide in-flight work, and redrive.

If they ask

“Why not Kafka?”

If the team already operates Kafka and needs replay/log semantics, say so. For this platform, SQS + EventBridge match the isolation and routing jobs without operating a cluster. I will not pretend Kafka is “more enterprise” as a slogan.

“Why not invoke Lambda directly from EventBridge?”

When the consumer needs a backlog, visibility, or a DLQ you already know how to operate — put SQS in the middle.

Common mistakes

COMMON MISTAKE: Calling SQS “the event bus.”

COMMON MISTAKE: One queue that every consumer filters in code.

INTERVIEW TIP: Reuse this sentence: EventBridge decides who cares. SQS decides how hard they work and how they fail.

SQS15 min

SQS

Amazon SQS — deep dive

In one sentence: SQS is a durable competing-consumer backlog. Learn visibility, batching, partial failure, and DLQ well enough to teach them.

SQS as a work queue A queue decouples producers from consumers. It is not an event bus and not a database. Producer SQS queueat-least-once ConsumerLambda / worker Side effectwrite / callStandard = high throughput, possible duplicates and reordering. FIFO = per-group order + exactly-once processing semantics with a dedup window.Interview: I put work on SQS when I need competing consumers and retries. I do not fan out notifications from a queue. Why is SQS a work queue and not an event bus?
SQS as a work queue
SQS visibility timeout After ReceiveMessage the item is hidden, not deleted. Delete only after the side effect succeeds. Visiblein queue Invisiblevisibility timeout Deleteside effect succeeded Reappeartimeout / nackTimeout shorter than processing → another consumer takes the same message. Timeout much longer than processing → poison messages stall.Interview: I set visibility > p99 processing, extend with ChangeMessageVisibility on long jobs, and I never delete-before-write. When does a message reappear after ReceiveMessage?
Visibility timeout
SQS Standard vs FIFO FIFO reduces overlap for a group. It does not replace application idempotency for two client clicks. Standardscale, possible dup + reorder FIFOper-group order + dedup windowChoose FIFO when one group (orderId) must not run overlapping workers — warehouse packing, not 'payments feel serious'.Both still need an idempotency key for user double-submit and at-least-once Lambda. messageId only dedups one receive, not two HTTP creates.Interview: I can name group id, dedup id, and the DynamoDB condition I still write. What does FIFO guarantee — and what must the handler still do?
Standard vs FIFO
SQS + Lambda batching Lambda polls the queue. Batch size, batching window, and function timeout are one contract. SQSmessages waiting Event source mappingbatch + window Lambda invokeRecords[] in one eventA batch is one invocation. If the function throws, the whole batch retries — unless you report partial batch failures.Interview: I size the batch so p99 processing fits inside timeout and visibility. I do not pick batch=10 because a blog said so. What retries if the handler throws on a batch?
SQS + Lambda batching
Partial batch failure Succeed the items you wrote. Return the item identifiers that must retry. Do not throw the whole batch. Batch of 5one Lambda invoke 3 succeededside effects committed 2 failedReportBatchItemFailuresWithout partial failure, SQS redelivers all five — including the three you already charged or emailed. That is how duplicates become incidents.Interview: I make each record idempotent AND I report failures. Either alone is incomplete. Why must you report failed item IDs instead of throwing?
Partial batch failure
DLQ and redrive A DLQ is an incident inbox, not a trash can. Redrive only after you fixed the consumer or the payload. Main queueretries + backoff maxReceiveCountpoison threshold DLQinspect → fix → redriveRedrive without a fix just burns the retry budget again. Capture the payload, the exception class, and the request id first.Interview: I alarm on DLQ depth, not only on Lambda errors. A silent DLQ is a production defect. What must you do before redriving a DLQ?
DLQ and redrive

Why this matters

SQS is the default isolation layer in this sprint. If fulfillment shares the HTTP function, you cannot scale or recover independently. If you throw after four successful records in a batch, you retry the four (T-11). If visibility is shorter than the function, two workers charge the warehouse (T-10, T-12).

Standard vs FIFO

  • Standard: high scale, possible duplicates and reordering. Always write idempotent handlers.
  • FIFO: per-group ordering and a deduplication window. Choose it when a group key (orderId) must not run overlapping workers — packing a single order — not because “payments feel serious.”

FIFO still needs application idempotency. Two HTTP creates with two keys are two messages. messageId only dedups a particular receive.

Visibility timeout

The message is hidden while in flight. If real work exceeds visibility, it reappears and a second worker starts.

Formula: visibility timeout > function timeout + buffer.

Do not sleep in the handler to backoff a warehouse (T-31). That stalls drain and still risks overlap.

Lambda event source mapping

  • Batch size is a timeout and duplicate risk, not a vanity TPS number.
  • Catch per record.
  • Enable ReportBatchItemFailures and return the failed item identifiers (C-09).
  • Throwing the whole batch retries successes too (T-11).

DLQ

Modest maxReceiveCount. A DLQ is an operator inbox, not a trash can. Classify before redrive (C-13): poison JSON vs downstream 503 vs bad IAM. Age can be high while depth looks fine — that is poison (T-08). Depth without errors is capacity (T-07). Poison loops without a DLQ are how bills double (T-13, T-29).

What to write on the whiteboard

Queue name, producer, consumer, reserved concurrency, batch size, visibility timeout, function timeout, maxReceiveCount, DLQ name, and the idempotency key inside the handler. If any of those is missing, the design is not interview-ready.

How to open (say it)

“Fulfillment is a queue. Visibility is longer than the function. I report failed item ids. Poison goes to a DLQ I classify before redrive.”

Real world — sale spike

Depth climbs, age stays healthy, Errors stay low: add capacity or raise reserved concurrency on the worker — do not purge. Age climbs, depth is small: find the poison message, do not scale blindly.

If they ask

“Why not EventBridge for fulfillment?”

The bus routes the fact. The worker needs a backlog and redrive. I put SQS behind the rule.

“Exactly-once?”

At-least-once delivery. Exactly-once effect via the DynamoDB condition on orderId + attempt.

Common mistakes

COMMON MISTAKE: Throwing after a partial batch.

COMMON MISTAKE: Visibility 30s, function timeout 60s.

INTERVIEW TIP: Say “age is the customer SLO, depth is the capacity SLO.”

EventBridge10 min

EventBridge

Amazon EventBridge — deep dive

In one sentence: EventBridge is a router for facts — buses, rules, patterns, targets. It is not a competing-consumer queue you drain for hours.

EventBridge routing A bus routes facts by pattern. Rules select. Targets receive. The bus is not a durable work queue. Producer Event busfacts Rulepattern match TargetsSQS / Lambda / SFnPut an SQS target when the consumer needs competing workers and a DLQ. Invoking Lambda directly from a rule still needs retry design.Interview: I route OrderPlaced to inventory and email with two rules. I do not dump raw events into one Lambda switch. What does a rule match, and why is the bus not a work queue?
EventBridge routing
SNS fan-out A topic copies a notification to many subscribers. Each subscriber still owns its own retry story. SNS topicnotification SQS orderswork queue SQS emailanother consumer HTTPS / Lambdaside pathFan-out is for 'many independent reactions to one fact'. It is not a competing-consumer work queue.Interview: I subscribe queues, not raw Lambdas, when I need retries and DLQ. SNS retry to HTTP is not SQS visibility. When is SNS the right fan-out and when do you still put SQS behind it?
SNS fan-out
Event choreography Each service reacts to facts it cares about. There is no central conductor — coupling moves into event contracts. OrdersOrderPlaced PaymentsPaymentTaken InventoryStockHeld NotifyEmailSentChoreography scales teams when contracts are stable. It fails when you need a single status, a timeout, or a compensation that spans services.Interview: I choreograph notifications. I orchestrate payment + reserve + capture when I must see the whole saga. When does choreography become harder than orchestration?
Event choreography

Why this matters

When fulfillment never runs but create returns 201, candidates open the worker first. Senior engineers compare a stored event to the rule pattern. TriggeredRules at zero is T-14. Invocations on the wrong function is T-15. Errors after a producer rename is T-16.

The envelope

At minimum: id, source, detail-type, time, detail, version. Validate at the consumer (C-10). Route on stable fields. Content filters on volatile nested fields (detail.amount renamed to totalAmount) break silently.

OrderCreated is a past-tense fact. “Call the warehouse” is work — that target should usually be SQS, not a Lambda you cannot backlog.

Rules and targets

A catch-all Order* rule pointed at billing is how the wrong function runs (T-15). List every matching rule, not only the one you remember. FailedInvocations is a different failure from a pattern miss.

Put SQS behind a rule whenever the consumer needs backlog, visibility, isolation, or redrive. The bus fans out; the queue works.

SNS is the simpler cousin when you only need fan-out and do not need EventBridge’s pattern language, archive, or cross-account bus features.

Versioning

Major routing on version or detail-type (C-11). Dual-publish on breaking changes. Consumer fixtures in producer CI (T-16). Unknown versions must not retry forever — they poison a queue if you wired one badly.

Debugging a silent consumer (SIGNAL order)

  1. S: Only fulfillment, since 14:10, all tenants?
  2. I: PutEvents success vs TriggeredRules.
  3. G: Sample event source / detail-type vs the rule.
  4. N: Routing, not the worker, if rules are zero.
  5. A: Dual-match sources, replay from the outbox — do not purge.
  6. L: Contract test on source.

How to open (say it)

“The bus routes facts. I will match source and detail-type before I debug the worker. Heavy consumers sit behind SQS.”

Real world — rename

Producer ships source: orders.service while the rule still matches app.orders. Create looks healthy. Fulfillment is silent. That is T-14. The fix is not a new Lambda.

If they ask

“Archive and replay?”

Useful for ops. Replay is not a substitute for an outbox on the write path. Consumers must stay idempotent.

“Schema registry?”

Fine if the org has one. I still validate at the consumer and version the envelope.

Common mistakes

COMMON MISTAKE: Treating EventBridge as a work queue you “drain.”

COMMON MISTAKE: Filtering on a nested field that product will rename next sprint.

INTERVIEW TIP: Say “TriggeredRules at zero is routing.” It is a senior tell.

Step Functions and sagas12 min

Step Functions and sagas

Step Functions and sagas — deep dive

In one sentence: Orchestrate when one owner must see waits, branches, different retries, or compensations. Do not wrap a single Lambda in a Standard workflow for “visibility.”

Step Functions orchestration A state machine owns the sequence, retries, and timeouts. Lambda stays a unit of work, not a workflow engine. Start TaskLambda / HTTP Choicebranch Wait / retry / catchthen next taskStandard workflows are durable and auditable. Express is cheaper for high-volume short flows. Do not hide a 40-step business process in nested Lambdas.Interview: I put the saga in Step Functions when I need visibility and compensation. I do not use it as a cron wrapper for one function. What belongs in the state machine versus in a Lambda?
Step Functions orchestration
Saga compensation A distributed write is a sequence of local transactions plus explicit undo. There is no two-phase commit across AWS accounts. Reserve stock Authorize pay#f8e7a8 Confirm#dcfce7 Compensaterelease / voidEach step is idempotent. Compensation is a first-class state, not a hope that the operator will click console buttons.Interview: I name the undo for reserve and authorize. 'The transaction will roll back' is a wrong answer on DynamoDB + SQS. What must exist for each local transaction in a saga?
Saga compensation
Orchestration vs choreography A state machine owns a multi-step business process. A bus fans facts to consumers who do not name each other. ChoreographyEventBridge facts, many subscribers OrchestrationStep Functions owns the pathUse Step Functions when you need waits, branches, different retries, or compensations. Do not wrap a single resize Lambda in a Standard workflow.A saga is local transactions + compensations — not 2PC across a warehouse API. Each step must name its undo.Interview: I draw the first async boundary first. Then I say whether one owner must see the whole path. What belongs in the state machine versus in a Lambda?
Orchestration vs choreography

Why this matters

After you draw EventBridge, interviewers ask “why not a state machine?” The senior answer is about ownership of the path, not about collecting AWS logos. A saga is a sequence of local transactions with named undos — not two-phase commit across a warehouse API.

When to orchestrate

Use Step Functions when you need:

  • Waits (human approval, carrier pickup)
  • Branches (fraud hold vs ship)
  • Different retry policies per step
  • Compensations if step 3 fails after step 2 committed
  • A single execution id ops can open

Do not use a Standard workflow around one resize Lambda. That is cost and complexity without a multi-step business process.

What belongs in the machine vs in Lambda

In the state machineIn a Lambda
Order of steps, wait, choice, parallelDomain validation, one I/O hop
Per-state retry / catchIdempotent call to one collaborator
Compensation routingThe compensate action itself

Keep payloads small. Do not park megabytes of PDF in state.

Saga, honestly

Each local step must name its compensation: capture → void/refund; reserve inventory → release; create shipment → cancel label. Compensations are also at-least-once — they need keys too. If you cannot name the undo, you do not have a saga; you have hope.

Choreography still publishes facts (PaymentCaptured). The orchestrator is the one component allowed to decide “we are in AWAITING_WAREHOUSE.”

Standard vs Express (conceptually)

Standard executions are long-lived and inspectable. Express is for high-volume short flows. Confirm current limits and pricing when you implement — do not recite a memorized duration as eternal law. Choose from the duration and inspectability job, not from a blog title.

How to open (say it)

“I choreograph facts. I orchestrate only when one owner must run a multi-step process with waits or undos.”

Real world — capture then ship

Step 1 captures payment (idempotent paymentId). Step 2 reserves inventory. Step 3 creates a shipment. If step 3 fails, compensate 2 then 1. The HTTP API only started the execution and returned 202 + execution id.

If they ask

“Why not the worker Lambda looping?”

Loops hide state in logs. A machine gives retries, timeouts, and a console execution you can defend at 2am.

“Is the outbox gone?”

No. Starting the execution still needs a durable write. Often: transaction (order + outbox) then the relay starts the machine, or the API starts the machine after the transaction.

Common mistakes

COMMON MISTAKE: “We use Step Functions” as the first sentence of a design.

COMMON MISTAKE: A saga with no compensation boxes.

INTERVIEW TIP: Draw the undo under each step. That is the staff-level tell.

You will

  • Design PK/SK from the questions you must answer
  • Name when a second table is simpler than single-table

DynamoDB modeling25 min

DynamoDB modeling

DynamoDB access-pattern modeling — deep dive

In one sentence: If you start from tables named like SQL, you will Scan. If you start from access patterns, you will Query. This is the heaviest rubric dimension in the sprint.

DynamoDB access-pattern worksheet Keys come from questions you must answer. If a pattern has no key, you do not have a design. Create orderPK CUST# / SK ORDER# Get ordersame PK + SK List by customerPK + SK begins_with Ops: failed jobssparse GSIPK is high cardinality on the write path. SK gives ranges. Status is an attribute — never PK=STATUS#OPEN (hot partition).A GSI is another table: eventual, own throttles, extra writes. Never read-your-writes from a GSI after PutItem.Interview: I refuse Scan as a product feature. Two tables are fine when they match two domains. Single-table is optional, not a religion. What does a Query need that a Scan does not?
Access-pattern worksheet
DynamoDB PK / SK The table is an access-pattern machine. PK groups the item collection. SK orders and ranges it. PK = ORDER#1001item collection SK = METAorder header SK = ITEM#skuline itemsQuery is cheap when you know PK (and optionally SK begins_with / between). Scan is a last resort and an interview red flag on a hot table.Interview: I design PK/SK from the questions I must answer, not from an ERD. I say the collection and the range in one sentence. What does a Query need that a Scan does not?
DynamoDB PK / SK
Global secondary index A GSI is another table you pay to keep consistent enough for a second access pattern. Base tablePK orderId / SK item GSIPK customerId / SK createdAtYou cannot Query by an attribute that is not in a key. A GSI (or a write-time denormalized item) is how you add 'orders by customer'.Interview: GSIs have their own RCU/WCU and can be eventually consistent. I do not add an index 'just in case' — each GSI is a product decision. Why is a GSI not a free extra WHERE clause?
Global secondary index
Single-table concept One table can hold several entity types if they share access patterns. It is not a religion. ORDER# + META/ITEMorder + lines CUST# + PROFILEcustomer CUST# + ORDER#customer→ordersSingle-table pays off when one Query must return a graph. Multiple tables are fine when teams and access patterns do not overlap.Interview: I can draw either. I refuse 'always single-table' as a slogan. I show the access patterns first. When is a second table simpler than a single-table design?
Single-table concept
DynamoDB Streams The stream is the change log after a committed write. Use it to fan out, not to 'fix' the write path. PutItemcommitted Stream recordNEW_AND_OLD Lambda / pipesearch, notify, outboxStream processing is at-least-once. The consumer must be idempotent. Do not write a second 'source of truth' without a key.Interview: I use streams for projection and fan-out. I do not use them as a distributed transaction. What delivery guarantee does a stream consumer have?
DynamoDB Streams

Why this matters

Interviewers watch whether you write the questions first. A complete Module 3 answer names two or three access patterns, a PK/SK, one optional GSI, a hot-key risk, a consistency choice, and whether a transaction is justified. You do not need a twelve-GSI masterpiece. You need to refuse PK=STATUS#OPEN and refuse Scan as a product feature.

Worksheet first

Write Create, Get, List, and any ops query. Assign PK/SK. Mark consistency. Mark expected QPS. If a pattern has no key, you do not have a design — you have a hope.

Order platform starter:

PatternPKSKNotes
Create / get orderCUST#<tenant+customer>ORDER#<id>Condition on create
List customer orderssame PKbegins_with ORDER#Item collection
Ops: failed fulfillmentGSI GSI1PK=FAILEDtimeSparse, not the live path

Keys

  • PK is high cardinality on the write path. Celebrity tenants still happen — shard or isolate them (T-18).
  • SK gives ranges and collections.
  • Status is an attribute. PK=STATUS#OPEN is the classic fail (AR-09): every open order hits one partition.

GSI and consistency

A GSI is another table: eventual, own throttles, extra writes. Never read-your-writes from a GSI after PutItem (T-21). Sparse GSIs are for failed jobs and ops, not “list all open orders in the company.”

If the product needs immediately consistent list-after-write, Query the base table collection — not the GSI.

Conditions, transactions, TTL, streams

  • Conditional writes are unique constraints and optimistic versions (C-05, C-18, T-20).
  • Transactions are for small invariants (order + outbox + idempotency), not four copied relational tables (AR-08).
  • TTL is best-effort epoch seconds (C-19) — not a legal-hold delete.
  • Streams are ordered per key and at-least-once (C-17). Use them as an outbox relay trigger, not as “exactly-once CDC.”

Single-table is optional

Use one table when item collections are accessed together and the team can keep a catalog of prefixes. Two tables are simpler when they match two domains (orders vs sessions). Single-table religion without access patterns is a fail.

How to open (say it)

“I will list the questions the product must answer, then assign keys. I will not start from an ERD.”

Real world — DDB-01

Create must not double-insert on retry. attribute_not_exists on the order SK, or an idempotency item in the same transaction. List is a Query, not a Scan filtered in Python.

If they ask

“Why not RDS?”

If the access patterns are relational joins and ad-hoc reporting, say so. For this checkout path, a handful of known queries plus conditions fit DynamoDB. I will not pretend DynamoDB is always cheaper or always simpler.

“Strong consistency?”

On the item you just wrote, Get/Query the base table. Do not promise GSI strong consistency.

Common mistakes

COMMON MISTAKE: PK=STATUS#OPEN.

COMMON MISTAKE: Scan as a product feature with “we will add a GSI later.”

INTERVIEW TIP: Write the worksheet on the board before the key schema. Interviewers grade the order of operations.

You will

  • Store the first successful result for a replayed key
  • Keep a request id across API Gateway, Lambda, and SQS

Reliability and security12 min

Reliability and security

Reliability, security, and observability — deep dive

In one sentence: Retries without authorization just repeat a breach. A deny you cannot see in logs is a deny you cannot prove. Name the failure at each hop, not the service list.

Retry taxonomy Not every error deserves a retry. Validation fails fast. Throttle retries with jitter. Unknown goes to a DLQ. Fail fast400 / 403 / 409 Retry + jitterthrottle / 5xx / timeout DLQpoison / unknown Do not stackSDK + SQS + SFnOverlapping SDK, Lambda async, SQS, and Step Functions retries cause retry storms (T-26). Cap each layer and name the owner.AR-15 is infinite retry. Sleeping in the handler to backoff stalls drain (T-31). Visibility is not a backoff tool.Interview: I classify the error before I add another retry. I can say who retries: client, Lambda, queue, or workflow. Which failures must not retry, and where does unknown work go?
Retry taxonomy
Idempotency At-least-once delivery means every write needs a natural or generated key the store can reject as a duplicate. RequestIdempotency-Key Conditional writeattribute_not_exists(pk) Replaysame result / 200SQS, Lambda async, API retries, and client double-submit all replay. 'The function is idempotent because it is a Lambda' is false.Interview: I name the key (orderId, eventId, Idempotency-Key) and the condition. I store the first response so retries do not charge twice. Where do you store the first successful result for a replayed key?
Idempotency
Dual-write vs transactional outbox A database commit and a bus publish can each fail alone. That is not an outbox. An outbox is one transaction plus a relay. Dual-write (fail)PutItem then PutEvents Outbox (recover)TransactWrite + relayWrite the order item and an unpublished outbox item together. Return 201. A relay or stream publisher emits, then marks published.If publish succeeds and the mark fails, republish with a stable event id. Consumers stay idempotent. Swallowing PutEvents is T-32.Interview: exactly-once delivery is not a platform promise. Exactly-once business effect is your job. Why is a dual write from the handler not an outbox?
Dual-write vs outbox
Serverless IAM boundaries The function role is the blast radius. Resource policies and identity policies are not interchangeable slogans. Caller identityIAM / JWT / API key Function roleleast privilege to AWS Resource policywho may invoke / readLambda never uses the caller's AWS credentials. API Gateway authorizes the caller; the role authorizes DynamoDB and SQS.Interview: I scope dynamodb:UpdateItem to one table/index and one PK prefix when I can. * on dynamodb:* is an incident waiting for a ticket. Who is allowed to call PutItem — the JWT or the function role?
IAM boundaries
Correlation id path Mint or accept one id at the edge. Pass it through every hop. Four uuids is how you cannot operate the system. API GWrequest id Lambdax-correlation-id Dynamo itemsame id Event / SQSattribute Worker logsjoin keyAlso put it on the outbox item and Step Functions state. Dashboards without a join key are decoration.SIGNAL uses this id in G: gather the last span and the item key. Do not DEBUG the full event in production (T-28).Interview: I can jump from a 5xx to the trace, the Dynamo key, and the SQS message id. Which identifiers do you keep across API Gateway, Lambda, and SQS?
Correlation id path
Serverless cost flow You pay for requests, duration, memory (GB-s), chatter (API/SQS/GSI writes), and idle provisioned capacity. RequestsAPIGW + Lambda GB-secondsmemory × time ChatterSQS / GSI / NAT Provisionedwarm tax Storage Dynamo + logsRight-size memory for CPU. Batch to cut invokes. Cache reads. Kill chatty logs. Destroy lab stacks. Never paste list prices into slides.Interview: I optimize the expensive hop I measured. I do not quote a blog's 'Lambda is cheaper than EC2' as a fact. Which two levers usually dominate a chatty Lambda + DynamoDB bill?
Cost flow

Why this matters

Module 4 binds the failure story. Walk one request from API Gateway to DynamoDB to outbox to EventBridge to SQS to the warehouse. At each hop name the failure and the control.

Retry taxonomy

ClassExamplesAction
Fail fast400, 403, 409, poison schemaDo not retry
Retry + jitterthrottle, transient 5xx, timeoutCap + jitter
DLQunknown / poison after N receivesOperator inbox
Do not stackSDK + Lambda async + SQS + Step FunctionsName one owner (T-26)

AR-15 is infinite retry. Sleeping in the handler to backoff stalls drain (T-31).

The story that wins mocks

  1. Timeout after write → idempotency item (T-30).
  2. Swallowed PutEvents → outbox (T-32).
  3. Visibility too short → formula (T-10).
  4. Poison JSON → DLQ + classify (T-08, T-13).
  5. KMS deny → key policy, not “IAM is fine” (T-25).

Then name the join key (correlation id) and one alarm: age, DLQ depth, throttles, unpublished outbox age.

Security in one pass

Per-function roles, KMS as a second plane, secrets not in env dumps, VPC not a default. Authorization is authorizer + handler + condition. Read the Security lesson next.

Observe and cost

Correlation ids (AR-11). Age and DLQ alarms. DEBUG of full events doubles the bill (T-28, T-29). Read Observability and Cost.

How to open (say it)

“I will walk failures, not logos. At each hop I name the retry class and the control.”

Common mistakes

COMMON MISTAKE: Adding retries until the graph is unreadable.

COMMON MISTAKE: “We are secure because we use IAM.”

INTERVIEW TIP: Swap the vocabulary: failures first, services second.

Idempotency8 min

Idempotency

Idempotency — deep dive

In one sentence: At-least-once delivery plus timeouts after side effects means you will run twice. Idempotency is how the business stays once.

Idempotency At-least-once delivery means every write needs a natural or generated key the store can reject as a duplicate. RequestIdempotency-Key Conditional writeattribute_not_exists(pk) Replaysame result / 200SQS, Lambda async, API retries, and client double-submit all replay. 'The function is idempotent because it is a Lambda' is false.Interview: I name the key (orderId, eventId, Idempotency-Key) and the condition. I store the first response so retries do not charge twice. Where do you store the first successful result for a replayed key?
Idempotency
Lambda handler shape The handler is a contract pipeline. Clients live outside it. Timeouts on outbound HTTP are tighter than the function timeout. 1. Parseevent + headers 2. Validateschema / 400 3. Authorizetenant + owner 4. Write oncecondition / key 5. Proxy bodystring + statusSDK clients and config load in Init (module scope). The handler must stay deterministic for a given event + collaborators.Interview: I can point to where a 400, 403, 409, and 201 are decided. I never hide a 40-second vendor call in step 4.502 at API Gateway usually means step 5 returned a dict body or a missing statusCode — prove invoke count before you debug Python. Where do you construct the DynamoDB client — and why?
Handler shape
Retry taxonomy Not every error deserves a retry. Validation fails fast. Throttle retries with jitter. Unknown goes to a DLQ. Fail fast400 / 403 / 409 Retry + jitterthrottle / 5xx / timeout DLQpoison / unknown Do not stackSDK + SQS + SFnOverlapping SDK, Lambda async, SQS, and Step Functions retries cause retry storms (T-26). Cap each layer and name the owner.AR-15 is infinite retry. Sleeping in the handler to backoff stalls drain (T-31). Visibility is not a backoff tool.Interview: I classify the error before I add another retry. I can say who retries: client, Lambda, queue, or workflow. Which failures must not retry, and where does unknown work go?
Retry taxonomy

Why this matters

Exactly-once delivery is not a platform guarantee. Exactly-once business effect is your job. AR-03 is a new UUID on every payment-service call. T-30 is the API dying after PutItem — the client retries and, without a key, you mint a second order.

Choose a key

SituationKey
HTTP createClient Idempotency-Key scoped by tenant + route
Payment capturepaymentId / charge id toward the PSP
S3 objectbucket + key + version
SQS receiveNot messageId alone for user double-click

messageId only dedups a particular receive. Two mobile taps are two messages or two HTTP calls. FIFO does not save you from that.

Scope keys by tenant and route so cart A cannot collide with cart B. Do not use a global constant as the partition key.

Store states

NEW → IN_PROGRESS → COMPLETED with a body hash.

  1. Conditional begin: only one request becomes IN_PROGRESS.
  2. Do the side effect.
  3. Store the serialized response and mark COMPLETED with TTL covering the retry window.
  4. Replay returns the stored response.
  5. Same key, different hash → 409 conflict, not a silent overwrite.

If the first request is still IN_PROGRESS, the second gets a conflict or a short wait — not a second charge.

In production the store is DynamoDB with TTL, not a process dict (DDB-07). The lab’s in-memory drill (C-04) teaches the state machine only.

Timeouts after write

If the API dies after PutItem, the client retries. With a key you return the first order. Teach this story until it is boring — it is the Module 4 mock staple.

How to open (say it)

“I will persist the first successful result for a replayed key. FIFO and message ids are not enough for two client clicks.”

Real world — radio drop

Mobile sends Idempotency-Key: k1 with the same cart hash twice. First call writes the order and times out on the response. Second call hits COMPLETED and returns the same orderId and 201. The warehouse sees one fulfillment message (or two messages and one conditioned write).

If they ask

“What if IN_PROGRESS lasts forever?”

TTL plus a recovery path: a watcher treats stale IN_PROGRESS as failed and allows a retry, or you inspect the PSP with the same paymentId.

“Is a cache enough?”

A process cache dies with the environment. The store must survive the retry window.

Common mistakes

COMMON MISTAKE: Generating the idempotency key on the server for every attempt.

COMMON MISTAKE: Treating FIFO as application idempotency.

INTERVIEW TIP: Name the key, the store, the hash, and the timeout-after-write story in one breath.

Transactional outbox8 min

Transactional outbox

Transactional outbox — deep dive

In one sentence: A database commit and a bus publish can each fail independently. That dual-write is not an outbox. An outbox is one transaction plus a relay.

Dual-write vs transactional outbox A database commit and a bus publish can each fail alone. That is not an outbox. An outbox is one transaction plus a relay. Dual-write (fail)PutItem then PutEvents Outbox (recover)TransactWrite + relayWrite the order item and an unpublished outbox item together. Return 201. A relay or stream publisher emits, then marks published.If publish succeeds and the mark fails, republish with a stable event id. Consumers stay idempotent. Swallowing PutEvents is T-32.Interview: exactly-once delivery is not a platform promise. Exactly-once business effect is your job. Why is a dual write from the handler not an outbox?
Dual-write vs outbox
Transactional outbox Write the business row and the outbound event in the same transaction. Publish from the outbox, not from the request thread. App writeorder + outbox row Outbox poll / streampublisher Bus / queuedownstreamEmit-after-commit in the handler loses events on a crash. Emit-before-commit publishes ghosts. The outbox makes the write and the intent atomic.Interview: DynamoDB TransactWriteItems (item + outbox) or a stream of the committed item. I do not dual-write in application code. Why is a dual write from the handler not an outbox?
Transactional outbox
DynamoDB Streams The stream is the change log after a committed write. Use it to fan out, not to 'fix' the write path. PutItemcommitted Stream recordNEW_AND_OLD Lambda / pipesearch, notify, outboxStream processing is at-least-once. The consumer must be idempotent. Do not write a second 'source of truth' without a key.Interview: I use streams for projection and fan-out. I do not use them as a distributed transaction. What delivery guarantee does a stream consumer have?
DynamoDB Streams

Why this matters

AR-13 and T-32 are the exam. Candidates say “we put the event on EventBridge after DynamoDB” and believe they are consistent. Then PutEvents is swallowed, or the write rolls back after a publish, and fulfillment disagrees with the order table.

An outbox means you write the business row and an unpublished event row in the same transaction. A later relay publishes the event. That is how you avoid the dual-write hole.

The pattern

In one DynamoDB transaction:

  1. Write the business item (ORDER#…).
  2. Write an outbox item (published=false) with a stable event id and the correlation id.
  3. Often write the idempotency item in the same transaction.

Return success to the client. A relay — polling or a DynamoDB Streams Lambda — calls EventBridge, then marks published under a condition.

Failure modes

What happenedRecovery
Publish failsItem stays unpublished; relay retries. Recoverable.
Publish succeeds, mark failsRepublish with the same event id. Consumers stay idempotent (T-27).
Swallow PutEventsLost fact. T-32. Not recoverable without the outbox row.
Hot PK=OUTBOXThrottle. Shard by time and tenant.

Consumers must still be idempotent. The outbox removes the dual-write hole; it does not create exactly-once delivery.

Streams versus a polling relay

A Lambda on Streams can treat INSERT of unpublished items as the trigger. That removes a cron. You still mark published (or filter by an attribute). Iterator age becomes an SLO. A polling relay is easier to pause. Either beats dual-write.

When you might skip it

Low-stakes metrics you accept to lose. Never skip for orders, payments, or audit you promised was complete.

How to open (say it)

“I will commit the order and an unpublished outbox item together, then publish. Exactly-once delivery is not the promise — exactly-once effect is.”

Real world — T-32

Create returns 201. The handler logs “published” after a failed PutEvents it swallowed. Fulfillment never starts. SIGNAL: orders exist, TriggeredRules zero, no event on the bus. Mitigation: stop swallowing, backfill from unpublished outbox rows, add an alarm on unpublished age.

If they ask

“Why not two-phase commit with the warehouse?”

You do not control their database. A saga with compensations is the honest model (see Step Functions).

“Can EventBridge be the source of truth?”

Not for the customer-facing order id you already returned.

Common mistakes

COMMON MISTAKE: PutItem then PutEvents and calling it an outbox.

COMMON MISTAKE: Random event ids so retries create duplicate facts.

INTERVIEW TIP: Draw two items in one transaction box, then a relay box. Interviewers look for that split.

Security and IAM8 min

Security and IAM

Serverless security — deep dive

In one sentence: Serverless removes patching nights. It does not remove authorization, tenancy, or key policy.

Serverless IAM boundaries The function role is the blast radius. Resource policies and identity policies are not interchangeable slogans. Caller identityIAM / JWT / API key Function roleleast privilege to AWS Resource policywho may invoke / readLambda never uses the caller's AWS credentials. API Gateway authorizes the caller; the role authorizes DynamoDB and SQS.Interview: I scope dynamodb:UpdateItem to one table/index and one PK prefix when I can. * on dynamodb:* is an incident waiting for a ticket. Who is allowed to call PutItem — the JWT or the function role?
IAM boundaries
Authorizer vs handler authz The edge answers 'who is this?'. The handler answers 'may they touch this item?'. Both are required. AuthorizerJWT / IAM / Lambda Contextsub, tenant, scopes Handler checkowner + tenant Dynamo conditionPK includes tenantA 403 with flat invocations is an edge problem (WAF, resource policy, authorizer). A 403 with rising invocations is your handler or condition.Interview: I never trust tenantId from the JSON body alone. List queries must Query that tenant's collection — never Scan the table. Who is allowed to call PutItem — the JWT or the function role?
Authorizer vs handler
VPC Lambda A VPC attachment is for private resources. It is not a security upgrade for a public HTTPS API. Non-VPC LambdaAWS APIs via public endpoints VPC ENI pathprivate subnet + NAT/endpoints Need VPC whenRDS / ElastiCache / private APIHyperplane ENIs reduced classic cold-start pain, but you still own subnet IPs, NAT cost, and interface endpoints.Interview: I keep Lambda out of VPC unless it must reach a private resource. I do not 'put it in VPC for security' as a reflex. When do you attach Lambda to a VPC — and when do you refuse?
VPC Lambda

Why this matters

AR-04 is the wildcard role. T-24 is a secret resource policy deny that looks like “Lambda cannot start.” T-25 is KMS denying a function whose IAM role looks fine. T-23 is a VPC function that cannot reach the PSP because there is no NAT or endpoint — it looks like a vendor outage.

Isolation review you can present

Start from the public webhook and walk inward:

  1. Signature or JWT at the edge.
  2. Authorizer: who is this?
  3. Handler: tenant and owner from the token.
  4. DynamoDB condition that includes tenant id.
  5. IAM that cannot Scan the table and names resource ARNs.
  6. KMS key policy (second plane).
  7. Secret ARN + cache (C-22), no long-lived secrets in images.
  8. No VPC unless a private dependency exists. AWS APIs should use endpoints, not NAT (AR-10).

Then walk a support break-glass path that is a different role with audit. If you cannot explain why the webhook role is smaller than the admin replayer, you are not done.

Authn vs authz

The JWT is not allowed to call PutItem. The function role is. The JWT tells the handler which PK to use. List queries Query that tenant’s collection — never Scan other tenants (DDB-06).

Network

Attach Lambda to a VPC only to reach private resources (RDS, Redis, an internal HTTP API). Missing NAT looks like a PSP outage (T-23). Public webhooks need signatures, not hope. Do not default every function into a VPC “for security.”

How to open (say it)

“I will walk identity inward: edge, handler, item condition, role, key policy. Wildcard is not a design.”

Real world — shared layer

After an IAM tightening, 5xx waves because a shared layer cannot GetSecretValue or Decrypt. Invocations rise; duration is short. That is T-24/T-25. Stay on the policy, not the warehouse.

If they ask

“Encryption at rest?”

DynamoDB and SQS have service-side encryption. Use a CMK when the threat model needs isolation — then operate the key policy.

“WAF?”

Yes for public HTTP. It does not replace handler tenancy.

Common mistakes

COMMON MISTAKE: Action: * / Resource: * on a webhook role.

COMMON MISTAKE: Trusting tenantId in the JSON body.

INTERVIEW TIP: Say “KMS is a second plane.” Staff interviews want that sentence.

Observability8 min

Observability

Serverless observability — deep dive

In one sentence: Async systems fail in a different hop than they were triggered. Without a join key you will DEBUG-everywhere and still not know.

Observability and tracing A request id must survive the hop from API Gateway to Lambda to DynamoDB to the queue. requestId xray / OTel#f8e7a8 log group metrics / SLI alarm + runbook#dcfce7SIGNAL: Symptom, Impact, Glimpse (recent change), Next hop, Analyze traces, Last control. Do not start with 'restart the function'.Interview: I can jump from a 5xx to the trace, the log line with the item key, and the SQS message id. Dashboards without ids are decoration. Which identifiers do you keep across API Gateway, Lambda, and SQS?
Observability and tracing
Correlation id path Mint or accept one id at the edge. Pass it through every hop. Four uuids is how you cannot operate the system. API GWrequest id Lambdax-correlation-id Dynamo itemsame id Event / SQSattribute Worker logsjoin keyAlso put it on the outbox item and Step Functions state. Dashboards without a join key are decoration.SIGNAL uses this id in G: gather the last span and the item key. Do not DEBUG the full event in production (T-28).Interview: I can jump from a 5xx to the trace, the Dynamo key, and the SQS message id. Which identifiers do you keep across API Gateway, Lambda, and SQS?
Correlation id path
SIGNAL incident framework Async systems fail in a different hop than they were triggered. Guessing 'Lambda bug' is how you miss a rule mismatch. SScope impact IInspect metrics GGather traces NNarrow domain AApply safe fix LLearn / preventAge without depth = poison. Depth without errors = capacity. TriggeredRules at zero = routing, not the worker.Mitigations that are rarely safe: purge a production queue, raise retries to infinity, leave DEBUG of full events on.Interview: I pick one primary domain before I change three knobs. L is a test + alarm, not 'be more careful'. What do you inspect before you open the worker logs?
SIGNAL framework

Why this matters

AR-11 is four uuids. T-28 is DEBUG of full events (IncomingBytes is a budget). If you only watch Lambda Errors you will miss T-04 (edge 403), T-14 (no rule match), and T-28 (log bill).

Correlation

Mint or accept x-correlation-id at the edge. Pass it through:

  • API Gateway request id / access logs
  • Lambda logs and traces
  • DynamoDB items and outbox rows
  • EventBridge detail
  • SQS message attributes
  • Step Functions state

SIGNAL uses this id in G: last span, REPORT line, exact table name, exact event source.

Logs, metrics, traces

  • Logs: JSON, allowlisted fields, no authorization headers or card numbers.
  • Metrics that page: age, DLQ depth, throttles, 5xx, iterator age, KMS denies, unpublished outbox age, TriggeredRules vs PutEvents.
  • Traces: show the last span before a timeout (T-01).

Sample debug for one tenant. Do not leave DEBUG of full events on after a campaign.

Dashboard before a campaign

API 5xx and latency. Lambda throttles, duration versus timeout, concurrent executions versus reserved cap. Queue depth and age. DLQ depth. EventBridge TriggeredRules versus PutEvents. DynamoDB throttles and user errors. KMS and Secrets denies. Log IncomingBytes.

If a dashboard cannot answer “is this poison or capacity?”, add age next to depth before you add another vanity count.

SIGNAL

Use the SIGNAL lesson on every incident drill. Metrics before logs when the question is capacity vs poison.

How to open (say it)

“I will keep one request id across the hop from API Gateway to the worker. Dashboards without ids are decoration.”

Real world — T-01

p99 is 28s. Trace ends in warehouse.charge. REPORT Init Duration is 80ms. You do not say cold start. You move the charge off the request path and keep the id so the 202 can be joined to the worker.

Common mistakes

COMMON MISTAKE: A new uuid in every hop.

COMMON MISTAKE: Logging the entire EventBridge detail in production.

INTERVIEW TIP: Name two paging metrics (age + DLQ) before you name X-Ray.

Cost and performance8 min

Cost and performance

Cost and performance — deep dive

In one sentence: Slice the bill by service and utilization. Do not quote unit prices from memory — they change. Optimize the expensive hop you measured.

Serverless cost flow You pay for requests, duration, memory (GB-s), chatter (API/SQS/GSI writes), and idle provisioned capacity. RequestsAPIGW + Lambda GB-secondsmemory × time ChatterSQS / GSI / NAT Provisionedwarm tax Storage Dynamo + logsRight-size memory for CPU. Batch to cut invokes. Cache reads. Kill chatty logs. Destroy lab stacks. Never paste list prices into slides.Interview: I optimize the expensive hop I measured. I do not quote a blog's 'Lambda is cheaper than EC2' as a fact. Which two levers usually dominate a chatty Lambda + DynamoDB bill?
Serverless cost flow
Lambda concurrency Account concurrency is a shared ceiling. Reserved carves a pool. Provisioned keeps environments warm. Account poolshared burst + limit Reservedguaranteed for this fn Provisionedwarm Init paid forReserved concurrency also caps the function. A reserved=5 checkout function cannot stampede the account — and cannot scale past 5.Interview: I isolate a noisy neighbor with reserved. I buy provisioned only when p99 Init misses the SLA. Quotas are not memorized — I check the current account/region. What does reserved concurrency guarantee — and what does it cap?
Lambda concurrency
VPC Lambda A VPC attachment is for private resources. It is not a security upgrade for a public HTTPS API. Non-VPC LambdaAWS APIs via public endpoints VPC ENI pathprivate subnet + NAT/endpoints Need VPC whenRDS / ElastiCache / private APIHyperplane ENIs reduced classic cold-start pain, but you still own subnet IPs, NAT cost, and interface endpoints.Interview: I keep Lambda out of VPC unless it must reach a private resource. I do not 'put it in VPC for security' as a reflex. When do you attach Lambda to a VPC — and when do you refuse?
VPC Lambda

Why this matters

T-29 is “our serverless bill doubled.” Traffic up 15% with a 2× bill is almost never the slogan “Lambda is expensive.” It is a multiplier you can name.

Multipliers

LeverHow it explodes
Retries / poison loopsSame work, N times, plus DLQ if you forgot one
Idle provisioned concurrencyWarm tax with no traffic
NAT for AWS APIsVPC functions calling DynamoDB/S3 through NAT
Log ingestionDEBUG full events (T-28)
Scans / GSI write ampEvery write pays extra indexes
Standard workflow around one LambdaState transitions you did not need

Performance that saves money

Faster functions use fewer GB-seconds, but a slow function behind a queue may be cheaper than provisioned concurrency you do not need. Memory also scales CPU — shrinking memory can lengthen duration and raise cost. Measure p99 and utilization.

Batch to cut invokes when the SLO allows (C-24). Confirm current size and count limits at implementation time — do not hard-code folklore.

Lab hygiene

Local pytest is the default. Optional cloud stacks stay tagged and get destroyed the same day. No always-on NAT for a weekend exercise.

How to answer “our serverless bill doubled”

Open cost by service, not by emotion:

  1. Provisioned concurrency utilization.
  2. NAT bytes from VPC functions that only call AWS APIs.
  3. Logs IncomingBytes versus invocations.
  4. Retry and DLQ loops.
  5. Scan / GSI write amplification.
  6. Step Functions on one-step jobs.

Then offer a kill: disable idle provisioned concurrency, move AWS traffic off NAT, drop DEBUG, stop the poison loop.

How to open (say it)

“I will not quote a list price. I will name the multiplier I would measure first.”

Common mistakes

COMMON MISTAKE: Reciting a blog’s “Lambda is cheaper than EC2.”

COMMON MISTAKE: Pasting last year’s GB-second price into a slide.

INTERVIEW TIP: Say “utilization” and “multiplier.” That is the staff cost vocabulary.

Download the full lab (all code)

Serverless order platform lab: accept, queue, persist, notify, and recover. Unzip and run pytest locally with mocked AWS. BayLearn does not execute candidate AWS accounts.

Download serverless-order-platform-lab.zip

You will

  • Run the local lab path without live AWS keys
  • Prove a replay does not double-charge

Lab 501 — Serverless order platform (LAB-SVL-501)40 min

Lab 501 — Serverless order platform (LAB-SVL-501)

Production order lab — deep dive

In one sentence: LAB-SVL-501 is the platform you keep drawing: idempotent create, DynamoDB, outbox, queue worker, DLQ, traces. Default path is local pytest. Optional Terraform is destroyed the same day.

Order processing lab LAB-SVL-501: API accepts an order, queue processes it, table stores it, bus notifies, machine recovers — then destroy the stack. HTTP APIPOST /orders Lambdavalidate SQSwork Worker + DDBidempotent EventBridge + SFnnotify / sagaDefault path is local pytest with mocked AWS. Optional Terraform is tagged, budgeted, and destroyed. Cost warning lives in the lab README.Interview: I can draw this, name the idempotency key, the DLQ, and the compensation. I do not leave a lab stack running overnight. What is the cheapest correct default for LAB-SVL-501?
Order processing lab
Transactional outbox Write the business row and the outbound event in the same transaction. Publish from the outbox, not from the request thread. App writeorder + outbox row Outbox poll / streampublisher Bus / queuedownstreamEmit-after-commit in the handler loses events on a crash. Emit-before-commit publishes ghosts. The outbox makes the write and the intent atomic.Interview: DynamoDB TransactWriteItems (item + outbox) or a stream of the committed item. I do not dual-write in application code. Why is a dual write from the handler not an outbox?
Transactional outbox
Partial batch failure Succeed the items you wrote. Return the item identifiers that must retry. Do not throw the whole batch. Batch of 5one Lambda invoke 3 succeededside effects committed 2 failedReportBatchItemFailuresWithout partial failure, SQS redelivers all five — including the three you already charged or emailed. That is how duplicates become incidents.Interview: I make each record idempotent AND I report failures. Either alone is incomplete. Why must you report failed item IDs instead of throwing?
Partial batch failure
Idempotency At-least-once delivery means every write needs a natural or generated key the store can reject as a duplicate. RequestIdempotency-Key Conditional writeattribute_not_exists(pk) Replaysame result / 200SQS, Lambda async, API retries, and client double-submit all replay. 'The function is idempotent because it is a Lambda' is false.Interview: I name the key (orderId, eventId, Idempotency-Key) and the condition. I store the first response so retries do not charge twice. Where do you store the first successful result for a replayed key?
Idempotency

Why this matters

The lab is your story bank for the mock: “when we injected a timeout after write, the key saved us.” Bring one metric and one log line, not a tour of every file. BayLearn does not execute candidate AWS accounts.

Architecture

  1. HTTP POST /orders → create Lambda.
  2. Validate, authorize, TransactWrite order + outbox + idempotency.
  3. EventBridge fans out the fact.
  4. SQS holds fulfillment work with reserved concurrency.
  5. Worker uses partial batch failure and a conditioned write.
  6. DLQ is the operator inbox. Correlation id is on every hop.

Local path uses mocked AWS and pytest. That is the cheapest correct default.

What you must prove

ProofHow
Replay does not double-createSame Idempotency-Key → one order
Partial batchFour successes stay done; one id reported
DLQPoison payload classified, not infinitely retried
OutboxNo swallowed publish; unpublished row exists if relay fails

Parts (do not gold-plate)

A Infrastructure or local compose. B Create API and validation. C Event flow. D Queue consumer. E DLQ. F Failure injection (timeout, poison, throttle). G Observability fields. H Load thoughts without melting a personal account. I Optional Step Functions extension. J Cleanup.

If you apply cloud resources, tag them and destroy them before you leave. Do not hard-code stale quotas or prices in Terraform comments you would not defend.

What to show the instructor

A green local test for idempotent create, a DynamoDB item collection you can sketch, an outbox row, and one injected failure with a SIGNAL note. Do not spend the hour formatting Terraform outputs.

How to open in the mock (say it)

“Create is sync and short. Fulfillment is a queue. The key and the outbox are how a timeout after write and a swallowed publish do not fork reality.”

Common mistakes

COMMON MISTAKE: Treating optional Terraform as the lab.

COMMON MISTAKE: Leaving a stack running overnight.

INTERVIEW TIP: Pick one injected failure and tell it with SIGNAL. That is the artifact, not extra endpoints.

Lab README

Lab README

Lab — BayLearn production serverless order platform

text

Client → API Gateway → CreateOrder Lambda → DynamoDB
       → EventBridge → SQS OrderProcessing → ProcessOrder Lambda → DynamoDB
Failure: SQS retries (maxReceiveCount 3) → DLQ

Cross-cutting: IAM least privilege, customer-managed KMS, CloudWatch alarms, correlation IDs, Terraform.

This is a BayLearn interview lab, not an AWS certification lab and not an AWS endorsement. You prove a production state machine locally with pytest. AWS deploy is optional.

Cost warning

Optional terraform apply creates Lambda, HTTP API, DynamoDB (on-demand), SQS, EventBridge, KMS, and CloudWatch log groups/alarms in your account.

  • Typical cost is under $2 if you terraform destroy the same day.
  • Never leave resources running overnight. Idle EventBridge rules, log ingestion, and forgotten stacks are how student bills surprise people.
  • Log groups retain 7 days. That is still not an excuse to keep the stack.
  • Do not run uncontrolled load tests. No artillery, locust, or “just 10k orders.” Synthetic C123 / P100 only.
  • Tag everything Project=baylearn-serverless-lab (the Terraform in this pack already does).
  • Do not commit credentials, terraform.tfvars, or *.tfstate.

What you build

PathWhat it is
lambda/create_order.pyPOST /orders — validate, claim Idempotency-Key, persist RECEIVED + outbox
lambda/get_order.pyGET /orders/{orderId}
lambda/list_customer_orders.pyGET /customers/{customerId}/orders
lambda/cancel_order.pyPOST /orders/{orderId}/cancel — only from RECEIVED
lambda/process_order.pySQS batch worker — partial batch failure, poison vs retry
lambda/store.pyIn-memory multi-table store for pytest; optional DynamoDB adapter
terraform/Optional AWS deploy
scripts/local_server.pySame HTTP API on :8080 with no AWS
scripts/demo.shSame key twice → same orderId
tests/pytest, no AWS / no boto3

API

Create

http

POST /orders
Idempotency-Key: client-request-123
Content-Type: application/json

{"customerId":"C123","items":[{"productId":"P100","quantity":2,"unitPrice":19.99}]}

First success is 201. Replay of a completed key is 200 with the prior order. Missing key is 400. Same key, different body is 409.

Read / list / cancel

http

GET  /orders/{orderId}
GET  /customers/{customerId}/orders
POST /orders/{orderId}/cancel

State machine

text

RECEIVED → PROCESSING → COMPLETED
RECEIVED → CANCELLED          (explicit cancel only)
PROCESSING → FAILED           (poison or exhausted retries)

Cancel is allowed only from RECEIVED. PROCESSING, COMPLETED, and FAILED return 409.

1. Prove it locally (no AWS)

bash

cd labs/serverless-order-platform
python3 -m pip install -q -r requirements-dev.txt
python3 -m pytest -q
python3 scripts/local_server.py

In another terminal:

bash

chmod +x scripts/demo.sh
./scripts/demo.sh

You should see PASS: same orderId on retry and HTTP 409 when the quantity changes.

2. Optional Terraform (same day, then destroy)

bash

cd terraform
cp terraform.tfvars.example terraform.tfvars
# edit name_prefix — your initials, lowercase
terraform init
terraform apply

Note orders_url. Point the demo at AWS:

bash

ORDERS_URL="$(terraform output -raw orders_url)" ../scripts/demo.sh

Tear it down before you walk away:

bash

terraform destroy

Confirm log groups /aws/lambda/{prefix}-* are gone or aging out at 7 days. Do not leave the stack “for later.”

Validation

  1. Same Idempotency-Key → same orderId, second call 200
  2. Orders table does not grow on retry
  3. Same key, different items → 409
  4. Missing key → 400 MISSING_IDEMPOTENCY_KEY
  5. Store down (store.down = True) → 503 fail closed
  6. ProcessOrder reports batchItemFailures only for retryable records
  7. Permanent poison is recorded and not retried
  8. After 3 retryable receives the message is on the DLQ
  9. Cancel from RECEIVED works; cancel from COMPLETED is 409

Interview talking points

  • Claim the idempotency key before you mint an order
  • Write the order and the outbox in one transaction, then publish
  • SQS is at-least-once — ProcessOrder must be idempotent
  • Permanent validation errors must not block the rest of the batch
  • Retryable errors use ReportBatchItemFailures; three strikes → DLQ
  • Correlation IDs travel on the HTTP request, the event, and the logs
  • This lab is DynamoDB + Lambda so a student account stays cheap. Say that out loud. Do not pretend it is your 50k QPS multi-region order fabric.

Cleanup

See cleanup.md. Short version: cd terraform && terraform destroy.

Cleanup

Cleanup

Cleanup

Destroy the same day. This lab is not meant to stay in an account.

Terraform

bash

cd terraform
terraform destroy

Confirm your prefix is gone:

bash

aws lambda list-functions --query "Functions[?starts_with(FunctionName, \`YOURPREFIX\`)].FunctionName"
aws dynamodb list-tables --query "TableNames[?contains(@, \`YOURPREFIX\`)]"
aws sqs list-queues --queue-name-prefix YOURPREFIX

KMS keys stay in a 7-day pending deletion window. That is expected. Do not schedule another lab on the same alias until the key is gone, or pick a new name_prefix.

Log groups are created with 7-day retention. After destroy they should be deleted with the stack. If a log group was created outside Terraform, delete it:

bash

aws logs delete-log-group --log-group-name /aws/lambda/YOURPREFIX-create-order

Local

No AWS resources. Stop scripts/local_server.py with Ctrl-C. Nothing to bill.

Do not

  • Leave EventBridge + Lambda “for the weekend”
  • Run load tests against the student API
  • Commit *.tfstate, terraform.tfvars, or access keys

Architecture

Architecture

Order platform lab architecture

What this lab is (and is not)

Production (interview whiteboard)This student lab
Edge + WAF + dedicated order serviceHTTP API → Lambda
Aurora / order DB + outbox tableDynamoDB multi-table (orders, customer_orders, idempotency, outbox, processed_events)
Separate publisher workerCreateOrder publishes after commit; unpublished outbox is the backstop
Multi-region, exactly-once marketingAt-least-once SQS + idempotent ProcessOrder

The state machine is what you defend in the interview. The AWS services are sized for a same-day lab.

text

Client
  │  POST /orders  + Idempotency-Key
  ▼
API Gateway (HTTP API)
  │
  ▼
CreateOrder Lambda
  │  1. validate
  │  2. claim idempotency (conditional put)
  │  3. transaction: order RECEIVED + customer_orders + outbox
  │  4. PutEvents (or local enqueue)
  ▼
DynamoDB (SSE-KMS)
  │
  ▼
EventBridge custom bus  (source=order-platform, detail-type=order.created)
  │
  ▼
SQS OrderProcessing  ──retries (3)──► DLQ
  │
  ▼
ProcessOrder Lambda
  │  skip duplicates / terminal orders
  │  poison (permanent) → success for the batch item
  │  retryable → ReportBatchItemFailures
  ▼
DynamoDB  RECEIVED → PROCESSING → COMPLETED

Why multi-table (not single-table)

Single-table design is a valid production choice. This lab does not force it. Four small tables keep the access patterns obvious:

TableKeyWhy
ordersorderIdGet / update status
customer_orderscustomerId + orderIdList a customer's orders
idempotencypk = key, TTL 24hClaim / replay
outboxoutboxIdEvent written with the order
processed_eventseventIdWorker exactly-once-enough

A GSI on orders (customerId) would also list orders. A dedicated table is equally honest.

Idempotent create

  1. Require Idempotency-Key.
  2. Hash {customerId, items}.
  3. Conditional put claims processing.
  4. If completed — return cached body (200). No second order.
  5. If processing — 409 in flight.
  6. If hash clashes — 409.
  7. Else write RECEIVED + outbox atomically (store.transaction() locally; TransactWriteItems on AWS).
  8. Publish order.created. Return 201.

If the store is down, fail closed (503). Do not mint an order you cannot remember.

ProcessOrder and the batch

SQS can deliver a mix of good and bad records.

  • Idempotent: same eventId or an already COMPLETED / CANCELLED order is a no-op.
  • Permanent (malformed, missing orderId, invalid_version): record poison, mark FAILED when we have an order, do not list the message in batchItemFailures. SQS deletes it. It must not block siblings.
  • Retryable (timeout, downstream_500, permission_denied): batchItemFailures = [{itemIdentifier}]. After maxReceiveCount = 3 the message lands on the DLQ and the order is marked FAILED.

Visibility timeout (90s) is greater than the function timeout (30s). Do not invert those.

Cancel rules

Cancel is a deliberate customer action, not a retry.

Current statusResult
RECEIVEDCANCELLED (200)
CANCELLED200 (idempotent)
PROCESSING / COMPLETED / FAILED409 ORDER_NOT_CANCELLABLE
missing404

Once processing has started, compensation is a different API (not in this lab).

Security and operability

  • Customer-managed KMS with rotation. EventBridge and SQS must be on the key or the queue stays empty.
  • IAM on named tables, the process queue, and the event bus. No AdministratorAccess.
  • Log groups /aws/lambda/{prefix}-* retain 7 days.
  • Alarms: DLQ visible > 0, oldest message age, Lambda errors.
  • Every mutating request carries X-Correlation-Id (or we mint one). Errors return {"code","message","requestId"}.

Synthetic data only

Use C123, P100, and keys like client-request-123. Do not load production customer files into a student account.

Failure drill

Failure drill

Failure drill

failures.py injects the interview cases. Local tests pass a labFailure on the event detail. ProcessOrder classifies them:

InjectionClassBatch behaviorOrder
timeoutretryableReportBatchItemFailuresstays RECEIVED until success or DLQ
downstream_500retryablesamesame
permission_deniedretryablesamesame
malformedpermanentnot retried; poison recordedunchanged (or FAILED if we can identify it)
invalid_versionpermanentpoison; no retryFAILED
duplicateskipsuccessno double complete

Receive count 3 on a retryable record → local store DLQ + FAILED. On AWS, SQS maxReceiveCount = 3 moves the message to the DLQ.

Crash after claim (create path)

X-Lab-Crash-After-Claim: 1 claims the key and returns 504. The order is not written. Retry the same key → 409 in flight.

bash

URL="http://127.0.0.1:8080/orders"

curl -sS -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-after" \
  -H "X-Lab-Crash-After-Claim: 1" \
  -d '{"customerId":"C123","items":[{"productId":"P100","quantity":2,"unitPrice":19.99}]}'
# 504

curl -sS -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: crash-after" \
  -d '{"customerId":"C123","items":[{"productId":"P100","quantity":2,"unitPrice":19.99}]}'
# 409 REQUEST_IN_FLIGHT

Do not mint a new key because the first call “failed.” That is a second order.

Partial batch (pytest)

tests/test_partial_batch.py sends [good, timeout, good, malformed]. Only timeout appears in batchItemFailures. The two good orders reach COMPLETED. Malformed is poison.

DLQ (pytest)

tests/test_dlq.py delivers the same timeout record with receive counts 1, 2, 3. On the third receive the store’s DLQ has the message and the order is FAILED.

AWS-only drills (optional, same day)

  1. Remove events.amazonaws.com from the CMK policy — CreateOrder still 201, queue stays empty, status RECEIVED.
  2. Set ProcessOrder reserved concurrency to 0 — queue depth grows, ingest still 201. Put it back.
  3. Publish a record with detail.labFailure = "timeout" three times — DLQ alarm ApproximateNumberOfMessagesVisible > 0.

Put the lab back, then terraform destroy the same day. Do not leave concurrency at 0.

How to test

How to test

Test and demo path

Time: 15–20 minutes locally, plus 15–25 minutes if you deploy to AWS

Cost: $0 locally. Under $2 on AWS if you terraform destroy the same day.

This is not an AWS certification lab.

In one sentence: Prove that a second POST /orders with the same Idempotency-Key returns the same orderId — then process it to COMPLETED without double-applying.

Path A — Read the state machine (no laptop)

Say this out loud:

text

missing Idempotency-Key        → 400
store down                     → 503 fail closed
completed key                  → 200 cached order   ← the demo
processing key                 → 409 in flight
same key + different body      → 409
RECEIVED → cancel              → CANCELLED
PROCESSING / COMPLETED / FAILED → cancel 409
SQS retryable                  → ReportBatchItemFailures
SQS permanent                  → poison, do not retry
3 retryable receives           → DLQ

Open lambda/create_order.py (claim_idempotency, transaction, 201 vs 200).

Open lambda/process_order.py (batchItemFailures, poison).

Open lambda/outbox.py.

Path B — Local demo (required, no AWS)

bash

cd labs/serverless-order-platform
python3 -m pip install -q -r requirements-dev.txt
python3 -m pytest -q

Expected: all tests passed.

FileWhat it proves
test_create_order.py201, RECEIVED, get, list, correlation id
test_idempotency.pyreplay 200, 409 hash clash, 409 in flight, 503
test_process_order.pyRECEIVED → COMPLETED, duplicates, EventBridge wrapper
test_partial_batch.pyonly retryable ids in batchItemFailures
test_dlq.pythird timeout → DLQ + FAILED
test_validation.pyitems / cancel rules
test_outbox.pytransaction rollback writes nothing

Start the local API (synthetic data only):

bash

python3 scripts/local_server.py

Other terminal:

bash

chmod +x scripts/demo.sh
./scripts/demo.sh

Expected:

  1. First POST → 201 and ord_… in RECEIVED
  2. Second POST → 200, same orderId, x-idempotent-replay: true
  3. GET /orders/{id} and GET /customers/C123/orders
  4. Same key, quantity 9 → 409
  5. Create + cancel → CANCELLED

The local worker drains the in-memory queue so the first order should move to COMPLETED within a second. Cancel uses a new key so it is still RECEIVED when you cancel.

Manual curl

bash

KEY="demo-$(date +%s)"
URL="http://127.0.0.1:8080/orders"

curl -sS -D - -X POST "$URL" \
  -H "content-type: application/json" \
  -H "Idempotency-Key: $KEY" \
  -H "X-Correlation-Id: demo-corr" \
  -d '{"customerId":"C123","items":[{"productId":"P100","quantity":2,"unitPrice":19.99}]}'

Path C — AWS (optional, same day)

bash

cd terraform
cp terraform.tfvars.example terraform.tfvars   # set name_prefix
terraform init
terraform apply
ORDERS_URL="$(terraform output -raw orders_url)" ../scripts/demo.sh
terraform destroy

Wait a few seconds after create for EventBridge → SQS → ProcessOrder before you assert COMPLETED on AWS.

Never leave this stack running. Log retention is 7 days. Do not run load tests.

What to say while you demo (30 seconds)

“I claim the Idempotency-Key before I write the order. Same key replays the cached orderId. I persist the order and the outbox in one transaction, then publish order.created to EventBridge. ProcessOrder is at-least-once: duplicates no-op, permanent poison is dropped from the batch, retryable records use ReportBatchItemFailures, and three strikes go to the DLQ. Cancel is only legal from RECEIVED. If the store is down I fail closed.”

Mark complete when

  • [ ] python3 -m pytest -q is all passed
  • [ ] demo.sh prints PASS and 409
  • [ ] You can explain poison vs retry without retrying a malformed record
  • [ ] If you applied Terraform: terraform destroy finished

Read the lab source

Same files as the zip. Open one at a time — map the function to the interview sentence.

Create order

python

"""POST /orders — validate, claim idempotency key, persist RECEIVED + outbox."""

from __future__ import annotations

import json
from typing import Any

from errors import api_error, api_ok
from events import order_created
from logging_util import body_of, correlation_id_of, headers_of, log_json, method_of, path_of, request_id_of
from outbox import new_item, publish_item
from store import StoreDown, get_store, new_order_id, now_iso, request_hash


def validate_create(body: dict[str, Any]) -> tuple[str, str] | None:
    customer_id = body.get("customerId")
    if not isinstance(customer_id, str) or not customer_id.strip():
        return ("INVALID_CUSTOMER", "customerId is required")
    items = body.get("items")
    if not isinstance(items, list) or not items:
        return ("INVALID_ITEMS", "items must be a non-empty array")
    for idx, item in enumerate(items):
        if not isinstance(item, dict):
            return ("INVALID_ITEMS", f"items[{idx}] must be an object")
        product_id = item.get("productId")
        if not isinstance(product_id, str) or not product_id.strip():
            return ("INVALID_ITEMS", f"items[{idx}].productId is required")
        qty = item.get("quantity")
        if isinstance(qty, bool) or not isinstance(qty, int) or qty < 1:
            return ("INVALID_ITEMS", f"items[{idx}].quantity must be a positive integer")
        price = item.get("unitPrice")
        if isinstance(price, bool) or not isinstance(price, (int, float)) or price < 0:
            return ("INVALID_ITEMS", f"items[{idx}].unitPrice must be a number >= 0")
    return None


def public_order(order: dict[str, Any]) -> dict[str, Any]:
    return {
        "orderId": order["orderId"],
        "customerId": order["customerId"],
        "items": order["items"],
        "total": order["total"],
        "status": order["status"],
        "version": order.get("version", 1),
        "createdAt": order.get("createdAt"),
        "updatedAt": order.get("updatedAt"),
        "correlationId": order.get("correlationId"),
    }


def build_order(body: dict[str, Any], correlation_id: str) -> dict[str, Any]:
    items = []
    total = 0.0
    for item in body["items"]:
        qty = int(item["quantity"])
        price = float(item["unitPrice"])
        line = {
            "productId": str(item["productId"]).strip(),
            "quantity": qty,
            "unitPrice": price,
        }
        items.append(line)
        total += qty * price
    created = now_iso()
    return {
        "orderId": new_order_id(),
        "customerId": str(body["customerId"]).strip(),
        "items": items,
        "total": round(total, 2),
        "status": "RECEIVED",
        "version": 1,
        "createdAt": created,
        "updatedAt": created,
        "correlationId": correlation_id,
    }


def handler(event: dict[str, Any], context: Any, store=None) -> dict[str, Any]:
    store = store or get_store()
    request_id = request_id_of(context)
    cid = correlation_id_of(event, context)

    if method_of(event) == "GET" and path_of(event).rstrip("/").endswith("/health"):
        return api_ok(200, {"ok": True, "service": "order-platform"})

    try:
        body = body_of(event)
    except (json.JSONDecodeError, ValueError, TypeError):
        return api_error(400, "INVALID_JSON", "request body must be valid JSON", request_id)

    headers = headers_of(event)
    key = (headers.get("idempotency-key") or "").strip()
    if not key:
        return api_error(400, "MISSING_IDEMPOTENCY_KEY", "Idempotency-Key header is required", request_id)

    invalid = validate_create(body)
    if invalid:
        return api_error(400, invalid[0], invalid[1], request_id)

    payload = {"customerId": str(body["customerId"]).strip(), "items": body["items"]}
    req_hash = request_hash(payload)

    try:
        claim = store.claim_idempotency(key, req_hash)
    except StoreDown:
        return api_error(503, "STORE_UNAVAILABLE", "idempotency store unavailable — fail closed", request_id)

    row = claim.get("row") or {}
    if not claim.get("created"):
        if row.get("requestHash") and row["requestHash"] != req_hash:
            return api_error(409, "IDEMPOTENCY_KEY_REUSED", "same Idempotency-Key with a different body", request_id)
        if row.get("status") == "completed":
            cached = row.get("responseBody") or {}
            log_json("info", "idempotent replay", correlationId=cid, requestId=request_id, orderId=cached.get("orderId"))
            return api_ok(200, cached, {"x-idempotent-replay": "true", "x-correlation-id": cid})
        if row.get("status") == "processing":
            return api_error(409, "REQUEST_IN_FLIGHT", "request in flight — retry the same key", request_id)
        if row.get("status") == "failed":
            cached = row.get("responseBody") or {"code": "PREVIOUS_ATTEMPT_FAILED", "message": "previous attempt failed"}
            return api_ok(int(row.get("responseStatus") or 400), cached, {"x-idempotent-replay": "true"})

    if headers.get("x-lab-crash-after-claim") == "1":
        return api_error(504, "LAB_CRASH_AFTER_CLAIM", "lab crash after claim — row left processing", request_id)

    order = build_order(body, cid)
    envelope = order_created(order, cid)
    outbox_item = new_item(envelope)

    try:
        with store.transaction():
            store.put_order(order)
            store.put_customer_order(order["customerId"], order)
            store.put_outbox(outbox_item)
            store.complete_idempotency(key, 201, public_order(order), order["orderId"])
    except StoreDown:
        return api_error(503, "STORE_UNAVAILABLE", "order store unavailable — fail closed", request_id)
    except Exception as exc:  # noqa: BLE001
        log_json("error", "create transaction failed", correlationId=cid, requestId=request_id, error=str(exc))
        return api_error(500, "CREATE_FAILED", "could not persist order and outbox", request_id)

    try:
        publish_item(store, outbox_item)
    except Exception as exc:  # noqa: BLE001
        log_json("error", "outbox publish deferred", correlationId=cid, orderId=order["orderId"], error=str(exc))

    log_json("info", "order created", correlationId=cid, requestId=request_id, orderId=order["orderId"])
    return api_ok(201, public_order(order), {"x-idempotent-replay": "false", "x-correlation-id": cid})

You will

  • Sit a 45–60 minute mock
  • Leave with a weighted score and 7-day plan

Mock interview brief5 min

Mock interview brief

Mock interview process — deep dive

In one sentence: Module 6 is a 45–55 minute rehearsal against the Serverless Engineer rubric. It is not a hiring decision.

EVENT interview framework Do not start with service logos. Name the user action, the fact, the first async boundary, then failure. EEstablish reqs + facts VVolume / velocity EExecution + state NNeutralize failure TTrace + trade-offE: who acts, do they wait, what fact is published, who is allowed. V: burst, payload, slowest downstream. Second E: first async boundary in ink.N: retries, DLQ, idempotency key, timeout formula, IAM. T: correlation, cost, the design you rejected.Fail phrase: 'We will use Lambda, API Gateway, SQS, EventBridge, DynamoDB, and Step Functions' before requirements. What do you name before you draw the first AWS logo?
EVENT interview framework
SIGNAL incident framework Async systems fail in a different hop than they were triggered. Guessing 'Lambda bug' is how you miss a rule mismatch. SScope impact IInspect metrics GGather traces NNarrow domain AApply safe fix LLearn / preventAge without depth = poison. Depth without errors = capacity. TriggeredRules at zero = routing, not the worker.Mitigations that are rarely safe: purge a production queue, raise retries to infinity, leave DEBUG of full events on.Interview: I pick one primary domain before I change three knobs. L is a test + alarm, not 'be more careful'. What do you inspect before you open the worker logs?
SIGNAL incident framework
Order processing lab LAB-SVL-501: API accepts an order, queue processes it, table stores it, bus notifies, machine recovers — then destroy the stack. HTTP APIPOST /orders Lambdavalidate SQSwork Worker + DDBidempotent EventBridge + SFnnotify / sagaDefault path is local pytest with mocked AWS. Optional Terraform is tagged, budgeted, and destroyed. Cost warning lives in the lab README.Interview: I can draw this, name the idempotency key, the DLQ, and the compensation. I do not leave a lab stack running overnight. What is the cheapest correct default for LAB-SVL-501?
Order processing lab

Clock

Background 5. Lambda/API 10. Messaging 10. DynamoDB 10. Reliability/security 10. Design/troubleshoot and your questions in the remaining time. If they skip ahead, follow the interviewer — then return to the missing EVENT letter.

How to talk

Clarify before boxes. Name events as facts. Draw the async boundary. State the idempotency key. Name one risk and the metric that would page. Offer the architecture you rejected.

Use the deep-dive diagrams as mental templates — do not recite service lists.

Probes

  • Engineer: where does work run, what is the PK, what if timeout after write.
  • Senior: outbox versus dual-write, hot keys, poison redrive.
  • Lead/staff: contract evolution, multi-account, when serverless is the wrong default.

Score

Ten dimensions in the rubric; DynamoDB and reliability are heavy. A score here does not mean you will or will not get hired. Read the feedback lesson after scoring.

Recovery when you freeze

Return to EVENT letters you have not said. If they hate your queue, ask the warehouse SLO and redesign from that number. If they push multi-region, name consistency and in-flight SQS before you draw a second region. Silence is worse than an incomplete box.

Mock process10 min

Mock process

Mock interview process — deep dive

In one sentence: Module 6 is a 45–55 minute rehearsal against the Serverless Engineer rubric. It is not a hiring decision.

EVENT interview framework Do not start with service logos. Name the user action, the fact, the first async boundary, then failure. EEstablish reqs + facts VVolume / velocity EExecution + state NNeutralize failure TTrace + trade-offE: who acts, do they wait, what fact is published, who is allowed. V: burst, payload, slowest downstream. Second E: first async boundary in ink.N: retries, DLQ, idempotency key, timeout formula, IAM. T: correlation, cost, the design you rejected.Fail phrase: 'We will use Lambda, API Gateway, SQS, EventBridge, DynamoDB, and Step Functions' before requirements. What do you name before you draw the first AWS logo?
EVENT interview framework
SIGNAL incident framework Async systems fail in a different hop than they were triggered. Guessing 'Lambda bug' is how you miss a rule mismatch. SScope impact IInspect metrics GGather traces NNarrow domain AApply safe fix LLearn / preventAge without depth = poison. Depth without errors = capacity. TriggeredRules at zero = routing, not the worker.Mitigations that are rarely safe: purge a production queue, raise retries to infinity, leave DEBUG of full events on.Interview: I pick one primary domain before I change three knobs. L is a test + alarm, not 'be more careful'. What do you inspect before you open the worker logs?
SIGNAL incident framework
Order processing lab LAB-SVL-501: API accepts an order, queue processes it, table stores it, bus notifies, machine recovers — then destroy the stack. HTTP APIPOST /orders Lambdavalidate SQSwork Worker + DDBidempotent EventBridge + SFnnotify / sagaDefault path is local pytest with mocked AWS. Optional Terraform is tagged, budgeted, and destroyed. Cost warning lives in the lab README.Interview: I can draw this, name the idempotency key, the DLQ, and the compensation. I do not leave a lab stack running overnight. What is the cheapest correct default for LAB-SVL-501?
Order processing lab

Clock

Background 5. Lambda/API 10. Messaging 10. DynamoDB 10. Reliability/security 10. Design/troubleshoot and your questions in the remaining time. If they skip ahead, follow the interviewer — then return to the missing EVENT letter.

How to talk

Clarify before boxes. Name events as facts. Draw the async boundary. State the idempotency key. Name one risk and the metric that would page. Offer the architecture you rejected.

Use the deep-dive diagrams as mental templates — do not recite service lists.

Probes

  • Engineer: where does work run, what is the PK, what if timeout after write.
  • Senior: outbox versus dual-write, hot keys, poison redrive.
  • Lead/staff: contract evolution, multi-account, when serverless is the wrong default.

Score

Ten dimensions in the rubric; DynamoDB and reliability are heavy. A score here does not mean you will or will not get hired. Read the feedback lesson after scoring.

Recovery when you freeze

Return to EVENT letters you have not said. If they hate your queue, ask the warehouse SLO and redesign from that number. If they push multi-region, name consistency and in-flight SQS before you draw a second region. Silence is worse than an incomplete box.

You will

  • Read the readiness report
  • Practice the weakest two skills first

Feedback and 7-day plan10 min

Feedback and 7-day plan

Feedback and seven-day plan

Module 7 is ten minutes of honesty. The report includes scores, strengths, weaknesses, and a practice plan. Instructors edit released feedback; private notes stay private. A score here does not mean you will or will not get hired. The BayLearn completion certificate is not an AWS certification.

Read the bars

A high Lambda score with a low DynamoDB score is a common senior-candidate shape. The mock weights modeling for a reason. Do not only grind coding challenges if your gap is EVENT.

Seven days

Day 1 Lambda + API Gateway. Day 2 SQS, retry, DLQ. Day 3 EventBridge, SNS, event design. Day 4 DynamoDB access patterns. Day 5 Idempotency, reliability, Step Functions. Day 6 Security, observability, cost. Day 7 a full mock. Swap days toward the weakest bars.

Artifacts

Re-draw the order platform from memory. Teach SIGNAL on T-01, T-10, T-17, T-32. Re-do DDB-01 and DDB-07 on paper. Keep downloads/final-serverless-interview-checklist.md nearby.

Certificate

The certificate is course completion after the mock path the product requires. It is not an AWS credential and not a job offer. It is not a license.

How to use the next 48 hours

Do not reread every lesson. Redraw the order platform from memory, then compare to diagrams/28-order-processing-lab.svg. Teach T-01, T-10, T-17, and T-32 to a rubber duck using SIGNAL. Re-do DDB-01 and DDB-07 on paper. Re-attempt the three coding challenges that match your weakest bar. Sleep. The seven-day plan is a sequence, not a dare to cram all 380 questions tonight. If an interview is Monday, prioritize the stories, not the trivia.

Pricing

Choose a delivery mode. BayAreaLa8s invoices after you request a session.

This text is a draft. It is not a current BayLearn offer and it does not change existing bookings. Read the draft refund policy

Self-paced

$59

Small group

$129

Live 1:1

$349

Introductory $299

Book a session

Request a slot. Invoicing is handled by BayAreaLa8s after the request — no Stripe checkout.

Log in or enroll to request a live session time.