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
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.
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.
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.
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.
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
sourceisorders.service, rule still matchesapp.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.
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 bar | Live session starts here |
|---|---|
| Messaging | Queue versus bus on a blank board |
| DynamoDB | Access-pattern worksheet, not single-table folklore |
| Reliability | Timeout-after-write until you can name the key |
| Security | Isolation walk: JWT → condition → KMS |
| Observability | Age 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.
- Reserved concurrency equal to expected peak, hoping the runtime stays warm
- Provisioned concurrency on the alias serving checkout, sized to the sale forecast
- Unreserved account concurrency so every function can steal capacity
- 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.
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
- A client calls API Gateway (HTTP API or REST API).
- The authorizer answers who is this?
- Lambda parses the proxy event, validates the body, and answers may they create this order?
- DynamoDB stores the order (and usually an idempotency / outbox item) under a condition.
- 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
| Step | Fail closed | Typical status |
|---|---|---|
| Parse | Malformed JSON / missing path | 400 |
| Validate | Schema, totals, currency | 400 |
| Authorize | Tenant and owner from the token | 403 |
| Write once | Condition / idempotency key | 201 or 409 |
| Respond | statusCode + string body | 200-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
- 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
= 5cannot 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.
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
| Signal | Look here first |
|---|---|
| p99 jumps after idle or a deploy | Init Duration, package size, VPC ENI |
| Every invoke is slow | Last outbound span, memory/CPU, lock, downstream |
| Errors with flat duration | Auth, 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
tenantIdin 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.
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 need | Lean |
|---|---|
| JWT / OIDC JSON API, lower latency/cost | HTTP API |
| API keys, request validation, edge cache, private API, WAF association you already standardized on REST | REST 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: 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
PutItemon 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 sees | Invocations | First hypothesis |
|---|---|---|
| 403 | Flat | WAF, resource policy, authorizer (T-04) |
| 502 | Rising | Illegal proxy response: dict body, missing statusCode, non-string header (T-05) |
| 504 / timeout | Rising, duration ≈ timeout | Integration vs Lambda budget; or a slow dependency |
| 429 | Rising | Stage/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
bodyand 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.
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
| Kind | Example | Primitive | Needs |
|---|---|---|---|
| Fact | OrderCreated | EventBridge (or SNS if the pattern is trivial) | Many subscribers, versioned envelope |
| Work | “Call the warehouse” | SQS | Backlog, visibility, DLQ, reserved concurrency |
| Notification | “Email the receipt” | SNS → maybe SQS | Fan-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.
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
ReportBatchItemFailuresand 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.
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)
- S: Only fulfillment, since 14:10, all tenants?
- I:
PutEventssuccess vsTriggeredRules. - G: Sample event
source/detail-typevs the rule. - N: Routing, not the worker, if rules are zero.
- A: Dual-match sources, replay from the outbox — do not purge.
- L: Contract test on
source.
How to open (say it)
“The bus routes facts. I will match
sourceanddetail-typebefore 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.”
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 machine | In a Lambda |
|---|---|
| Order of steps, wait, choice, parallel | Domain validation, one I/O hop |
| Per-state retry / catch | Idempotent call to one collaborator |
| Compensation routing | The 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.
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:
| Pattern | PK | SK | Notes |
|---|---|---|---|
| Create / get order | CUST#<tenant+customer> | ORDER#<id> | Condition on create |
| List customer orders | same PK | begins_with ORDER# | Item collection |
| Ops: failed fulfillment | GSI GSI1PK=FAILED | time | Sparse, 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#OPENis 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.
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
| Class | Examples | Action |
|---|---|---|
| Fail fast | 400, 403, 409, poison schema | Do not retry |
| Retry + jitter | throttle, transient 5xx, timeout | Cap + jitter |
| DLQ | unknown / poison after N receives | Operator inbox |
| Do not stack | SDK + Lambda async + SQS + Step Functions | Name one owner (T-26) |
AR-15 is infinite retry. Sleeping in the handler to backoff stalls drain (T-31).
The story that wins mocks
- Timeout after write → idempotency item (T-30).
- Swallowed PutEvents → outbox (T-32).
- Visibility too short → formula (T-10).
- Poison JSON → DLQ + classify (T-08, T-13).
- 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.
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
| Situation | Key |
|---|---|
| HTTP create | Client Idempotency-Key scoped by tenant + route |
| Payment capture | paymentId / charge id toward the PSP |
| S3 object | bucket + key + version |
| SQS receive | Not 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.
- Conditional begin: only one request becomes
IN_PROGRESS. - Do the side effect.
- Store the serialized response and mark
COMPLETEDwith TTL covering the retry window. - Replay returns the stored response.
- 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.
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:
- Write the business item (
ORDER#…). - Write an outbox item (
published=false) with a stable event id and the correlation id. - 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 happened | Recovery |
|---|---|
| Publish fails | Item stays unpublished; relay retries. Recoverable. |
| Publish succeeds, mark fails | Republish with the same event id. Consumers stay idempotent (T-27). |
| Swallow PutEvents | Lost fact. T-32. Not recoverable without the outbox row. |
Hot PK=OUTBOX | Throttle. 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:
PutItemthenPutEventsand 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.
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:
- Signature or JWT at the edge.
- Authorizer: who is this?
- Handler: tenant and owner from the token.
- DynamoDB condition that includes tenant id.
- IAM that cannot
Scanthe table and names resource ARNs. - KMS key policy (second plane).
- Secret ARN + cache (C-22), no long-lived secrets in images.
- 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
tenantIdin 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.
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,
TriggeredRulesvsPutEvents. - 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.
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
| Lever | How it explodes |
|---|---|
| Retries / poison loops | Same work, N times, plus DLQ if you forgot one |
| Idle provisioned concurrency | Warm tax with no traffic |
| NAT for AWS APIs | VPC functions calling DynamoDB/S3 through NAT |
| Log ingestion | DEBUG full events (T-28) |
| Scans / GSI write amp | Every write pays extra indexes |
| Standard workflow around one Lambda | State 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:
- Provisioned concurrency utilization.
- NAT bytes from VPC functions that only call AWS APIs.
- Logs IncomingBytes versus invocations.
- Retry and DLQ loops.
- Scan / GSI write amplification.
- 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.zipYou 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.
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
- HTTP
POST /orders→ create Lambda. - Validate, authorize, TransactWrite order + outbox + idempotency.
- EventBridge fans out the fact.
- SQS holds fulfillment work with reserved concurrency.
- Worker uses partial batch failure and a conditioned write.
- 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
| Proof | How |
|---|---|
| Replay does not double-create | Same Idempotency-Key → one order |
| Partial batch | Four successes stay done; one id reported |
| DLQ | Poison payload classified, not infinitely retried |
| Outbox | No 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) → DLQCross-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 destroythe 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/P100only. - Tag everything
Project=baylearn-serverless-lab(the Terraform in this pack already does). - Do not commit credentials,
terraform.tfvars, or*.tfstate.
What you build
| Path | What it is |
|---|---|
lambda/create_order.py | POST /orders — validate, claim Idempotency-Key, persist RECEIVED + outbox |
lambda/get_order.py | GET /orders/{orderId} |
lambda/list_customer_orders.py | GET /customers/{customerId}/orders |
lambda/cancel_order.py | POST /orders/{orderId}/cancel — only from RECEIVED |
lambda/process_order.py | SQS batch worker — partial batch failure, poison vs retry |
lambda/store.py | In-memory multi-table store for pytest; optional DynamoDB adapter |
terraform/ | Optional AWS deploy |
scripts/local_server.py | Same HTTP API on :8080 with no AWS |
scripts/demo.sh | Same 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}/cancelState 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.pyIn another terminal:
bash
chmod +x scripts/demo.sh
./scripts/demo.shYou 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 applyNote orders_url. Point the demo at AWS:
bash
ORDERS_URL="$(terraform output -raw orders_url)" ../scripts/demo.shTear it down before you walk away:
bash
terraform destroyConfirm log groups /aws/lambda/{prefix}-* are gone or aging out at 7 days. Do not leave the stack “for later.”
Validation
- Same
Idempotency-Key→ sameorderId, second call 200 - Orders table does not grow on retry
- Same key, different items → 409
- Missing key → 400
MISSING_IDEMPOTENCY_KEY - Store down (
store.down = True) → 503 fail closed - ProcessOrder reports
batchItemFailuresonly for retryable records - Permanent poison is recorded and not retried
- After 3 retryable receives the message is on the DLQ
- Cancel from
RECEIVEDworks; cancel fromCOMPLETEDis 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 destroyConfirm 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 YOURPREFIXKMS 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-orderLocal
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 service | HTTP API → Lambda |
| Aurora / order DB + outbox table | DynamoDB multi-table (orders, customer_orders, idempotency, outbox, processed_events) |
| Separate publisher worker | CreateOrder publishes after commit; unpublished outbox is the backstop |
| Multi-region, exactly-once marketing | At-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 → COMPLETEDWhy 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:
| Table | Key | Why |
|---|---|---|
orders | orderId | Get / update status |
customer_orders | customerId + orderId | List a customer's orders |
idempotency | pk = key, TTL 24h | Claim / replay |
outbox | outboxId | Event written with the order |
processed_events | eventId | Worker exactly-once-enough |
A GSI on orders (customerId) would also list orders. A dedicated table is equally honest.
Idempotent create
- Require
Idempotency-Key. - Hash
{customerId, items}. - Conditional put claims
processing. - If
completed— return cached body (200). No second order. - If
processing— 409 in flight. - If hash clashes — 409.
- Else write
RECEIVED+ outbox atomically (store.transaction()locally;TransactWriteItemson AWS). - 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
eventIdor an alreadyCOMPLETED/CANCELLEDorder is a no-op. - Permanent (
malformed, missingorderId,invalid_version): record poison, markFAILEDwhen we have an order, do not list the message inbatchItemFailures. SQS deletes it. It must not block siblings. - Retryable (
timeout,downstream_500,permission_denied):batchItemFailures = [{itemIdentifier}]. AftermaxReceiveCount = 3the message lands on the DLQ and the order is markedFAILED.
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 status | Result |
|---|---|
RECEIVED | CANCELLED (200) |
CANCELLED | 200 (idempotent) |
PROCESSING / COMPLETED / FAILED | 409 ORDER_NOT_CANCELLABLE |
| missing | 404 |
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:
| Injection | Class | Batch behavior | Order |
|---|---|---|---|
timeout | retryable | ReportBatchItemFailures | stays RECEIVED until success or DLQ |
downstream_500 | retryable | same | same |
permission_denied | retryable | same | same |
malformed | permanent | not retried; poison recorded | unchanged (or FAILED if we can identify it) |
invalid_version | permanent | poison; no retry | FAILED |
duplicate | skip | success | no 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_FLIGHTDo 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)
- Remove
events.amazonaws.comfrom the CMK policy — CreateOrder still 201, queue stays empty, statusRECEIVED. - Set ProcessOrder reserved concurrency to 0 — queue depth grows, ingest still 201. Put it back.
- Publish a record with
detail.labFailure = "timeout"three times — DLQ alarmApproximateNumberOfMessagesVisible > 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 → DLQOpen 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 -qExpected: all tests passed.
| File | What it proves |
|---|---|
test_create_order.py | 201, RECEIVED, get, list, correlation id |
test_idempotency.py | replay 200, 409 hash clash, 409 in flight, 503 |
test_process_order.py | RECEIVED → COMPLETED, duplicates, EventBridge wrapper |
test_partial_batch.py | only retryable ids in batchItemFailures |
test_dlq.py | third timeout → DLQ + FAILED |
test_validation.py | items / cancel rules |
test_outbox.py | transaction rollback writes nothing |
Start the local API (synthetic data only):
bash
python3 scripts/local_server.pyOther terminal:
bash
chmod +x scripts/demo.sh
./scripts/demo.shExpected:
- First POST → 201 and
ord_…inRECEIVED - Second POST → 200, same
orderId,x-idempotent-replay: true GET /orders/{id}andGET /customers/C123/orders- Same key, quantity 9 → 409
- 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 destroyWait 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 -qis all passed - [ ]
demo.shprints PASS and 409 - [ ] You can explain poison vs retry without retrying a malformed record
- [ ] If you applied Terraform:
terraform destroyfinished
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.
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.
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
Small group
Live 1:1
$349
Introductory $299
Book a session
Request a slot. Invoicing is handled by BayAreaLa8s after the request — no Stripe checkout.