BayLearn Weekend Interview Sprints
Python Backend Weekend Interview Sprint
Build It. Scale It. Explain It.
Practice core Python, asyncio, FastAPI, SQLAlchemy, idempotency, and production debugging — then defend the design in a scored mock.
- 4-Hour Live 1:1
- Core Python + FastAPI
- Asyncio & Concurrency
- Order Service Lab
- Practice Question Bank (190+)
Not sure if this is the right Sprint? Start with the assessment.
Refund terms are drafted and are not a current offer. Refund policy
Live 1:1 is $349. Introductory live 1:1 is $299 — a configured price, not a countdown.
Who this is for
- Python Developer
- Backend Engineer
- API Engineer
- Senior Software Engineer
- Full Stack Engineer
Best fit: You write Python in production and want sharper answers on FastAPI, async, data, and production behavior.
Not ideal: You are learning Python syntax for the first time.
What You Leave With
- Interview Readiness Score
- Top Strengths and Gaps
- Reusable Interview Framework
- Real Scenario Practice
- Mock Interview Score
- Personalized Feedback
- Question Bank
- 7-Day Preparation Plan
Four-hour agenda
Hour 1
Core concepts and interview patterns
Hour 2
Architecture / coding scenarios
Hour 3
Hands-on interview challenges
Hour 4
Mock interview and feedback
Meet Your Interview Coach
Himanshu Bhadra
Enterprise Architect | Cloud | AI | Distributed Systems | Technical Leadership
Learn by designing, building and explaining.
Availability
Private 1:1 · Book on request
Private 1:1 sessions are scheduled after you book. No public cohort dates are listed yet.
Formats: Group Sprint and Private 1:1 Sprint when scheduled.
Book a Free 15-Minute Interview Strategy CallFAQ
- Can I master the topic in four hours?
- No. The Sprint is focused interview preparation for people who already have relevant fundamentals or experience.
- What happens in the four hours?
- Targeted review, scenario practice, hands-on or architecture exercises, and a mock interview with feedback.
- Is it live 1:1?
- For the premium format, yes. Other delivery modes may be offered separately.
- Can I share my job description?
- Yes, so preparation can be better aligned to the target role.
- Do you guarantee I will pass?
- No. BayLearn improves preparation and readiness but does not guarantee hiring outcomes.
- What if my interview is next week?
- That is the primary use case for the Weekend Interview Sprint.
- What if I need more depth?
- Use a BayLearn Professional Program for deeper 8–16 week training.
- What is the refund policy?
- Refund terms are a draft and are not a current offer. They depend on the format you buy. Read the draft at /refund-policy/ before you enroll or book.
Need more than a weekend?
Professional Programs are 8–16 week paths with labs and capstones. Use a Sprint to get interview-ready, then a program if you need deeper mastery.
Explore Professional ProgramsDraft refund policy. Not a current offer.
Curriculum
Short lessons in interview order. Lab 501 is the FastAPI Order Service — download the zip, read the source here, then run pytest on your machine. BayLearn does not execute candidate code.
You will
- See the full lesson path before you book
- Know this is a Python/FastAPI interview sprint, not a textbook
Course overview5 min
Course overview
Python + FastAPI Backend Interview Sprint
Write the service, size it, then explain the trade-off.
A 4-hour BayLearn Interview Sprint. Python 3.12+ and FastAPI. You review the Python and FastAPI topics interviews actually hit, build a production-style Order Service, work coding problems, answer architecture questions, and sit a realistic mock interview.
This is not a compressed Python textbook. Interviewers will not stop at @app.post. They ask about idempotency, N+1, the GIL, and a mutable default argument.
Promise
Write a real answer, stretch it to retries and two workers, and say the trade-offs out loud. You leave with a readiness report and a 7-day plan. The score is rehearsal against the BayLearn rubric. It does not predict hiring.
Journey
text
ASSESS → PYTHON ESSENTIALS → ADVANCED PYTHON / ASYNC / CONCURRENCY
→ FASTAPI + PYDANTIC + REST → SQLALCHEMY / DATA / PRODUCTION
→ ORDER SERVICE LAB → MOCK INTERVIEW → FEEDBACK + 7-DAY PLANWhat interviews actually test
Can you write the code, explain it, talk about what happens in production, and defend the design? A typical loop looks like this:
- Implement
POST /ordersso a retry does not create two payments. - Explain why you chose Pydantic models at the edge and a service layer for the transaction.
- Find the N+1 query when listing orders with line items.
- Discuss what happens when inventory is reserved and payment later fails.
If you cannot talk through those four, decorator trivia will not carry you.
The four-hour agenda
| Module | Time | Topic |
|---|---|---|
| 0 | 15 min | Readiness Assessment |
| 1 | 35 min | Python Interview Essentials |
| 2 | 40 min | Advanced Python, Async & Concurrency |
| 3 | 40 min | FastAPI + REST + Pydantic |
| 4 | 35 min | SQLAlchemy, Data & Production Backend |
| 5 | 35 min | Live Coding + FastAPI Order Service |
| 6 | 45–60 min | Mock Interview |
| 7 | 10 min | Feedback & Practice Plan |
Who this is for
Python Developer, Backend Engineer, SWE / SWE II, Senior Backend, Tech Lead, Lead Backend, Staff Engineer, and Solutions Architects who still get a coding-plus-design loop. Tracks: ENGINEER, SENIOR_ENGINEER, LEAD_STAFF.
How to study
Say answers out loud. Ten questions spoken beat fifty skims. After each lesson, pick one order / payment / inventory example and teach the decision as if a staff engineer is sitting across from you.
Open the course overview next, then Module 0.
Instructor: BayAreaLa8s Team. Prices load from central configuration — do not expect amounts in this curriculum.
Start here
Start here
Course overview — Python + FastAPI Backend Interview Sprint
Write the service, size it, then explain the trade-off.
In one sentence: In four hours you practice the Python and FastAPI answers interviewers actually ask, then you build an Order Service, defend it in a mock, and leave with a 7-day plan.
Why this matters
Backend interviews are not “list the FastAPI decorators.” You write a correct function, keep money and inventory consistent, and explain what breaks when someone retries, two workers run at once, or load goes up.
People fail this loop in three common ways:
- They recite “lists are mutable” and then ship a mutable default argument that leaks state across requests.
- They say “Python cannot do concurrency because of the GIL,” then cannot explain threads for I/O or processes for CPU.
- They ship
POST /orderswithout an idempotency key, then cannot talk about double charges.
This sprint trains the spoken answer and the written code together.
What you will do
- Take a 20-question readiness assessment and see nine skill scores
- Review Python the way interviewers probe it: types, mutability, structures, functions
- Make iterator, typing, GIL, and asyncio decisions on order and payment examples
- Design REST + Pydantic the way a FastAPI service is actually reviewed
- Walk production patterns: SQLAlchemy 2.x, cache-aside, outbox, observability
- Build LAB-PF-501 locally with pytest — BayLearn does not execute your code
- Practice from a 190+ question bank and 25 coding challenges
- Run a scored 45–60 minute mock (ENGINEER / SENIOR / LEAD tracks)
- Leave with a weighted report and a 7-day plan
The lessons
Work them in order. Mark a lesson complete when you can teach the decision. Scrolling is not enough.
Start here — this overview.
Module 0 — How the assessment works · Readiness
Module 1 — Core types and mutability · Data structures · Functions, scope, copying
Module 2 — Iterators, generators, decorators · Typing and the object model · GIL · Asyncio
Module 3 — FastAPI fundamentals · Pydantic and Depends · REST, errors, auth
Module 4 — SQLAlchemy, transactions, N+1 · Caching, outbox, queues · Production engineering
Module 5 — Live coding + Order Service lab (LAB-PF-501)
Module 6 — Mock interview process
Module 7 — Feedback and 7-day plan
Who this is for
Engineers with roughly 1–12+ years who interview for Python backend roles. Full-stack candidates with a FastAPI or Django/Flask service on the resume belong here. If you have never written a FastAPI route, this sprint will feel compressed — take the assessment first and use the weak-skill list.
Tracks: ENGINEER, SENIOR_ENGINEER, LEAD_STAFF. Delivery: self-paced, small group, or live 1:1. Duration: 4 hours (3h45m–4h15m).
How to study
- Build it: write the function or sketch the handler. Do not only nod at the sample.
- Scale it: connect the idea to two workers, a retry, or a cache miss.
- Explain it: 60–90 seconds out loud, then one follow-up you expect.
Downloads live in downloads/. The player loads the same lesson text from course-ui/content/.
What this is not
Not a Python certification dump. Not a FastAPI getting-started tutorial. Not a hiring prediction. The certificate is a BayLearn course-completion certificate, not an industry certification.
Instructor: BayAreaLa8s Team. No individual instructor names. Prices are not printed here.
You will
- Answer 20 scenario questions
- Show weak categories to the instructor before the live session
How the assessment works5 min
How the assessment works
Module 0 — Readiness Assessment
Duration: 15 minutes · Kind: assessment
The assessment is not a gate and not a hiring prediction. It is a map. Twenty questions, nine skill scores, one band. Your instructor sees the weak categories before a live session so the four hours go to the gaps that will actually show up in Monday’s interview.
What it measures
| Skill | What a miss usually means in an interview |
|---|---|
| Python Fundamentals | You lecture types and then mutate a tuple’s inner list, or confuse is with == |
| Pythonic Coding | You cannot choose list vs dict vs set, or you leak a mutable default |
| Advanced Python | Generators, decorators, typing, and MRO become slogans |
| Async & Concurrency | “Python cannot do concurrency”; time.sleep in async def |
| FastAPI | You cannot place routes, deps, or lifespan; you treat Pydantic as optional comments |
| REST/API Design | 200-with-error, no pagination story, auth confused with authz |
| Data/Persistence | Session-per-app, N+1 on order + lines, no transaction boundary |
| Testing | “I would write tests” with no TestClient or fixture story |
| Production Readiness | Retry without jitter; secrets in logs; no readiness probe |
How to take it
Answer from current instinct. Do not open tabs. A padded 95% hides the module you should drill. When you finish, write down the two lowest bars before you open Module 1.
Bands (rehearsal only)
- Foundation (0–40) — rebuild types, structures, and one FastAPI path before the mock.
- Developing (41–60) — definitions are thin; drill spoken follow-ups and one lab path.
- Interview Capable (61–75) — you can sit a mid-level loop; they will still poke GIL and N+1.
- Interview Ready (76–90) — use the lab and mock to practice senior trade-offs, not definitions.
- Advanced (91–100) — we will interrupt you with dual-write and two-worker failure modes.
INTERVIEW TIP: After the score, pick one production sentence you cannot say yet: “
POST /ordersis idempotent because…” That sentence is what Module 4 is for.
Open how the assessment works, then the readiness lesson.
Readiness Assessment15 min
Readiness Assessment
Module 0 — Readiness Assessment
Duration: 15 minutes · Kind: assessment
The assessment is not a gate and not a hiring prediction. It is a map. Twenty questions, nine skill scores, one band. Your instructor sees the weak categories before a live session so the four hours go to the gaps that will actually show up in Monday’s interview.
What it measures
| Skill | What a miss usually means in an interview |
|---|---|
| Python Fundamentals | You lecture types and then mutate a tuple’s inner list, or confuse is with == |
| Pythonic Coding | You cannot choose list vs dict vs set, or you leak a mutable default |
| Advanced Python | Generators, decorators, typing, and MRO become slogans |
| Async & Concurrency | “Python cannot do concurrency”; time.sleep in async def |
| FastAPI | You cannot place routes, deps, or lifespan; you treat Pydantic as optional comments |
| REST/API Design | 200-with-error, no pagination story, auth confused with authz |
| Data/Persistence | Session-per-app, N+1 on order + lines, no transaction boundary |
| Testing | “I would write tests” with no TestClient or fixture story |
| Production Readiness | Retry without jitter; secrets in logs; no readiness probe |
How to take it
Answer from current instinct. Do not open tabs. A padded 95% hides the module you should drill. When you finish, write down the two lowest bars before you open Module 1.
Bands (rehearsal only)
- Foundation (0–40) — rebuild types, structures, and one FastAPI path before the mock.
- Developing (41–60) — definitions are thin; drill spoken follow-ups and one lab path.
- Interview Capable (61–75) — you can sit a mid-level loop; they will still poke GIL and N+1.
- Interview Ready (76–90) — use the lab and mock to practice senior trade-offs, not definitions.
- Advanced (91–100) — we will interrupt you with dual-write and two-worker failure modes.
INTERVIEW TIP: After the score, pick one production sentence you cannot say yet: “
POST /ordersis idempotent because…” That sentence is what Module 4 is for.
Open how the assessment works, then the readiness lesson.
20 scenario questions. Each card is tagged with the skill it scores. Open a card to read the prompt and the four choices.
- True True True True — Python interned every equal string, so == and is are interchangeable.
- True True True False — == is content equality. Literals s1 and s2 typically share an interned object; the computed s3 is a new object, so is is False.
- True False True False — two literals of the same text are never the same object.
- False False True False — == compares identity for str, so only s3 matches.
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
- Defend mutable-default and copy choices
- Pick the right collection under interview pressure
Core types and mutability12 min
Core types and mutability
Core types and mutability
In one sentence: Know what can change in place, never share a mutable default across requests, and use is only when you mean identity.
The built-in roster interviewers expect
| Type | Mutable? | Typical order-service use |
|---|---|---|
int | No | Quantity, version, status code |
float | No | Avoid for money. Use Decimal or integer cents. |
bool | No | Flags; remember bool is a subclass of int |
str | No | SKUs, customer ids, idempotency keys |
list | Yes | Line items you will append |
tuple | Spine no | Fixed pair (sku, qty) — see caveat |
dict | Yes | JSON-shaped payloads, indexes by id |
set | Yes | Membership: “have we seen this SKU?” |
frozenset | No | Hashable set of tags used as a map key |
None | N/A | Missing optional; singleton |
bytes / bytearray | No / Yes | Hashes vs buffers you mutate |
Decimal | No | Money. Still not a float underneath. |
float for currency is an interview smell. 0.1 + 0.2 is not 0.3. Say Decimal (or integer cents) and move on. If they push, mention rounding (ROUND_HALF_EVEN) and “I store cents as int when the ledger must be exact.”
See it — names, objects, mutation
Read the diagrams, then say: I rebind names for immutables. I mutate lists and dicts in place. A tuple is only as hashable as its children. I never put a tuple-of-list in a set of seen orders.
Mutable vs immutable
An immutable object cannot change its value after creation. Rebinding a name is not mutation: n = 1; n = 2 creates a new int. A mutable object can change in place: lines.append(item) mutates the same list other names still point at.
python
order_id = "ord-1"
alias = order_id
order_id = "ord-2" # rebind; alias still "ord-1"
lines = [{"sku": "A", "qty": 1}]
alias_lines = lines
alias_lines.append({"sku": "B", "qty": 2}) # lines now has two itemsPYTHON GOTCHA:
+=on a list mutates;+=on a tuple rebinds a new tuple.lines += [item]vspair += (item,)are different machines.
Interning and the small-int cache are CPython details. Mention them as a *warning* (“do not depend on is for numbers”). Do not treat them as trivia to show off.
The tuple caveat
“Tuples are immutable” is incomplete. The *container* cannot grow or shrink, but it can hold mutable children.
python
row = ("ord-1", ["A", "B"])
row[1].append("C") # legal. row is now ('ord-1', ['A', 'B', 'C'])
# hash(row) # TypeError — unhashable because of the listA tuple is a valid dict key only if every nested object is hashable. (sku, qty) of two ints is fine. (sku, [tags]) is not.
NamedTuple and dataclass(frozen=True) have the same rule: frozen spine, mutable payload if you put a list inside.
Identity vs equality
a == b→__eq__(value)a is b→ same object (sameid())
Use is for None (if order is None), sentinels, and “did I get the cached instance back?” Use == for numbers, strings, and domain values.
python
a = 256
b = 256
a is b # often True (interned) — do not depend on this
x = 257
y = 257
x == y # True
x is y # often False outside the same compilation unitCOMMON MISTAKE: Writing
if status is "PAID"because it worked once on interned literals. A status loaded from JSON is a differentstrobject.
Custom __eq__ without __hash__ (or with a hash that ignores equality fields) breaks sets and dict keys — same failure mode Java candidates hit on equals/hashCode.
If you write OrderId, hash and eq the same fields, and never mutate those fields after the object is used as a key.
python
class OrderId:
def __init__(self, value: str) -> None:
self.value = value
def __eq__(self, other: object) -> bool:
return isinstance(other, OrderId) and self.value == other.value
def __hash__(self) -> int:
return hash(self.value)PYTHON GOTCHA:
True == 1andhash(True) == hash(1).{True: "flag", 1: "one"}keeps one key. Do not useboolas a numeric key.
Mutable default arguments
python
def add_line(line, lines=[]): # created once, at def time
lines.append(line)
return lines
add_line({"sku": "A"})
add_line({"sku": "B"}) # [{"sku": "A"}, {"sku": "B"}]The default list is created once, when the function is defined, and reused. In a FastAPI worker that lives for hours, this is cross-request state.
python
def add_line(line, lines=None):
if lines is None:
lines = []
lines.append(line)
return linesSame bug appears on dict and set defaults, and on dataclass fields if you write lines: list = [] instead of field(default_factory=list).
PRODUCTION RISK: A mutable default on a helper used by a dependency can leak one customer’s lines into the next request on that worker.
Weak vs strong answer
Weak: “Lists are mutable, tuples are immutable.”
Strong: “I rebind names for immutables and mutate lists in place. A tuple of a list is a mutable payload and is unhashable. I never use a mutable default in a web worker — that list is process-wide.”
Weak: “Use is to compare strings, it’s faster.”
Strong: “is is identity. I use it for None. Value equality is ==. Interning can make is look right until JSON creates a new str.”
Whiteboard in 60 seconds
- Two columns: immutable vs mutable. Put
floatin “don’t use for money.” - Draw a tuple box holding a list; mark “unhashable / inner mutation.”
isvs==withNoneas the onlyisyou write by habit.def f(x, acc=None)— “default created once.”- Arrow: worker process lives for hours → leaked default list.
Follow-up ladder
- What is mutable? → table + tuple caveat.
- Why is
iswrong for status? → interned literal vs JSONstr. - Show the default-arg leak on a FastAPI worker. → one list, many requests.
boolas a dict key? →True == 1collapse.- How would you make
Moneysafe? → frozen dataclass /Decimal, nofloat.
Interview questions
What types are mutable?
list, dict, set, bytearray, most user objects. int/float/bool/str/tuple/frozenset/bytes/None are not (tuple caveat).
When is a tuple a bad dict key?
When it contains a mutable. Hashability is recursive.
Why is `if x is None` preferred to `==`?
None is a singleton; is cannot be overloaded by a sloppy __eq__. Value equality is the wrong question.
What happens with `def hook(events=[])` in a web process?
Every omitted-arg call shares one list. Request B sees request A’s events.
Follow-up: “bool is a subclass of int — so what?” True == 1, and True can sneak into a dict keyed by 1. Do not use bool as a numeric key.
INTERVIEW TIP: Open with “immutable means I rebind; mutable means other names see the change.” Then give the default-arg example. Then stop.
SENIOR-LEVEL EXPECTATION: Tie the leak to a worker process that is not restarted per request, and name the dataclass
default_factorycousin of the same bug.
Data structures and comprehensions12 min
Data structures and comprehensions
Data structures and comprehensions
In one sentence: Pick the structure for the operation you need next — membership, order, uniqueness, or a key — and say the cost.
Decision table
| Need | Reach for | Avoid |
|---|---|---|
| Sequence, duplicates OK, index | list | deque unless you pop left a lot |
| Fixed record, hashable if contents are | tuple / NamedTuple | tuple-of-lists as a key |
| Key → value | dict | parallel lists of ids and objects |
| Unique membership | set | if x in big_list on hot paths |
| Unique + hashable set-as-key | frozenset | set as a dict key |
| Insertion-ordered unique | dict keys or dict.fromkeys | relying on set order as an API |
| FIFO / sliding window | collections.deque | list.pop(0) |
| Counters / frequencies | collections.Counter | rolling your own off-by-one |
| Default nested maps | defaultdict | setdefault chains you cannot read |
| Bounded cache | OrderedDict / functools.lru_cache | unbounded dict of all SKUs |
| Heap / top-K | heapq | sorting a million rows for “top 5” |
See it
Read the diagrams, then say: I pick the structure from the next operation, not from “I always use lists.” Membership on a million SKUs is a set or a dict key. Hashability is the gate.
Hashability
A dict key or set member must be hashable: it implements __hash__ and __eq__, and the hash is stable while it lives in the container. Immutables of immutables are hashable. Lists, dicts, and sets are not.
python
seen = set()
seen.add(("sku-1", 2)) # OK
# seen.add(["sku-1", 2]) # TypeError
index = {("sku-1", 2): "line-9"}If you write a custom OrderId, implement __eq__ and __hash__ on the same fields. Mutating a key after insert orphans the entry — Python’s version of the Java equals/hashCode disaster.
Walk the lookup if they ask you to “open the dict”:
hash(key)- mask into a bucket
- compare with
==until you hit or miss - average O(1); worst-case degraded hashes exist — interviews want the average story
PYTHON GOTCHA:
hash(True) == hash(1)andTrue == 1, so{True: "flag", 1: "one"}collapses to one key.
Insertion order
Since Python 3.7, dict preserves insertion order as a language guarantee (3.6 CPython already did). set order is not an API. If the interviewer asks “which structure for insertion-order unique SKUs?”, say dict.fromkeys(skus) or a list-plus-set.
Do not say “dicts are unordered.” That answer aged out.
python
def unique_skus(lines: list[dict]) -> list[str]:
return list(dict.fromkeys(line["sku"] for line in lines))OrderedDict still matters for move_to_end (LRU). For “keep first-seen order,” dict is enough.
Complexity they will ask
| Operation | list | dict / set | deque |
|---|---|---|---|
| Index / key lookup | O(1) | O(1) average | O(n) middle |
Membership x in … | O(n) | O(1) average | O(n) |
| Append / insert key | O(1) amortized | O(1) average | O(1) either end |
| Pop last / delete key | O(1) | O(1) average | O(1) |
| Pop front | O(n) | n/a | O(1) |
Worst-case hash attacks exist; interviews want the average story plus “I would not use a list for membership on a million SKUs.”
Amortized list append: over-allocation. You do not need the growth factor. You need “occasional resize, still amortized O(1).”
Comprehensions
Prefer a comprehension when the result is a new collection and the body is an expression.
python
qtys = [line.qty for line in order.lines if line.qty > 0]
by_sku = {line.sku: line.qty for line in order.lines}
skus = {line.sku for line in order.lines}Generator expressions ((line.qty for line in lines)) do not build the list. Use them when you will iterate once (a large export, a stream).
Do not stuff side effects into a comprehension ([cache.set(x) for x in xs]). That is a loop pretending to be a comprehension.
Nested comprehensions are legal and often unreadable. Two lines beat a double-for in one pair of brackets.
python
pairs = []
for order in orders:
for line in order.lines:
pairs.append((order.id, line.sku))Walrus (:=) in a comprehension is legal and easy to overuse. If they cannot read it in two seconds, write a loop.
in, views, and copies
sku in mappingtests keys, not values.dict.keys()/.values()/.items()are views — they change if the dict changes. Iterating a view while mutating the dict raisesRuntimeError.list(d)copies keys.dict(d)is a shallow copy. Nested lists inside values are still aliased.
COMMON MISTAKE:
if line in orderswhenordersis a dict of id → order. You meantif line.order_id in orders.
Weak vs strong answer
Weak: “I use lists for everything, then convert.”
Strong: “Next operation is membership on SKUs → set. Next operation is id → order → dict. Next operation is first-seen unique → dict.fromkeys.”
Weak: “Dicts are unordered.”
Strong: “Insertion order is guaranteed since 3.7. Sets are not an ordered API.”
Whiteboard in 60 seconds
- Draw the decision table: sequence / key / membership / FIFO.
- Write
O(1)vsO(n)forin. - Hash path: key → hash → bucket →
==. dictinsertion order since 3.7;setis not ordered API.- One comprehension; one generator expression for a large export.
Follow-up ladder
- List vs set for SKU membership? → O(n) vs O(1).
- Why can’t a list be a key? → mutable, hash would change.
- Dedupe and keep first-seen? →
dict.fromkeys. Trueand1in the same dict? → collapse.- Sliding window of last N events? →
deque(maxlen=N), notlist.pop(0).
Interview questions
List vs tuple vs set vs dict — how do you choose?
Walk the table. Give an order-service example for each.
Why can’t a list be a dict key?
It is unhashable because it is mutable; the hash would change.
Is dict ordered?
Yes, insertion order, Python 3.7+. Do not rely on set order.
When is a comprehension the wrong tool?
Side effects, complex nesting, or you need break/except.
Follow-up: “How do you dedupe SKUs and keep first-seen order?” dict.fromkeys.
INTERVIEW TIP: Say the next operation first (“I need membership”), then the type, then the cost.
SENIOR-LEVEL EXPECTATION: Mention hashability, the
True/1collapse, and that mutating a live key orphans the bucket.
Functions, scope, and copying11 min
Functions, scope, and copying
Functions, scope, and copying
In one sentence: Name the contract, pass arguments explicitly, understand who can see a name, and copy only as deep as the aliasing risk.
Arguments
python
def create_order(customer_id: str, *lines, notify: bool = True, **meta) -> str:
...- Positional / keyword (the normal ones)
*lines— extra positionals as a tuple- Keyword-only after
*(here,notify) **meta— extra keywords as a dict/(positional-only) appears in stdlib (pow(base, exp, /)); mention it if they ask
Never hide required business data in **kwargs “for flexibility.” Interviewers hear “I will not name my contract.”
python
create_order("c-1", {"sku": "A", "qty": 1}, notify=False, source="web")COMMON MISTAKE:
def add(**kwargs)then readingkwargs["customer_id"]with no validation. That is how you ship a 500 instead of a 422.
*args and **kwargs are a tuple and a dict at the receiver. They do not validate. At a FastAPI boundary, a Pydantic model is the contract; **kwargs is an escape hatch for middleware you do not own.
LEGB
Python resolves names in Local → Enclosing → Global → Built-in.
python
TAX = Decimal("0.1") # global
def make_pricer(rate):
def price(amount): # enclosing: rate
return amount * (1 + rate)
return priceglobal x rebinds a module name. nonlocal x rebinds an enclosing name. You almost never need global in a FastAPI service. If you do, you are holding process-wide mutable state.
Unbound locals: assigning to a name anywhere in the function makes it local for the *whole* function.
python
count = 0
def bump():
print(count) # UnboundLocalError if you also assign below
count = count + 1Closures and the late-binding gotcha
Closures capture the variable, not the value at definition time.
python
handlers = []
for status in ("CREATED", "PAID", "SHIPPED"):
handlers.append(lambda: status) # all see SHIPPED
handlers = []
for status in ("CREATED", "PAID", "SHIPPED"):
handlers.append(lambda status=status: status) # bind nowSame bug with asyncio.create_task(call(url)) built in a loop if url is rebound. Bind with a default or pass the value into a helper.
PYTHON GOTCHA: Late binding is not a compiler bug. The cell still points at the loop name.
Lambdas
Lambdas are anonymous single-expression functions. Fine as a sort key. Not fine as a 12-line business rule.
python
lines.sort(key=lambda line: (line.sku, -line.qty))If you need statements, a def with a name you can log and test. A lambda that closes over a loop variable is the late-binding bug again.
copy.copy vs copy.deepcopy
- Assignment aliases: two names, one object.
- `copy.copy` — new outer container, same children (shallow).
- `copy.deepcopy` — recurse; new graph. Slow; can explode on cycles / ORM objects.
python
import copy
original = {"lines": [{"sku": "A", "qty": 1}]}
shallow = copy.copy(original)
shallow["lines"][0]["qty"] = 9 # original qty is now 9
deep = copy.deepcopy(original)
deep["lines"][0]["qty"] = 1 # original stays 9On an order service: shallow-copy a request dict before you stamp a server field, *or* build a new Pydantic model. Do not deepcopy a SQLAlchemy instance and expect a detached row you can commit.
A list-of-dicts copy that is usually enough:
python
clone = [dict(line) for line in lines] # new dicts, but nested objects still aliasPRODUCTION RISK: Deep-copying ORM graphs pulls lazy relations and turns a handler into an N+1 festival.
Exceptions
python
class OrderError(Exception):
"""Domain failure mapped to an HTTP error body."""
class InventoryConflict(OrderError):
pass
try:
reserve(sku, qty)
except InventoryConflict:
raise
except OrderError as exc:
log.warning("order_failed", extra={"err": type(exc).__name__})
raise
finally:
...Rules interviewers like:
- Catch specific types. Bare
except:swallowsKeyboardInterruptand bugs. except Exceptionis for a boundary (middleware) that must return JSON, not for a service core.- Raise domain errors; map them once to HTTP (Module 3).
raise(bare) preserves the traceback;raise eresets it.raise e from errchains.- Use exception groups /
except*only if they ask aboutasyncio.TaskGroup.
else on try runs when nothing was raised — useful when you want “success path” off the except indent.
contextlib.suppress is for expected, local cases — not for “ignore all DB errors.”
Weak vs strong answer
Weak: “Python is pass-by-reference.”
Strong: “Names bind to objects. Rebinding a name does not change other names. Mutating a mutable object does. That is why I do not say pass-by-value or pass-by-reference like C++.”
Weak: “I always deepcopy to be safe.”
Strong: “I copy as deep as the aliasing risk. Deepcopy on an ORM graph is an N+1 and a cycle risk. I build a new command model.”
Whiteboard in 60 seconds
- Signature: required,
*args, keyword-only,**kwargs. - LEGB boxes. Circle
nonlocalas rare. - Loop + lambda: bind with default.
- Shallow vs deep: one shared child arrow in red.
raisevsraise evsraise e from err.
Follow-up ladder
- What do
*args/**kwargsbind? → tuple and dict. - Why did every lambda print
SHIPPED? → late binding. - Show a shallow-copy bug on
lines. → shared child dict. - When is deepcopy wrong? → ORM, sockets, locks.
- How do you map
InventoryConflict? → one handler, 409, no traceback to the client.
Interview questions
**What do *args and **kwargs actually bind?**
A tuple and a dict. They do not magically validate.
Explain LEGB with a closure.
Inner price sees rate from enclosing; Decimal from built-in if you used that name badly.
Why did all my lambdas print the last status?
Late binding. Default-arg bind or a helper.
When is deepcopy wrong?
ORM objects, large graphs, anything with locks or sockets.
Follow-up: “How do you copy a list of line dicts so qty edits don’t alias?” [dict(line) for line in lines] or copy.deepcopy if nested deeper — say which and why.
INTERVIEW TIP: If they ask “pass by value or reference?”, say: names are bound to objects; objects may be mutable. The reference is not copied as a C++ reference; the object identity is.
SENIOR-LEVEL EXPECTATION: Refuse
globalcaches in a handler. Put shared clients onapp.statevia lifespan (Module 3).
You will
- Name when threads lose to processes
- Move blocking I/O off the event loop
Iterators, generators, decorators10 min
Iterators, generators, decorators
Iterators, generators, decorators, context managers
In one sentence: Stream work you cannot fit in memory, wrap functions without lying about their names, and close resources on every path.
Iterable vs iterator vs generator
- Iterable — has
__iter__that returns an iterator.list,dict, files, query results. - Iterator — has
__next__(and usually__iter__returningself). Exhausts. - Generator — a function with
yield; Python builds the iterator for you.
python
lines = ["A", "B"] # iterable
it = iter(lines) # iterator
next(it) # "A"
next(it) # "B"
# next(it) -> StopIterationA for loop calls iter then next until StopIteration. You rarely raise that yourself if you have yield.
You can iterate a list twice. An iterator is spent. That is why list(results) vs returning the iterator matters for a retry.
python
class SkuIter:
def __init__(self, skus: list[str]) -> None:
self._skus = skus
self._i = 0
def __iter__(self):
return self
def __next__(self) -> str:
if self._i >= len(self._skus):
raise StopIteration
sku = self._skus[self._i]
self._i += 1
return skuIn an interview, a generator is the version you would ship:
python
def iter_skus(skus: list[str]):
yield from skusyield and streaming files
python
def iter_order_rows(path: str):
with open(path, encoding="utf-8") as handle:
header = handle.readline()
for raw in handle:
yield raw.rstrip("\n").split(",")The function returns immediately. Work happens as the caller iterates. A 2 GB export does not become a 2 GB list.
yield from delegates to another iterable — useful for flattening pages.
python
def all_pages(client, url):
while url:
page = client.get(url)
yield from page["items"]
url = page.get("next")Generator send / yield expressions exist (coroutines of the pre-asyncio era). Mention them; do not implement a scheduler on the whiteboard.
finally in a generator runs when the generator is closed (GC, .close(), or finishing). A generator that holds a DB cursor must be consumed or closed or you leak a connection.
COMMON MISTAKE:
return [row for row in handle]inside a function namediter_…. You just loaded the file.
Decorators and functools.wraps
A decorator is a callable that takes a function and returns a callable.
python
import functools
import time
def timed(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
t0 = time.perf_counter()
try:
return fn(*args, **kwargs)
finally:
ms = (time.perf_counter() - t0) * 1000
log.info("timed", extra={"fn": fn.__name__, "ms": ms})
return wrapperWithout @wraps, wrapper.__name__ is "wrapper". Tracebacks, OpenAPI operation ids, and Depends diagnostics get worse.
Parametrized decorator: nest one more function (def timed(label): def deco(fn): ...).
On FastAPI you will also see decorator-style routers (@router.post). Those register routes; they are not a reason to invent a logging decorator that swallows exceptions.
Stacking: @auth then @timed — bottom decorator runs first on the way in. Say “I would print __wrapped__ if I needed the order,” not a memorized stack you cannot defend.
PYTHON GOTCHA: A decorator that does
return fn(*args)withoutwrapper(calling at decoration time) runs the handler at import. That can take the app down.
Context managers
with calls __enter__ / __exit__ (or the generator form).
python
from contextlib import contextmanager
@contextmanager
def session_scope(factory):
session = factory()
try:
yield session
session.commit()
except Exception:
session.rollback()
raise
finally:
session.close()Files, locks, sessions, and metric spans belong in with. FastAPI lifespan (Module 3) is the process-level version.
__exit__(self, exc_type, exc, tb) returning True swallows the exception. Do not.
ExitStack / AsyncExitStack when you open N resources in a loop. Mention if they ask about many temp files.
See it as a pipeline
Iterable source → generator transform → consumer (response stream or DB writer). Decorators wrap the consumer with cross-cutting timing. Context managers bracket the session.
FastAPI StreamingResponse is this idea over HTTP: yield chunks, do not Path.read_text() a 2 GB CSV.
Weak vs strong answer
Weak: “A generator is a function that returns many values.”
Strong: “It returns an iterator immediately. Each yield parks and hands one row. Memory stays flat. If it holds a cursor, I must close it.”
Weak: “Decorators add logging.”
Strong: “They wrap a callable. I use @wraps so OpenAPI still sees create_order. I do not swallow exceptions. I do not call the function at import.”
Whiteboard in 60 seconds
- Three boxes: iterable / iterator / generator.
yieldas “pause and hand a row.”@wrapsso__name__survives.with sessioncommit/rollback/close.- Arrow: unconsumed generator → leaked connection.
Follow-up ladder
- Is a list an iterator? → No. Iterable.
- Stream a 2 GB export? → generator / StreamingResponse.
- Why
@wraps? → name, docs, annotations, unwrap. - When is a decorator wrong? → request-scoped state that
Dependsalready gives you. - Generator + DB cursor? →
with/finally/.close().
Interview questions
Is a list an iterator?
No. It is iterable. iter(list) is the iterator. You can iterate a list twice; an iterator is spent.
Why generators for large files?
Constant memory; backpressure from the consumer.
What does `@wraps` preserve?
__name__, __doc__, __annotations__, and the unwrap chain.
When is a decorator the wrong abstraction?
When you need request-scoped state FastAPI already gives you via Depends.
Follow-up: “How do you stream a CSV response from FastAPI?” A generator (or StreamingResponse) yielding chunks — not Path.read_text().
INTERVIEW TIP: If they say “implement
range,” write a class with__iter__/__next__*or* a generator. Then say which you would ship.
SENIOR-LEVEL EXPECTATION: Mention that a generator holding a DB cursor must be consumed and closed — lifespan /
with/finally— or you leak connections.
Typing and object model8 min
Typing and object model
Typing, dataclasses, and the object model
In one sentence: Type hints are for humans and checkers; Pydantic is for runtime boundaries; know when a dataclass is enough and when you still need a class.
Type hints vs Pydantic
python
def total(qty: int, unit: Decimal) -> Decimal:
return qty * unitHints are not enforced at runtime by CPython. total("2", "3") still runs (and then blows up in arithmetic). Tools (mypy, pyright) and your IDE use them.
Pydantic does coerce and reject at runtime — that is why FastAPI request bodies feel “typed for real.”
| Tool | When | Runtime? |
|---|---|---|
| Annotations | Internal functions, editor help | No (unless you add a library) |
dataclasses | Simple in-process records | No validation unless you add it |
Pydantic BaseModel | HTTP, settings, JSON edges | Yes |
TypedDict | Untyped dicts you cannot upgrade yet | No |
NamedTuple | Tiny immutable records | No |
COMMON MISTAKE: “We use type hints, so we don’t need Pydantic.” A crafted JSON payload will still put a string in
qty.
from __future__ import annotations postpones evaluation (strings). Fine in 3.10+. Mention if they ask why a hint is a string at runtime (get_type_hints resolves it).
Python 3.10+ unions: str | None instead of Optional[str]. 3.12 generics: def first[T](xs: list[T]) -> T | None.
Dataclasses
python
from dataclasses import dataclass, field
from decimal import Decimal
@dataclass(frozen=True, slots=True)
class Money:
amount: Decimal
currency: str = "USD"
def plus(self, other: "Money") -> "Money":
if self.currency != other.currency:
raise ValueError("currency mismatch")
return Money(self.amount + other.amount, self.currency)frozen=True gives shallow immutability (hashable if fields are). slots=True (3.10+) saves memory and blocks surprise attributes.
field(default_factory=list) — never lines: list = [].
Do not use a dataclass as a SQLAlchemy mapped class unless you are on the 2.x mapped-dataclass path and you know it. Interview default: Pydantic at the edge, mapped classes in persistence, dataclasses for pure values (Money, Sku).
__post_init__ is for derived fields and invariants — not for talking to the database.
Protocol and Generic
python
from typing import Protocol, TypeVar
class PaymentPort(Protocol):
def capture(self, order_id: str, amount: Decimal) -> str: ...
T = TypeVar("T")
class Page(Generic[T]):
items: list[T]
next_cursor: str | NoneA Protocol is structural typing (“has capture”). You do not inherit a framework base just to fake a gateway in tests. A Generic is a container that keeps the inner type.
TypeVar bounds (TypeVar("M", bound=Money)) appear if they ask you to write max_by. Mention ParamSpec / Concatenate only if they point at a decorator’s types.
ABC + @abstractmethod is nominal: you must inherit. Use it when you own the hierarchy. Use Protocol when you want a test double without subclassing.
classmethod, staticmethod, property
python
class Order:
def __init__(self, id: str, status: str) -> None:
self.id = id
self._status = status
@classmethod
def from_row(cls, row: dict) -> "Order":
return cls(row["id"], row["status"])
@staticmethod
def is_terminal(status: str) -> bool:
return status in {"SHIPPED", "CANCELLED"}
@property
def status(self) -> str:
return self._status- instance method — needs
self - classmethod — alternative constructors;
clsso subclasses work - staticmethod — namespaced function; if it never uses
cls/self, ask whether it belongs on the class - property — attribute syntax with a getter; do not hide a query behind a property (that is how N+1 sneaks into templates)
@cached_property is per-instance memo. Fine for parsed headers. Dangerous if it caches a stale ORM relation.
MRO, conceptually
Python uses C3 linearization. Class.mro() is the search order for attributes.
text
class Service: ...
class Audited(Service): ...
class Idempotent(Service): ...
class OrderService(Audited, Idempotent): ...OrderService.mro() lists OrderService, Audited, Idempotent, Service, object (order can surprise people — C3 preserves local precedence).
You do not need to reproduce the algorithm. You need to say: diamond inheritance is why we prefer composition, and super() follows the MRO, not “my parent only.”
PYTHON GOTCHA:
super()in a mixin is not “call my superclass.” It is “call the next type in *this instance’s* MRO.”
See it
Read the diagrams, then say: Hints help the checker. Pydantic guards the HTTP edge. The ORM row is not the JSON contract. I compose a payment port instead of inheriting three mixins.
Weak vs strong answer
Weak: “Python is typed now.”
Strong: “Annotations are optional and not enforced at runtime. I still validate at the boundary with Pydantic. Internally I use dataclasses for Money and Protocols for ports.”
Weak: “I’ll make Order inherit Audited, Cached, and Logged.”
Strong: “I compose an auditor and a cache port. super() in a mixin follows the instance MRO, which I do not want to debug on a weekend.”
Whiteboard in 60 seconds
- Hints = static; Pydantic = runtime boundary.
- Frozen dataclass for
Money;default_factoryfor lists. - Protocol box for
PaymentPort. - MRO as a list, not a tree you invent on the fly.
- Three shapes: command / view / row.
Follow-up ladder
- Do hints enforce types? → No.
- Dataclass vs Pydantic vs ORM? → value / boundary / persistence.
- Show
Money.plusthat cannot mutateself. → frozen, return new. - Why Protocol? → test doubles without an ABC tax.
super()in a mixin? → next in *this* MRO.
Interview questions
Do type hints enforce types?
No. Checkers and optional runtimes do. FastAPI uses Pydantic at the edge.
Dataclass vs Pydantic vs ORM model?
Value / boundary / persistence. Do not leak the ORM to JSON.
What is a Protocol for?
Testing and swap-out without a rigid ABC, when structure is enough.
classmethod vs staticmethod?
from_row needs cls. is_terminal does not — and might be a module function.
Follow-up: “Show Money.plus that cannot mutate self.” Frozen dataclass returning a new instance.
INTERVIEW TIP: If they ask “is Python object-oriented?”, say yes — everything is an object — then talk composition and Protocols, not a zoo hierarchy.
SENIOR-LEVEL EXPECTATION: Refuse multiple inheritance for
OrderServicefeatures. Compose a gateway and an auditor.
GIL and concurrency10 min
GIL and concurrency
GIL, threading, and multiprocessing
In one sentence: The GIL serializes bytecode in one process — Python still does concurrency; you pick threads, processes, or asyncio based on wait vs compute.
What the GIL actually is
CPython’s Global Interpreter Lock is a mutex that lets only one thread execute Python bytecode at a time in a process. It simplifies memory management. That is not the same as “Python is single-threaded,” and it is not “Python cannot do concurrency.”
I/O operations (sockets, disk, most DB drivers) typically release the GIL while they wait. Two threads can wait on two payment HTTP calls at once. Two threads incrementing a pure-Python counter will take turns on the GIL and often run *slower* than one thread.
Some C extensions (selected NumPy work, parts of regex, compression) also release the GIL around tight C loops. Do not claim “all C code releases it.”
Free-threaded CPython (PEP 703, 3.13+ experimental) is a follow-up, not the default you design for this weekend. If they ask, say: “I design for today’s CPython GIL, and I still need locks for check-then-act.”
Read the diagram, then say: I/O-bound work can use threads or asyncio. CPU-bound work needs processes, a native extension that releases the GIL, or a worker queue. I never say Python cannot do concurrency.
Concurrency vs parallelism
- Concurrency — overlap waits. One core can juggle many sockets.
- Parallelism — two cores run bytecode at the same time. In CPython that means two processes (or native code that released the GIL).
Interviewers listen for this split. Mixing the words is a mid-level slip.
Threads — I/O
threading.Thread or concurrent.futures.ThreadPoolExecutor for blocking I/O you cannot easily await (a legacy SDK, a sync driver).
python
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch_rates(skus: list[str], client) -> dict[str, Decimal]:
out: dict[str, Decimal] = {}
with ThreadPoolExecutor(max_workers=8) as pool:
futs = {pool.submit(client.get_rate, sku): sku for sku in skus}
for fut in as_completed(futs):
out[futs[fut]] = fut.result()
return outShared mutable state still needs a Lock or a queue. The GIL is not a substitute for a lock on dict compound updates (check-then-act).
PYTHON GOTCHA:
list.appendis atomic in CPython practice;d[k] += 1is not a single bytecode. Name the race.
threading.Lock is per-process. Two uvicorn workers are two processes. An in-memory lock does not protect inventory.
Multiprocessing — CPU
multiprocessing / ProcessPoolExecutor / a separate worker service. Each process has its own interpreter and its own GIL. You pay: memory, pickle of arguments, no shared dict unless you use explicit IPC.
python
from concurrent.futures import ProcessPoolExecutor
def tax_pdfs(orders: list[Order]) -> list[bytes]:
with ProcessPoolExecutor() as pool:
return list(pool.map(render_tax_pdf, orders))Pickle must succeed. Lambdas and local functions often fail. SQLAlchemy sessions and sockets must not be pickled — recreate them in the child.
FastAPI / uvicorn workers (uvicorn --workers 4) are this idea at the process edge: N processes, N GILs, N connection pools.
fork vs spawn: macOS/Windows spawn; Linux fork can inherit connections you must not share. Recreate the engine in the child. pool_pre_ping is not a substitute for “do not inherit a live socket.”
Decision matrix
| Work | Tool | Why |
|---|---|---|
| Many HTTP/DB waits, async libs | asyncio | One thread, cooperative overlap |
| Many waits, sync SDK | threads | GIL released on I/O |
| CPU: PDF, image, crypto in Python | processes or queue | Bypass GIL |
| Shared counter in one process | threading.Lock / Queue | GIL ≠ correctness |
| Inventory decrement | SQL constraint / version | Not a Python lock |
| Use all cores for FastAPI | uvicorn workers + queue | One process ≠ one machine |
COMMON MISTAKE: “We’ll add threads to speed up JSON parsing of a huge body.” That is CPU. Threads will contend the GIL.
What you say about FastAPI
A typical uvicorn worker is one process, often one event loop (asyncio). Extra async def handlers do not use extra cores. Extra workers (processes) or extra machines do.
A CPU-heavy endpoint should offload (asyncio.to_thread for a bit of sync I/O, ProcessPoolExecutor or a broker for real CPU). Otherwise you stall every other request on that worker.
Do not invent a custom thread pool “because FastAPI is slow.” Measure first. Most slowness is N+1, sync I/O in async def, or a pool that is too small.
Pool math: 4 workers × pool_size=10 is 40 Postgres connections before overflow. Name it.
Weak vs strong answer
Weak: “Python can’t do concurrency because of the GIL.”
Strong: “The GIL serializes bytecode in one process. Concurrent I/O is routine. Parallel CPU needs processes or native code. Inventory still needs SQL.”
Weak: “I’ll lock a dict to reserve stock.”
Strong: “Two workers, two GILs, two dicts. I decrement with UPDATE … WHERE qty >= :n or a version column.”
Whiteboard in 60 seconds
- One box: process + GIL. One thread runs bytecode.
- Arrow out of GIL: “I/O wait.”
- Two process boxes: two GILs, two cores, two pools.
- Matrix: I/O / CPU / correctness (DB).
- Write
workers × pool_size.
Follow-up ladder
- What is the GIL? → bytecode mutex, not “no concurrency.”
- Can two threads wait on HTTP? → yes, GIL released.
- Speed up JSON parse with threads? → no, CPU.
- Four cores for FastAPI? → four workers + pool math.
- Reserve inventory? → SQL, not
threading.Lock.
Interview questions
What is the GIL?
A process-wide lock on bytecode execution in CPython. Not a language law — other implementations differ — but CPython is what they mean.
Can Python do concurrency?
Yes. Concurrent I/O is routine. Parallel CPU needs multiple processes or native code.
Threads vs processes vs asyncio?
Walk the matrix. Give checkout (asyncio), legacy SOAP client (threads), tax PDF (process/queue).
Does the GIL make my FastAPI app safe?
No. Races on check-then-act still exist. Two workers are two processes — an in-memory lock is worthless.
Follow-up: “How do you use four cores?” Four uvicorn workers *or* a pool, plus a pool-per-process for Postgres. Memory cost named.
INTERVIEW TIP: Lead with “the GIL does not mean no concurrency.” Then the matrix. Then stop.
SENIOR-LEVEL EXPECTATION: Separate *concurrency* (overlap waits) from *parallelism* (two cores at once) in one sentence, then name pool math across workers.
Asyncio and blocking work12 min
Asyncio and blocking work
Asyncio and blocking work
In one sentence: One thread, one event loop, cooperative tasks — await the I/O, never time.sleep the loop, and bound every fan-out with timeout and cancellation.
The event loop
asyncio runs tasks on an event loop. A task is a wrapper around a coroutine (async def). The coroutine yields control at await. While it waits on a socket, the loop runs other tasks.
python
async def fetch_payment(client, payment_id: str) -> dict:
return await client.get(f"/payments/{payment_id}")async def that never awaits is a sequential function that only looks async. def handlers in FastAPI run in a threadpool — that is a different machine. Mixing them carelessly is how you exhaust the pool.
Read the diagrams, then say: I overlap waits with await. I do not block the loop. I cancel work that missed its budget.
A coroutine object is not running until you await it or schedule it (create_task, gather, TaskGroup). Forgetting to await is a silent “coroutine was never awaited” warning and a missing side effect.
time.sleep vs asyncio.sleep
| Call | Effect on the loop |
|---|---|
await asyncio.sleep(2) | Parks this task; other requests run |
time.sleep(2) inside async def | Freezes the worker for two seconds |
time.sleep(2) inside def FastAPI route | Blocks a threadpool thread, not the loop — still a scarce resource |
This is the highest-yield asyncio interview question. Draw it.
CPU-bound or sync SDK: await asyncio.to_thread(sync_fn, *args) (3.9+) or a ProcessPoolExecutor via loop.run_in_executor. to_thread still uses a thread — good for I/O, not for burning cores.
COMMON MISTAKE:
requests.getinsideasync def. Use an async client (httpx.AsyncClient) orto_thread. Otherwise you blocked the loop.
gather, timeouts, cancellation
python
import asyncio
async def load_order_extras(order_id: str, payments, inventory):
try:
pay, inv = await asyncio.wait_for(
asyncio.gather(
payments.get(order_id),
inventory.get(order_id),
return_exceptions=False,
),
timeout=1.5,
)
except TimeoutError:
raise DownstreamTimeout("extras")
return pay, invasyncio.gather— run many; by default the first exception cancels siblings (3.11+TaskGroupis the structured version).return_exceptions=True— you must inspect results; forgotten exceptions die silently.asyncio.wait_for/asyncio.timeout(3.11+) — bound the budget.- Cancellation raises
CancelledError(aBaseException). Clean up infinallyortry/except CancelledError.
python
async def with_timeout(coro, seconds: float):
async with asyncio.timeout(seconds):
return await coroASYNC WARNING: A
gatherof 200 payment calls without a semaphore will open 200 sockets. Bound concurrency.
python
sem = asyncio.Semaphore(10)
async def bounded(call):
async with sem:
return await call()On cancel: close the HTTP connection, roll back the DB transaction, do not leave a half-captured payment. “I would check the client honors cancellation” is a senior sentence.
create_task in a request without keeping a reference can be GC’d. Prefer structured TaskGroup / gather you await before the response.
Offloading and FastAPI
- Prefer
async def+ async drivers (asyncpg, httpx) for I/O-heavy routes. - Keep
deffor truly sync libraries; FastAPI will run them in its threadpool. Do not then calldeffromasync defwithoutto_thread. - Lifespan: open a shared
httpx.AsyncClientand dispose it on shutdown. Do not create a client per request. - Background:
BackgroundTasksis in-process and dies with the worker. Real work goes to a queue (Module 4).
Calling asyncio.run inside a running loop (a FastAPI handler) raises. The server already owns the loop.
Mixing async def route + sync SQLAlchemy session.execute in the same handler blocks the loop unless you offload. Either use an async session or keep the route def.
Weak vs strong answer
Weak: “Async makes Python parallel.”
Strong: “Async overlaps waits on one thread. Parallel CPU still needs processes. time.sleep in async def freezes every request on that worker.”
Weak: “I’ll gather all the payment calls.”
Strong: “Gather with a semaphore and a timeout. On cancel I close the client and roll back. 200 unbounded sockets is an outage.”
Whiteboard in 60 seconds
- Loop + two tasks parked on I/O.
- Red X on
time.sleep/requests.get. gather+ timeout + semaphore.- Arrow “CPU → process pool / queue.”
CancelledErrorinfinally.
Follow-up ladder
- What does
awaitdo? → yield until done. - Why is
time.sleepa prod bug? → one thread, everyone waits. - Sync payment SDK? →
to_thread+ timeout + pool size. - Cancel a slow fan-out? → timeout scope; client must close.
gathervsTaskGroup? → structured cancellation, 3.11+.
Interview questions
What does `await` do?
Yield control until the awaitable finishes. The loop runs other tasks.
Why is `time.sleep` in `async def` a production bug?
It blocks the only thread the loop has. p99 for *everyone* on that worker gets worse.
How do you cancel a slow payment fan-out?
Timeout scope; ensure the client honors cancellation (close the socket).
`gather` vs `TaskGroup`?
TaskGroup (3.11) cancels siblings on failure and is structured. gather is older and easy to misuse with return_exceptions.
Follow-up: “The payment SDK is sync-only.” to_thread or a threadpool, *and* a timeout around it. Name the pool size.
INTERVIEW TIP: If you remember one line: “
await asyncio.sleep, nevertime.sleep, in an async handler.”
SENIOR-LEVEL EXPECTATION: Bound concurrency and name what happens to in-flight work on cancel (connection closed, DB transaction rolled back).
You will
- Explain why Depends is the default for I/O
- Separate request schemas from ORM models
FastAPI fundamentals14 min
FastAPI fundamentals
FastAPI fundamentals
In one sentence: FastAPI is an ASGI app — routes, parameters, middleware, and lifespan — served by uvicorn (or any ASGI server), not a magic thread-per-request framework.
App, router, route
python
from fastapi import APIRouter, FastAPI, status
app = FastAPI(title="Order Service")
router = APIRouter(prefix="/api/v1")
@router.post("/orders", status_code=status.HTTP_201_CREATED)
async def create_order(payload: OrderCreate) -> OrderRead:
...
app.include_router(router)Split routers by area (orders, health). Keep the app factory small so tests can build an app with a fake session.
Path operations are just functions. FastAPI inspects signatures for parameters and response models.
See it
Read the diagrams, then say: Middleware wraps every request. Depends wires per-request pieces. The route stays thin. The service owns the transaction. The response model is the contract.
Parameters
| Kind | How | Example |
|---|---|---|
| Path | {order_id} | /orders/{order_id} |
| Query | function arg | limit: int = 20 |
| Header | Header() | Idempotency-Key |
| Body | Pydantic model | payload: OrderCreate |
| Form / File | Form, UploadFile | rare on this sprint |
| Cookie | Cookie() | prefer tokens in Authorization |
python
from fastapi import Header, Path, Query
async def get_order(
order_id: str = Path(..., min_length=1),
include: str | None = Query(None),
x_correlation_id: str | None = Header(None, alias="X-Correlation-Id"),
) -> OrderRead:
...Do not stuff a JSON body into query strings. Do not read Request.json() manually when a model will do.
Identity in the path, filters in the query, command in the body. POST /orders?customerId= is a smell.
Middleware vs dependencies
Middleware wraps the whole app: CORS, correlation IDs, raw timing. It sees bytes and Request / Response.
Dependencies (Depends) wrap a route or router: auth, session, settings. They can yield (setup/teardown) and they show up in OpenAPI.
Use middleware for “every request gets a correlation id.” Use Depends for “this route needs a current user and a session.”
Starlette middleware order is last-added-first-run for the request. Say “I would verify with a log line,” not a stack you memorized and cannot defend.
Do not authenticate only in CORS. CORS is not a lock (Module 3 REST).
Lifespan
python
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.engine = make_engine(settings)
app.state.http = httpx.AsyncClient(timeout=2.0)
yield
await app.state.http.aclose()
await app.state.engine.dispose()
app = FastAPI(lifespan=lifespan)Startup/shutdown belong here — not at import time, not in a route. Deprecated @app.on_event("startup") still appears in old blogs; prefer lifespan.
Tests should call the factory so each test gets a clean engine. Import-time engine = create_engine(...) fights pytest.
PRODUCTION RISK: Creating an
httpx.AsyncClientor an engine per request. You will leak sockets and exhaust the DB.
ASGI and uvicorn (conceptually)
WSGI (Flask classic) is sync, one call at a time per worker. ASGI is async-aware: it can park a request and run another.
FastAPI is an ASGI application. uvicorn is a common ASGI server. Gunicorn can manage uvicorn workers. You do not need to configure a cloud load balancer on the whiteboard unless they ask.
text
Client → uvicorn (event loop) → FastAPI app → router → service
└── workers = processes = multiple loops / GILsuvicorn app:app --workers 2 is two processes. In-memory idempotency maps are then wrong. Each worker has its own pool — do the math (Module 4).
Health routes (GET /health) should not take the session lock. Readiness may check “engine can connect.”
Graceful shutdown: SIGTERM → stop taking work → finish in-flight (bounded) → dispose engine. A 30-second kill grace is an ops number. Do not treat it as a hope.
OpenAPI
FastAPI generates OpenAPI from signatures and models. That is a generated contract. You still version URLs (/api/v1), error codes, and idempotency by hand. Do not say “OpenAPI is the source of truth” if you change status codes in a handler the schema does not mention.
response_model filters fields. response_model_exclude_unset is a follow-up, not the opener.
Weak vs strong answer
Weak: “FastAPI is async Flask with types.”
Strong: “It is an ASGI app on Starlette + Pydantic. Middleware wraps the request. Depends injects the session. Lifespan owns the engine. Workers are processes.”
Weak: “I’ll put the session on a global.”
Strong: “Yielding dependency, close in finally. Tests override it. A global session is shared across requests and tasks.”
Whiteboard in 60 seconds
- Client → uvicorn → middleware → Depends → route → service.
- Path / query / header / body labeled on one
POST /orders. - Lifespan: engine + HTTP client in, dispose out.
- Workers = processes = N pools.
- OpenAPI generated; status codes owned by you.
Follow-up ladder
- What is FastAPI built on? → Starlette + Pydantic.
- Middleware vs Depends? → whole-app wrap vs request graph.
- Where does the session live? → yield dep, not global.
- Two workers and an in-memory key map? → broken idempotency.
- Why lifespan vs import-time engine? → tests + dispose.
Interview questions
What is FastAPI built on?
Starlette (ASGI, routing, middleware) + Pydantic (validation).
Path vs query vs body?
Identity in the path, filters in the query, command in the body.
Middleware vs Depends?
Cross-cutting vs request-scoped injection. Do not authenticate only in CORS.
Why lifespan?
Own long-lived resources. Survive tests that create many apps.
Follow-up: “Where do you put the SQLAlchemy session?” Yielding dependency, close in finally. Not a global.
INTERVIEW TIP: Draw CSR: router / service / repository. Entity never enters the router.
SENIOR-LEVEL EXPECTATION: Mention OpenAPI as a generated contract, then say you still version URLs and error codes by hand — and name worker × pool math.
Pydantic and dependency injection13 min
Pydantic and dependency injection
Pydantic and dependency injection
In one sentence: Validate at the edge with models, inject collaborators with Depends, and load settings from the environment — never from a committed secret file.
BaseModel and Field
python
from pydantic import BaseModel, Field, field_validator
from decimal import Decimal
class OrderLineIn(BaseModel):
sku: str = Field(min_length=1, max_length=64)
qty: int = Field(gt=0, le=100)
unit_price: Decimal = Field(gt=0)
@field_validator("sku")
@classmethod
def sku_upper(cls, value: str) -> str:
return value.strip().upper()
class OrderCreate(BaseModel):
customer_id: str
lines: list[OrderLineIn] = Field(min_length=1)
currency: str = "USD"Pydantic v2 is the sprint default (pydantic>=2.9). validator / .dict() / orm_mode are v1 names. Say field_validator, model_dump(), from_attributes=True.
Field carries constraints, aliases, and examples. Constraints belong on the model, not in a paragraph of if in the router.
model_config = ConfigDict(extra="forbid") rejects unknown fields — useful on commands so a client cannot sneak status="SHIPPED".
PYTHON GOTCHA:
qty: intwill coerce"2"from JSON. That is usually what you want at the HTTP edge. Internal functions should not rely on coercion.
Annotated[int, Field(gt=0)] is the 2.x style if they write it that way. Either is fine.
Request vs response
python
class OrderRead(BaseModel):
model_config = {"from_attributes": True}
id: str
status: str
total: Decimal
lines: list[OrderLineOut]
@router.post("/orders", response_model=OrderRead)
async def create_order(payload: OrderCreate) -> Order:
order = await service.create(payload)
return orderRequest models are commands: only what the client may send. Response models are views: only what you promise to emit. FastAPI uses response_model to filter fields — a safety net if you accidentally return an ORM object.
Never accept an internal status="SHIPPED" on create. Never return hashed passwords, tokens, or raw payment PANs.
Two models that look similar are cheaper than one model with fifteen optional fields and a guess.
Aliases (alias="customerId") if the public JSON is camelCase. Keep Python snake_case. populate_by_name=True if you accept both.
COMMON MISTAKE: One
Ordermodel for create, update, ORM, and JSON. You will leakversioninternals or acceptidfrom the client.
Depends
python
from fastapi import Depends
def get_settings() -> Settings:
return Settings()
def get_session(settings: Settings = Depends(get_settings)):
session = Session(make_engine(settings))
try:
yield session
finally:
session.close()
def get_service(session=Depends(get_session), settings=Depends(get_settings)) -> OrderService:
return OrderService(session, settings)
@router.post("/orders")
async def create_order(
payload: OrderCreate,
service: OrderService = Depends(get_service),
):
return service.create(payload)Depends is the constructor injection of this stack. Tests override get_session / get_settings with app.dependency_overrides.
yield dependencies are context managers. Do not swallow exceptions in them. After the route returns, the generator resumes — that is when you close.
Depends(get_settings) vs a global: the global is harder to override and hides the graph. A cached @lru_cache on get_settings is fine if settings are process-immutable.
Sub-dependencies cache per request by default (same get_session called twice is one session). Say this if they ask why you did not pass the session around by hand.
Settings
python
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
database_url: str = "sqlite:///./order_service.db"
log_level: str = "INFO".env is local. Commit .env.example with no secrets. Production injects environment variables. Never hard-code passwords, API keys, or account ids in the repo.
Cloud-neutral: database_url is a URL, not “RDS endpoint.”
SecretStr for tokens so repr(settings) does not dump them into logs.
Weak vs strong answer
Weak: “Pydantic is just dataclasses with types.”
Strong: “It is runtime validation at the boundary. Hints do not reject JSON. I keep command, view, and row as three shapes.”
Weak: “I’ll new OrderService() in the router.”
Strong: “Depends builds the graph. Tests override the session. Yield closes the connection on every path.”
Whiteboard in 60 seconds
OrderCreatevsOrderReadvs mappedOrder.Field(gt=0)on qty;extra="forbid"on commands.- Depends graph: settings → session → service → route.
- Settings from env;
.env.exampleonly. dependency_overridesin pytest.
Follow-up ladder
- Why Pydantic if we have hints? → runtime at the edge.
- v1 vs v2 names? →
model_dump,field_validator,from_attributes. - Client sent
qty: 0? → 422 before the service. - How do you test without Postgres? → override
get_session. - Where do secrets live? → env / secret manager,
SecretStr, never git.
Interview questions
Why Pydantic if we have type hints?
Runtime validation and coercion at the boundary. Hints do not reject JSON.
v1 vs v2 names?
model_dump, model_validate, field_validator, from_attributes.
How do you test a route without Postgres?
Override get_session / get_service. TestClient against the app factory.
Where do secrets live?
Environment or a secret manager. Not in git. Not in logs.
Follow-up: “Client sent qty: 0.” 422 from Pydantic before the service runs.
INTERVIEW TIP: Say “three shapes: command, view, row.” That usually settles the room.
SENIOR-LEVEL EXPECTATION: Settings as a dependency, not
os.environ["…"]sprinkled in the service — andextra="forbid"on commands so clients cannot setstatus.
REST, errors, auth13 min
REST, errors, auth
REST, errors, auth
In one sentence: Status codes and a stable error JSON are the contract; pagination and idempotency keep it scalable; authn is not authz; CORS is not a lock.
Status codes you must own
| Code | When on an order API |
|---|---|
| 200 | Read or update that returns a body |
| 201 | Create; include Location |
| 204 | Delete / empty success (if you choose) |
| 400 | Malformed / missing required header (Idempotency-Key) |
| 401 | Missing or invalid credentials |
| 403 | Authenticated but not allowed |
| 404 | Order id does not exist (do not leak others’ ids if that is policy) |
| 409 | Idempotency key reused with a different body; optimistic lock; conflict |
| 422 | Validation (Pydantic) |
| 429 | Rate limit |
| 500 | Bug — you log it; you do not dump a traceback to the client |
| 503 | Not ready / dependency down |
Replayed idempotent create: return the original status and body (often 201). Not a second insert. Not a 200 that changes the contract unless you documented it.
COMMON MISTAKE:
200 {"error": "..."}. Clients and gateways will not retry or trip breakers correctly.
Location: /api/v1/orders/{id} on 201. ETags / If-Match are the HTTP cousin of your version column. Mention if they ask about concurrency without saying “optimistic lock.”
Error contract JSON
Pick one shape and keep it.
json
{
"error": {
"code": "IDEMPOTENCY_KEY_CONFLICT",
"message": "Idempotency-Key was reused with a different body",
"details": [{"field": "Idempotency-Key", "issue": "payload hash mismatch"}],
"correlationId": "demo-1"
}
}Map domain exceptions in one handler. Validation errors should look like the same envelope with a VALIDATION_ERROR code. Do not invent a new key per endpoint.
RFC 7807 (application/problem+json) is a valid alternative. They care that the shape is stable, not which brand name you pick.
Never return SQL text, stack traces, or internal table names.
Pagination
Offset (?page=5000&size=20) is simple and degrades on large tables. Keyset / cursor (?after=ord_…) is the production default for “list my orders.”
Return items + next_cursor (or null). Do not return unbounded arrays from GET /orders.
Stable sort: (created_at, id). A sort on created_at alone duplicates or skips rows when timestamps collide.
Cap limit (default 20, max 100). A client passing limit=1000000 is a self-inflicted outage.
Idempotency
POST /orders is not idempotent by HTTP definition. You make it idempotent with a key:
- Client sends
Idempotency-Key(orclient_order_id). - You store key + payload hash + response in the same transaction as the order.
- Replay same hash → stored response.
- Replay different hash → 409.
GET / PUT / DELETE should already be safe or idempotent; still protect payments you forward.
Read the diagram, then say: The unique constraint is the correctness mechanism. The service method is the story that uses it.
Canonicalize JSON before hashing (separators, sorted keys) or semantically equal bodies hash differently and you 409 honest retries.
Key TTL: store long enough to cover client retries (24h is a common story). Do not keep them forever without a plan.
Auth vs authz vs CORS
- Authentication — who is this? Token, session, mTLS. Result: a principal.
- Authorization — what may they do?
customer_idmatches, role isagent, scope includesorders:write. - CORS — a browser policy. It does not stop curl, server-to-server calls, or a stolen token.
A valid JWT that can cancel *any* order is an authz bug. CORS did not cause it.
Say “I verify the token in a dependency, then I check ownership in the service.” Do not implement OAuth on the whiteboard unless they ask — name the seam.
Access-Control-Allow-Origin: * plus cookies is a footgun. For a public JSON API with bearer tokens, be explicit about origins and methods.
PRODUCTION RISK: Treating CORS as “our security layer” in a design interview.
Weak vs strong answer
Weak: “I return 200 and put errors in the body.”
Strong: “Status is the machine contract. 409 for key/body mismatch. 422 for Pydantic. One error envelope with code and correlationId.”
Weak: “We use CORS so it’s secure.”
Strong: “CORS is a browser relaxation. Authn is who. Authz is whether Alice may cancel Bob’s order.”
Whiteboard in 60 seconds
- Table: 201 / 401 / 403 / 409 / 422.
- Error envelope with
code+correlationId. - Cursor pagination on
(created_at, id). - Authn vs authz vs CORS as three separate circles.
- Idempotency: same TX, unique key, hash, 409.
Follow-up ladder
- 201 vs 200 on create? → 201 + Location; replay may repeat 201.
- Same key, different body? → 409.
- Paginate all orders? → keyset, stable sort.
- Authn vs authz? → who vs what.
- PUT vs PATCH for status? → replace vs command; version both.
Interview questions
201 vs 200 on create?
201 + Location on first create. Replay may repeat 201 with the same body.
How do you paginate “all orders”?
Keyset on (created_at, id). Admit offset for admin UIs with small tables.
Authn vs authz?
Who vs what. Example: Alice cannot cancel Bob’s order.
Is CORS enough?
No. It is a browser relaxation.
Follow-up: “PUT vs PATCH for status.” PUT replaces the resource; PATCH is a command ({status, version}). Either is fine if you are consistent and versioned.
INTERVIEW TIP: Memorize 409 for “same key, different body.” That one sentence reads senior.
SENIOR-LEVEL EXPECTATION: Mention rate limiting and abuse on create, canonical JSON hashing, and that an in-memory key map dies across workers.
You will
- Design POST /orders with an Idempotency-Key
- Investigate slowness with logs, metrics, and traces
SQLAlchemy and transactions12 min
SQLAlchemy and transactions
SQLAlchemy, transactions, and N+1
In one sentence: The engine is the pool; the session is the unit of work; SQLAlchemy 2.x select is the style; N+1 and expand/contract are the seniority tests.
Engine and session
python
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
engine = create_engine(settings.database_url, pool_size=5, max_overflow=10, pool_pre_ping=True)
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False, autoflush=False)- Engine — dialect + connection pool. One per process. Created in lifespan. Disposed on shutdown.
- Session — identity map + transaction. One per request (or per job). Close always.
- Do not create an engine per request. Do not share a session across tasks or processes.
pool_pre_ping drops dead connections. Size the pool per worker: 4 workers × pool_size=10 is 40 connections before overflow.
Read the diagrams, then say: The router does not commit. The service starts the unit of work, writes the order and the idempotency row, commits once. Pool math is workers × (pool_size + overflow).
SQLAlchemy 2.x
Prefer 2.x style (sprint: sqlalchemy>=2.0.36,<2.1):
python
from sqlalchemy import select
from sqlalchemy.orm import selectinload
stmt = (
select(Order)
.where(Order.customer_id == customer_id)
.options(selectinload(Order.lines))
.order_by(Order.created_at.desc(), Order.id)
.limit(20)
)
orders = session.scalars(stmt).all()Legacy session.query(Order).filter(...) still works and still appears in blogs. In an interview, write select. Use Mapped[] annotations on models.
expire_on_commit=False is handy for returning attributes after commit; know that you can see stale data if another transaction changed the row.
autoflush=False means you control when pending INSERTs become visible to later SELECTs in the same session. Default autoflush can surprise you in a uniqueness check.
Identity map: two get(Order, id) in one session return the same Python object. That is a feature until you expected a refresh.
Transactions
python
def create(self, cmd: OrderCreate, key: str) -> Order:
with self.session.begin():
self._reserve_key(key, cmd)
order = self._insert(cmd)
self._store_response(key, order)
self.events.publish_after_commit(OrderCreated(order.id))
return ordersession.begin() commits on success and rolls back on error. Nested begin_nested() is a SAVEPOINT — rare on this sprint.
What rolls back: the SQL you flushed in that transaction. What does not: an HTTP call you already made to a payment provider. That is why you do not capture a card inside the same try and hope the rollback covers it. You need an idempotency story on the provider.
Read-your-writes: after flush, later queries in the same session see the new row. After commit, another session needs its own query.
PRODUCTION RISK: Calling
commit()in the router *and* in the service. You will commit half-graphs or hide the boundary.
Isolation (if they push)
Default Postgres is READ COMMITTED. Phantom reads and write skew exist. Inventory “read qty then update” is not safe under READ COMMITTED without UPDATE … WHERE qty >= :n or SELECT … FOR UPDATE.
You do not need to lecture on SERIALIZABLE unless they ask. Say: “I would not check-then-act in Python. I would make the write conditional.”
Pooling
Defaults are fine for a demo and wrong for production. Talk:
pool_size/max_overflow/pool_timeoutpool_pre_ping=True- NullPool for SQLite tests if you must
- One engine per process (uvicorn workers)
A “connection leak” is usually a session you did not close, or a generator that never finished.
SQLite + check_same_thread=False is a test convenience. Prod is Postgres + one engine per process.
N+1
python
orders = session.scalars(select(Order)).all()
for order in orders:
_ = order.lines # one extra SELECT per order ← N+1Fix with selectinload / joinedload (mind row multiplication) / an explicit join + distinct. lazy="raised" on relationships makes the bug loud in tests.
noload + a second query you own is acceptable. Silent lazy I/O in a serializer is not.
joinedload on a collection can explode into a cartesian product. selectinload is the default sentence for “list orders with lines.”
Count queries in a test (assert query_count == 2). echo=True is for local debugging, not prod.
Optimistic locking
sql
UPDATE orders SET status = 'CANCELLED', version = version + 1
WHERE id = :id AND version = :seenZero rows → 409. A Python Lock is worthless across workers.
Alembic expand / contract
Never ALTER … RENAME a live column in one deploy if old and new app versions overlap.
- Expand — add the new column / table, backfill, dual-write if needed.
- Deploy app that reads new, still writes both.
- Contract — stop writing old, then drop.
Destructive down migrations on prod are a story you tell, not a reflex. Expand/contract is the interview phrase.
SQLite in LAB-PF-501 is fine for tests. Mention Postgres types (UUID, JSONB) when they ask “what changes in prod?”
Weak vs strong answer
Weak: “I call commit in the router after the service returns.”
Strong: “The service owns begin(). Order + key + outbox commit together. The router maps exceptions to HTTP.”
Weak: “I’ll add Redis so the DB is faster.”
Strong: “First I kill N+1 with selectinload and I size the pool. Cache is for stale-OK reads.”
Whiteboard in 60 seconds
- Engine (pool) vs session (UoW).
- One
begin()around order + idempotency. - Red N+1 arrows; green
selectinload. - Expand then contract.
UPDATE … WHERE version = :seen.
Follow-up ladder
- Engine vs session? → pool vs unit of work.
- Write a 2.x query? →
select+scalars. - How do you see N+1? → query count,
lazy="raised". - Two workers, last unit? → conditional UPDATE, not a Lock.
- Rename a column live? → expand / dual-write / contract.
Interview questions
Engine vs session?
Pool vs unit of work. Lifecycle: process vs request.
How do you write a 2.x query?
select(Model).where(...).options(...) + session.scalars.
How do you see N+1?
Query count in a test, echo=True in dev, APM spans, lazy="raised".
Where is the transaction boundary on POST /orders?
Service method. Key + order + lines in one commit.
Follow-up: “Two workers reserved the last unit.” Optimistic version or UPDATE … WHERE qty >= :n. Not a Python Lock.
INTERVIEW TIP: If you only remember one loader, remember
selectinloadfor collections.
SENIOR-LEVEL EXPECTATION: Name pool math across workers, isolation for check-then-act, and the expand/contract sequence for a rename.
Caching, idempotency, outbox12 min
Caching, idempotency, outbox
Caching, outbox, and background work
In one sentence: Cache is a performance copy, the database is the truth; dual writes need an outbox; queues absorb spikes and demand idempotent consumers.
Cache-aside
text
read: cache.get(key) → hit return
miss → DB → cache.set(key, value, ttl) → return
write: DB commit → cache.delete(key) # or short TTL and accept staleRead the diagrams, then say: I do not treat the cache as a source of truth. I invalidate on write. I accept a stale read window or I pay for a tighter protocol. A stampede can make p99 worse after you “added Redis.”
Use cache-aside for read-heavy, tolerance-for-stale data: product catalog, public SKU names, feature flags. Do not cache “available qty” as the reservation authority.
Stampede: many misses at once. Mitigate with single-flight (lock on key), slightly jittered TTLs, or a stale-while-revalidate story.
Write-through / write-behind: mention as alternatives. Write-through couples write latency to the cache. Write-behind can lose writes. Aside is the default sentence.
COMMON MISTAKE: Caching the entire
Orderaggregate including payment state with a 10-minute TTL. You will ship a paid order asCREATED.
Redis use cases (examples, not a vendor quiz)
Cloud-neutral first: “a cache” / “a key-value store.” Redis is the common example.
| Use | Why Redis-shaped |
|---|---|
| Cache-aside | Fast get/set/ttl |
| Rate limiting | INCR + EXPIRE |
| Idempotency *cache* | Optional; DB unique key remains the source of truth |
| Session store | If you must have server sessions |
| Leader / lock | Short locks; know they expire |
Redis down: the app should still read from Postgres (degraded), not 500 the catalog. Circuit or fail-open on cache, fail-closed on payments.
Do not store PANs or raw tokens in Redis “because it is fast.”
One Redis box doing cache + broker + session + lock is a coupling story. Name the jobs; split them if they fail differently.
Transactional outbox
After-commit listeners (BackgroundTasks, in-process signals) can lose the event if the process dies after commit. Dual-write to “DB + broker” without a protocol loses one side.
text
same transaction:
insert orders
insert outbox(payload, dest)
commit
worker: read unpublished → publish → mark sent
consumer: idempotent on event idInbox / dedupe table on the consumer for at-least-once delivery. At-most-once loses money events. Exactly-once is a marketing phrase — you build effectively once with idempotency.
LAB-PF-501 may use an after-commit in-process event. The upgrade sentence is outbox.
Publish-before-commit: the consumer creates side effects for a rolled-back order. That is the dual-write failure mode they want named.
PRODUCTION RISK: Publishing to the broker *before* commit. The consumer will create side effects for a rolled-back order.
Queues and workers
Use a queue when:
- The HTTP budget cannot wait (email, PDF, webhooks)
- You need retries and a dead-letter
- You want to scale workers independently of the API
Celery (or Dramatiq, RQ) — Python workers, broker in the middle (Redis/Rabbit). SQS (or any cloud queue) — same idea, managed broker. Name them as examples. The interview wants: producer, broker, consumer, retry, DLQ, idempotent handler.
text
API --(commit)--> outbox --> publisher --> broker --> worker --> inboxBackgroundTasks is not a queue. It is “run this after the response is sent, in this process.” Fine for metrics; not fine for “charge the card.”
Poison messages: retry with backoff, then DLQ, then a human. Infinite retry is how you overload Postgres overnight.
Weak vs strong answer
Weak: “We’ll add Redis for speed.”
Strong: “What is allowed to be stale? Catalog yes. Available qty no. Cache-aside, invalidate on write, fail-open on cache.”
Weak: “I’ll publish to Kafka in the service after insert.”
Strong: “Same transaction as an outbox row. Publisher drains after commit. Consumer is idempotent on event id.”
Whiteboard in 60 seconds
- Cache-aside arrows; DB as truth.
- Invalidate on write; name stale window + stampede.
- Outbox in the same commit.
- Worker + DLQ + idempotent consumer.
- Fail-open cache / fail-closed payments.
Follow-up ladder
- When do you cache? → read-heavy, stale-OK.
- Cache-aside vs write-through? → aside default.
- Why outbox? → atomic write + intent to publish.
- Worker saw the event twice? → inbox / idempotent capture.
- Redis down? → degrade catalog; do not degrade charge.
Interview questions
When do you cache?
Read-heavy, stale-OK. Never as inventory truth.
Cache-aside vs write-through?
Aside is the default. Write-through couples write latency to the cache.
Why outbox?
Atomic “business write + intent to publish.” Crash-safe.
Celery vs a cloud queue?
Same pattern. Choice is ops: language workers vs managed broker. Cloud-neutral first.
Follow-up: “Worker processed the event twice.” Inbox key / idempotent capture / unique event id.
INTERVIEW TIP: If they say “just add Redis,” ask “what is allowed to be stale?”
SENIOR-LEVEL EXPECTATION: Separate cache, session store, broker, and source of truth. One Redis box doing all four is a coupling story, not a win.
Testing and production11 min
Testing and production
Production FastAPI: logs, retries, health, containers
In one sentence: Log without secrets, correlate every hop, retry with jitter only when it is safe, and split liveness from readiness.
Logging — no secrets
Structured logs (JSON) with a small field set: timestamp, level, message, correlation_id, order_id, customer_id (if policy allows), duration_ms, error_code.
Never log:
Authorization/ cookies / raw tokens- Card PAN, CVV, passwords, session secrets
- Full request bodies that may contain PII you have not reviewed
- Idempotency keys if they are secrets; a hash is safer
python
log.info(
"order_accepted",
extra={"order_id": order.id, "correlation_id": cid, "line_count": len(order.lines)},
)print is not how you observe a service. logger.exception belongs in the boundary, not in every helper.
Redact at middleware if you must log headers. Default to not logging them.
PRODUCTION RISK: Debug-level request dumps left on in production. That is how tokens land in the log store.
Correlation IDs, metrics, traces
- Correlation / request id — accept
X-Correlation-Idor generate one; put it on logs, responses, and outbound calls. - Metrics — RED (rate, errors, duration) on
POST /orders; saturation on pool and queue depth. - Traces — one span per request; child spans for DB and HTTP. Sampling in prod.
Read the diagram, then say: I can answer “what happened to checkout-42?” with a single id across API, worker, and payment client.
You do not need to name a specific APM vendor. Cloud-neutral: “metrics backend,” “log store,” “trace collector.”
SLIs for this API: success rate on POST /orders, p99 latency, idempotent-replay ratio, 409 rate, pool wait time.
Retries with jitter
Retry only idempotent or explicitly safe calls. A bare retry on POST /charge double-captures.
text
attempt k: delay = min(cap, base * 2^k) ± jitter- Jitter stops thundering herds after an outage.
- Cap the attempts and the total budget (align with the caller’s timeout).
- Retry 408/429/502/503, not 400/401/403/404/422.
- 409 on idempotency conflict is not “retry with a new key.”
Circuit breaker: stop calling a dead dependency so you fail fast and shed load. Half-open probe. Name it; do not implement Resilience4j-in-Python from memory unless they ask.
Bulkhead: a dedicated thread/semaphore for payments so a stuck PSP does not starve GET /health.
Health vs readiness
| Probe | Question | Fail means |
|---|---|---|
Liveness /health | Is the process alive? | Restart the container |
Readiness /ready | Can I take traffic? | Stop sending requests |
/health should be cheap — no DB if a DB blip would kill-loop the process. /ready may check engine connect + “migrations applied.”
Do not require a cache hit for readiness unless the cache is truly mandatory.
Containers, conceptually
text
image (non-root) → process (uvicorn) → probes on /health /ready
config via env → no secrets in the image
one process per container (workers are still processes)Mention: non-root user, read-only FS where possible, resource limits, graceful shutdown (SIGTERM → finish in-flight → dispose engine). Dockerfile in LAB-PF-501 is the exhibit. You do not need Kubernetes objects on the board unless they ask.
Horizontal scale: stateless app. Sticky sessions are a smell. Files on local disk are a smell. Uploads go to object storage.
Multi-stage image: build wheels in one stage, slim runtime in the next. Do not copy .env into the image.
Testing in production-shaped code
pytest + httpx.ASGITransport / FastAPI TestClient. Fixture for the app factory and an SQLite engine. Assert statuses and error codes, not only 200.
Talk about: contract tests on the error envelope, a replay test for the idempotency key, a query-count test for list-orders.
BayLearn will not run your tests. You run them locally.
Weak vs strong answer
Weak: “We have logs and monitoring.”
Strong: “JSON logs with a correlation id, no secrets. RED metrics on POST /orders. Traces for DB and HTTP. I can pull checkout-42 in one query.”
Weak: “Retry three times.”
Strong: “Retry 502/503 with jitter, cap the budget, never retry charge without the same idempotency key. Circuit open if the PSP is dead.”
Whiteboard in 60 seconds
- Log line with
correlation_id, no token. - Retry curve + jitter; “idempotent only.”
/healthvs/ready.- Container: env config, non-root, graceful shutdown.
- Stateless: no local disk, no sticky sessions.
Follow-up ladder
- What do you log on POST /orders? → ids, duration, not bodies.
- Why jitter? → desynchronize retries.
- Health vs ready? → restart vs drain.
- SIGTERM mid-request? → finish or 503; dispose pool.
- How do you configure prod? → env / secret manager; no secrets in the image.
Interview questions
What do you log on `POST /orders`?
Accept/reject, ids, duration. Never the raw key header if it is sensitive — the *hash* maybe.
Why jitter?
Desynchronize retries after a shared outage.
Health vs readiness?
Alive vs safe to receive traffic.
How do you configure prod?
Env / secret manager. .env.example in git. No passwords in images.
Follow-up: “Worker received SIGTERM mid-request.” Finish or return 503; do not start new work; flush logs; dispose the pool.
INTERVIEW TIP: The phrase “retry with jitter, only if idempotent” is a complete mid-level answer. Add budget and status-code filter to go senior.
SENIOR-LEVEL EXPECTATION: Tie probes to orchestration behavior (restart vs drain) without requiring a specific cloud, and name a bulkhead so a stuck PSP does not starve health checks.
Download the full lab (all code)
FastAPI + Pydantic v2 + SQLAlchemy 2.x Order Service: schemas, idempotent create, optimistic locking, outbox, and pytest. Unzip, run pytest locally. BayLearn does not execute candidate code.
Download pf-order-api-lab.zipYou will
- Download pf-order-api-lab.zip or read the source in this lesson
- Run pytest locally — BayLearn does not execute your code
Lab 501 — Order Service overview10 min
Lab 501 — Order Service overview
Module 5 — Live Coding + FastAPI Order Service
Duration: 35 minutes · Kind: lab
This module is the write-and-scale hour. You write interview-sized Python, then run LAB-PF-501 on your machine. BayLearn does not compile or execute your code. If pytest is green locally, you cleared the mechanical bar.
Live coding (first 15 minutes)
Expect a prompt in the shape of the challenge bank:
- Frequency counter or dedupe preserving order
- Idempotency handler for
POST /orders - Async timeout / bounded concurrency
- Retry with jitter
Talk while you type. Name the contract. Write the sad path first if it is cheap, then the happy path. Do not invent a framework.
Order Service lab (20 minutes)
The lab lives in labs/order-service/ (LAB-PF-501). You build a production-style slice:
- Router + request/response Pydantic models (not ORM rows)
- Validation and a consistent error body
- SQLAlchemy 2.x order + lines, optimistic locking on the order version
- Idempotent create (
Idempotency-Keyheader) - One event after the transaction (
OrderCreated) - Structured logging with a correlation ID
- Tests you can run with pytest against SQLite
SQLite is enough for the sprint. A compose file may offer managed-Postgres-shaped config. You do not need Redis, a broker, or a cloud account to finish.
What interviewers watch
| They watch | They punish |
|---|---|
| Pydantic at the HTTP edge | ORM model in the request body |
| Service owns the session | Global session, commit in the router |
| Idempotent create | Two rows for one retry |
| Version / constraint on status | Blind last-write-wins |
Log order_id + correlation_id | Secrets, tokens, or print as product |
How to demo
pytestinlabs/order-service/- Show the idempotency test: same key, one order
- Show conflict when the key is reused with a different body
- Point at event publication after commit (or outbox table)
Open the lab lesson. Then interview follow-ups. Keep downloads/coding-challenges.md beside you.
COMMON MISTAKE: Spending the whole 35 minutes on package structure. Interviewers would rather see one correct POST and a test than empty hexagonal folders.
Lab pack README
Lab pack README
Python + FastAPI Interview Sprint labs
The weekend lab is Lab 501 — Order Service (`LAB-PF-501`).
It is a local Python 3.12+ / FastAPI service. BayLearn does not compile or
execute candidate code.
| Lab | What you do | Success |
|---|---|---|
| order-service | Build POST /api/v1/orders with schemas, SQLAlchemy, optimistic locking, idempotent create, transactional outbox write, and tests | pytest is green on your machine |
Download the same tree as pf-order-api-lab.zip from the sprint landing page,
or clone labs/order-service/ from this repository.
bash
cd labs/order-service
python3.12 -m venv .venv # use python3 if it already reports 3.12+
source .venv/bin/activate
pip install -e ".[dev]"
pytestSQLite is the default and the only database the tests use. Optional Postgres
is documented in order-service/README.md (docker compose up db).
Order Service README
Order Service README
Order Service lab (LAB-PF-501)
BayLearn interview lab: a production-style FastAPI / Pydantic v2 / SQLAlchemy 2.x
Order API. Routes expose schemas only (never ORM models). Persistence uses a
service + repository, optimistic locking, idempotent create, a transactional
outbox write, and a correlation-id middleware.
BayLearn does not compile or execute candidate code. Success is pytest on
your machine.
Prerequisites
- Python 3.12+
- Network on first
pip installso dependencies can download
Install and test (SQLite)
bash
python3.12 -m venv .venv # python3 works if it already reports 3.12+
source .venv/bin/activate
pip install -e ".[dev]"
pytestTests use an in-memory SQLite database (create_all in the fixture). Alembic
migration 0001_initial is also shipped for the file/Postgres profiles.
Run the API locally (SQLite)
bash
cp .env.example .env
uvicorn app.main:app --reload --app-dir src- API: http://localhost:8000/api/v1/orders
- Health: http://localhost:8000/health
- Ready: http://localhost:8000/ready
- OpenAPI: http://localhost:8000/docs
.env.example contains only DATABASE_URL=sqlite:///./order_service.db.
Do not add secrets or tokens.
Optional PostgreSQL
bash
docker compose up db
pip install -e ".[dev,postgres]"
# then point DATABASE_URL at postgresql+psycopg://orders@localhost:5432/orders
# (compose uses trust auth; no password is stored in this repo)
alembic upgrade head
uvicorn app.main:app --reload --app-dir srcOr the containerized API (SQLite inside the image):
bash
docker compose up --build apiThe image runs as a non-root user. Health checks hit GET /health.
API
| Method | Path | Notes |
|---|---|---|
POST | /api/v1/orders | Requires Idempotency-Key. Same key + body replays the first order. |
GET | /api/v1/orders/{order_id} | 404 when missing |
GET | /api/v1/orders | page / size, optional customer_id and status |
PATCH | /api/v1/orders/{order_id}/status | If-Match or body version → 409 on stale version |
DELETE | /api/v1/orders/{order_id} | Soft cancel (status=CANCELLED). Row is kept. |
GET | /health | Liveness |
GET | /ready | Readiness (database ping) |
Create example:
bash
curl -sS -X POST http://localhost:8000/api/v1/orders \
-H 'Content-Type: application/json' \
-H 'Idempotency-Key: checkout-42' \
-H 'X-Correlation-Id: demo-1' \
-d '{
"customer_id": "11111111-1111-1111-1111-111111111111",
"items": [
{ "product_id": "22222222-2222-2222-2222-222222222222", "quantity": 2, "unit_price": "19.99" }
]
}'Statuses: CREATED → CONFIRMED → PROCESSING → SHIPPED, or CANCELLED
from a non-terminal state. Money fields are Decimal, never float.
Standard error JSON:
json
{
"timestamp": "2026-09-12T00:00:00Z",
"status": 404,
"code": "ORDER_NOT_FOUND",
"message": "Order not found: …",
"correlationId": "…",
"errors": []
}Validation failures (quantity <= 0, empty items) return 422.
Design notes
- Idempotency: unique constraint on
idempotency_keys.key. Concurrent
inserts with the same key are caught and replayed; a different body is 409.
- Optimistic lock:
orders.versionstarts at 0.If-Matchor
{"version": N} must match; mismatch is 409 OPTIMISTIC_LOCK_CONFLICT.
- Outbox:
outbox_eventsis written in the same transaction. A publisher
worker is conceptual and is not implemented here.
- Logging: structured JSON with
correlation_id. Authorization / token
fields are never logged.
- DELETE: cancellation only. Documented here and on the OpenAPI operation.
What this lab does not include
- Remote code execution or an online compiler
- Secrets, API keys, or passwords in source or images
- A real message broker (outbox publisher is conceptual)
Lab walkthrough
Lab walkthrough
Order Service lab — LAB-PF-501
In one sentence: Build a thin, production-shaped POST /orders you can run with pytest on your laptop — Pydantic, SQLAlchemy 2.x, optimistic locking, idempotency, one event, tests.
What you are building
The lab lives at labs/order-service/ (Python 3.12+, FastAPI, Pydantic v2, SQLAlchemy 2.x, Alembic). BayLearn will not execute this for you. Success is pytest on your machine against SQLite.
See it
Read the diagrams, then say: In 35 minutes I ship the accept path: request model, validation, SQLAlchemy, version column, idempotent create, one event, tests. Workers and the broker are the *story* after commit — not a second service I have to deploy.
Minimum slice:
POST /orders(or/api/v1/orders) accepts a JSON command (customer, lines, optional currency).- Pydantic on the request; one error envelope for 400/409/422 and domain errors.
OrderServiceis constructed viaDepends; it owns the session /begin().- Persist
Order+OrderLine. Do not return mapped objects as the public contract — use a response model. - Idempotent create via
Idempotency-Keystored uniquely with a body hash. - Optimistic version on status changes (
versioncolumn). - After commit, publish
OrderCreated(in-process or outbox row). - Log
correlation_id+order_idon accept and reject. No secrets. - Tests: validation, happy create, replayed key, key conflict, version conflict.
SQLite is enough. A compose file may offer Postgres. You do not need Redis, Celery, or a cloud account to finish the sprint.
Whiteboard in 60 seconds
- Router / service / repository. Row never enters the router as the API type.
- Key store + order row, one commit. Replay vs 409.
versionon PATCH status.- After commit:
OrderCreated. Correlation id on the log line.
Build It (live-coding warm-up)
Before you open the lab, write one of these on a blank file, talking out loud:
- Frozen dataclass
Money(plusrejects mixed currencies) - Idempotency handler that returns the cached response on the same hash
- A function that does not use a mutable default
Ten minutes. If you freeze, you found the skill to drill — not a reason to skip the lab.
Scale It (the service shape)
text
orders.router models in/out, no logic
→ OrderService unit of work, ports
→ OrderRepository
→ IdempotencyStore
→ OrderEvents after commit or outboxSettings from the environment (.env.example has DATABASE_URL=sqlite:///./order_service.db — no secrets). Lifespan owns the engine.
Event publication: after-commit in-process is acceptable for the lab. If you want the senior version, write an outbox table in the same transaction and a test that the row exists even if the publisher is mocked.
Explain It (what you say in the mock)
“Retries with the same key and body return the original order. A different body on the same key is 409. We version the order so two status writers cannot clobber. We do not charge inside this transaction in the lab; if we did, we would forward the same key to the PSP. The event fires after commit so listeners do not see a rolled-back order.”
Name the loser: after-commit events can still be lost on crash (outbox is the upgrade). In-memory idempotency does not survive two uvicorn workers.
How to run
bash
cd labs/order-service
python3.12 -m venv .venv # python3 works if it already reports 3.12+
source .venv/bin/activate
pip install -e ".[dev]"
pytestUse a local virtualenv. Do not paste the project into an online compiler. Do not ask the player to execute code — it will not.
Optional: docker compose for a Postgres-shaped walkthrough. Default tests stay on SQLite.
Interview questions while you demo
- Where is the transaction boundary?
- What happens if I replay the key?
- What happens if I replay the key with a different JSON body?
- Why SQLite in tests and Postgres in prod — what changes?
- What did you leave out on purpose?
COMMON MISTAKE: Spending the block on folder cleanup. One green POST plus a replay test beats empty ports-and-adapters.
SENIOR-LEVEL EXPECTATION: Point at the unique constraint and the version column. Those are the correctness mechanisms.
Lab 501 — Architecture5 min
Lab 501 — Architecture
Order Service lab — LAB-PF-501
In one sentence: Build a thin, production-shaped POST /orders you can run with pytest on your laptop — Pydantic, SQLAlchemy 2.x, optimistic locking, idempotency, one event, tests.
What you are building
The lab lives at labs/order-service/ (Python 3.12+, FastAPI, Pydantic v2, SQLAlchemy 2.x, Alembic). BayLearn will not execute this for you. Success is pytest on your machine against SQLite.
See it
Read the diagrams, then say: In 35 minutes I ship the accept path: request model, validation, SQLAlchemy, version column, idempotent create, one event, tests. Workers and the broker are the *story* after commit — not a second service I have to deploy.
Minimum slice:
POST /orders(or/api/v1/orders) accepts a JSON command (customer, lines, optional currency).- Pydantic on the request; one error envelope for 400/409/422 and domain errors.
OrderServiceis constructed viaDepends; it owns the session /begin().- Persist
Order+OrderLine. Do not return mapped objects as the public contract — use a response model. - Idempotent create via
Idempotency-Keystored uniquely with a body hash. - Optimistic version on status changes (
versioncolumn). - After commit, publish
OrderCreated(in-process or outbox row). - Log
correlation_id+order_idon accept and reject. No secrets. - Tests: validation, happy create, replayed key, key conflict, version conflict.
SQLite is enough. A compose file may offer Postgres. You do not need Redis, Celery, or a cloud account to finish the sprint.
Whiteboard in 60 seconds
- Router / service / repository. Row never enters the router as the API type.
- Key store + order row, one commit. Replay vs 409.
versionon PATCH status.- After commit:
OrderCreated. Correlation id on the log line.
Build It (live-coding warm-up)
Before you open the lab, write one of these on a blank file, talking out loud:
- Frozen dataclass
Money(plusrejects mixed currencies) - Idempotency handler that returns the cached response on the same hash
- A function that does not use a mutable default
Ten minutes. If you freeze, you found the skill to drill — not a reason to skip the lab.
Scale It (the service shape)
text
orders.router models in/out, no logic
→ OrderService unit of work, ports
→ OrderRepository
→ IdempotencyStore
→ OrderEvents after commit or outboxSettings from the environment (.env.example has DATABASE_URL=sqlite:///./order_service.db — no secrets). Lifespan owns the engine.
Event publication: after-commit in-process is acceptable for the lab. If you want the senior version, write an outbox table in the same transaction and a test that the row exists even if the publisher is mocked.
Explain It (what you say in the mock)
“Retries with the same key and body return the original order. A different body on the same key is 409. We version the order so two status writers cannot clobber. We do not charge inside this transaction in the lab; if we did, we would forward the same key to the PSP. The event fires after commit so listeners do not see a rolled-back order.”
Name the loser: after-commit events can still be lost on crash (outbox is the upgrade). In-memory idempotency does not survive two uvicorn workers.
How to run
bash
cd labs/order-service
python3.12 -m venv .venv # python3 works if it already reports 3.12+
source .venv/bin/activate
pip install -e ".[dev]"
pytestUse a local virtualenv. Do not paste the project into an online compiler. Do not ask the player to execute code — it will not.
Optional: docker compose for a Postgres-shaped walkthrough. Default tests stay on SQLite.
Interview questions while you demo
- Where is the transaction boundary?
- What happens if I replay the key?
- What happens if I replay the key with a different JSON body?
- Why SQLite in tests and Postgres in prod — what changes?
- What did you leave out on purpose?
COMMON MISTAKE: Spending the block on folder cleanup. One green POST plus a replay test beats empty ports-and-adapters.
SENIOR-LEVEL EXPECTATION: Point at the unique constraint and the version column. Those are the correctness mechanisms.
Order Service README
Order Service README
Order Service lab (LAB-PF-501)
BayLearn interview lab: a production-style FastAPI / Pydantic v2 / SQLAlchemy 2.x
Order API. Routes expose schemas only (never ORM models). Persistence uses a
service + repository, optimistic locking, idempotent create, a transactional
outbox write, and a correlation-id middleware.
BayLearn does not compile or execute candidate code. Success is pytest on
your machine.
Prerequisites
- Python 3.12+
- Network on first
pip installso dependencies can download
Install and test (SQLite)
bash
python3.12 -m venv .venv # python3 works if it already reports 3.12+
source .venv/bin/activate
pip install -e ".[dev]"
pytestTests use an in-memory SQLite database (create_all in the fixture). Alembic
migration 0001_initial is also shipped for the file/Postgres profiles.
Run the API locally (SQLite)
bash
cp .env.example .env
uvicorn app.main:app --reload --app-dir src- API: http://localhost:8000/api/v1/orders
- Health: http://localhost:8000/health
- Ready: http://localhost:8000/ready
- OpenAPI: http://localhost:8000/docs
.env.example contains only DATABASE_URL=sqlite:///./order_service.db.
Do not add secrets or tokens.
Optional PostgreSQL
bash
docker compose up db
pip install -e ".[dev,postgres]"
# then point DATABASE_URL at postgresql+psycopg://orders@localhost:5432/orders
# (compose uses trust auth; no password is stored in this repo)
alembic upgrade head
uvicorn app.main:app --reload --app-dir srcOr the containerized API (SQLite inside the image):
bash
docker compose up --build apiThe image runs as a non-root user. Health checks hit GET /health.
API
| Method | Path | Notes |
|---|---|---|
POST | /api/v1/orders | Requires Idempotency-Key. Same key + body replays the first order. |
GET | /api/v1/orders/{order_id} | 404 when missing |
GET | /api/v1/orders | page / size, optional customer_id and status |
PATCH | /api/v1/orders/{order_id}/status | If-Match or body version → 409 on stale version |
DELETE | /api/v1/orders/{order_id} | Soft cancel (status=CANCELLED). Row is kept. |
GET | /health | Liveness |
GET | /ready | Readiness (database ping) |
Create example:
bash
curl -sS -X POST http://localhost:8000/api/v1/orders \
-H 'Content-Type: application/json' \
-H 'Idempotency-Key: checkout-42' \
-H 'X-Correlation-Id: demo-1' \
-d '{
"customer_id": "11111111-1111-1111-1111-111111111111",
"items": [
{ "product_id": "22222222-2222-2222-2222-222222222222", "quantity": 2, "unit_price": "19.99" }
]
}'Statuses: CREATED → CONFIRMED → PROCESSING → SHIPPED, or CANCELLED
from a non-terminal state. Money fields are Decimal, never float.
Standard error JSON:
json
{
"timestamp": "2026-09-12T00:00:00Z",
"status": 404,
"code": "ORDER_NOT_FOUND",
"message": "Order not found: …",
"correlationId": "…",
"errors": []
}Validation failures (quantity <= 0, empty items) return 422.
Design notes
- Idempotency: unique constraint on
idempotency_keys.key. Concurrent
inserts with the same key are caught and replayed; a different body is 409.
- Optimistic lock:
orders.versionstarts at 0.If-Matchor
{"version": N} must match; mismatch is 409 OPTIMISTIC_LOCK_CONFLICT.
- Outbox:
outbox_eventsis written in the same transaction. A publisher
worker is conceptual and is not implemented here.
- Logging: structured JSON with
correlation_id. Authorization / token
fields are never logged.
- DELETE: cancellation only. Documented here and on the OpenAPI operation.
What this lab does not include
- Remote code execution or an online compiler
- Secrets, API keys, or passwords in source or images
- A real message broker (outbox publisher is conceptual)
Lab 501 — Build the Order Service (LAB-PF-501)20 min
Lab 501 — Build the Order Service (LAB-PF-501)
Order Service lab (LAB-PF-501)
BayLearn interview lab: a production-style FastAPI / Pydantic v2 / SQLAlchemy 2.x
Order API. Routes expose schemas only (never ORM models). Persistence uses a
service + repository, optimistic locking, idempotent create, a transactional
outbox write, and a correlation-id middleware.
BayLearn does not compile or execute candidate code. Success is pytest on
your machine.
Prerequisites
- Python 3.12+
- Network on first
pip installso dependencies can download
Install and test (SQLite)
bash
python3.12 -m venv .venv # python3 works if it already reports 3.12+
source .venv/bin/activate
pip install -e ".[dev]"
pytestTests use an in-memory SQLite database (create_all in the fixture). Alembic
migration 0001_initial is also shipped for the file/Postgres profiles.
Run the API locally (SQLite)
bash
cp .env.example .env
uvicorn app.main:app --reload --app-dir src- API: http://localhost:8000/api/v1/orders
- Health: http://localhost:8000/health
- Ready: http://localhost:8000/ready
- OpenAPI: http://localhost:8000/docs
.env.example contains only DATABASE_URL=sqlite:///./order_service.db.
Do not add secrets or tokens.
Optional PostgreSQL
bash
docker compose up db
pip install -e ".[dev,postgres]"
# then point DATABASE_URL at postgresql+psycopg://orders@localhost:5432/orders
# (compose uses trust auth; no password is stored in this repo)
alembic upgrade head
uvicorn app.main:app --reload --app-dir srcOr the containerized API (SQLite inside the image):
bash
docker compose up --build apiThe image runs as a non-root user. Health checks hit GET /health.
API
| Method | Path | Notes |
|---|---|---|
POST | /api/v1/orders | Requires Idempotency-Key. Same key + body replays the first order. |
GET | /api/v1/orders/{order_id} | 404 when missing |
GET | /api/v1/orders | page / size, optional customer_id and status |
PATCH | /api/v1/orders/{order_id}/status | If-Match or body version → 409 on stale version |
DELETE | /api/v1/orders/{order_id} | Soft cancel (status=CANCELLED). Row is kept. |
GET | /health | Liveness |
GET | /ready | Readiness (database ping) |
Create example:
bash
curl -sS -X POST http://localhost:8000/api/v1/orders \
-H 'Content-Type: application/json' \
-H 'Idempotency-Key: checkout-42' \
-H 'X-Correlation-Id: demo-1' \
-d '{
"customer_id": "11111111-1111-1111-1111-111111111111",
"items": [
{ "product_id": "22222222-2222-2222-2222-222222222222", "quantity": 2, "unit_price": "19.99" }
]
}'Statuses: CREATED → CONFIRMED → PROCESSING → SHIPPED, or CANCELLED
from a non-terminal state. Money fields are Decimal, never float.
Standard error JSON:
json
{
"timestamp": "2026-09-12T00:00:00Z",
"status": 404,
"code": "ORDER_NOT_FOUND",
"message": "Order not found: …",
"correlationId": "…",
"errors": []
}Validation failures (quantity <= 0, empty items) return 422.
Design notes
- Idempotency: unique constraint on
idempotency_keys.key. Concurrent
inserts with the same key are caught and replayed; a different body is 409.
- Optimistic lock:
orders.versionstarts at 0.If-Matchor
{"version": N} must match; mismatch is 409 OPTIMISTIC_LOCK_CONFLICT.
- Outbox:
outbox_eventsis written in the same transaction. A publisher
worker is conceptual and is not implemented here.
- Logging: structured JSON with
correlation_id. Authorization / token
fields are never logged.
- DELETE: cancellation only. Documented here and on the OpenAPI operation.
What this lab does not include
- Remote code execution or an online compiler
- Secrets, API keys, or passwords in source or images
- A real message broker (outbox publisher is conceptual)
Lab pack README
Lab pack README
Python + FastAPI Interview Sprint labs
The weekend lab is Lab 501 — Order Service (`LAB-PF-501`).
It is a local Python 3.12+ / FastAPI service. BayLearn does not compile or
execute candidate code.
| Lab | What you do | Success |
|---|---|---|
| order-service | Build POST /api/v1/orders with schemas, SQLAlchemy, optimistic locking, idempotent create, transactional outbox write, and tests | pytest is green on your machine |
Download the same tree as pf-order-api-lab.zip from the sprint landing page,
or clone labs/order-service/ from this repository.
bash
cd labs/order-service
python3.12 -m venv .venv # use python3 if it already reports 3.12+
source .venv/bin/activate
pip install -e ".[dev]"
pytestSQLite is the default and the only database the tests use. Optional Postgres
is documented in order-service/README.md (docker compose up db).
Order Service README
Order Service README
Order Service lab (LAB-PF-501)
BayLearn interview lab: a production-style FastAPI / Pydantic v2 / SQLAlchemy 2.x
Order API. Routes expose schemas only (never ORM models). Persistence uses a
service + repository, optimistic locking, idempotent create, a transactional
outbox write, and a correlation-id middleware.
BayLearn does not compile or execute candidate code. Success is pytest on
your machine.
Prerequisites
- Python 3.12+
- Network on first
pip installso dependencies can download
Install and test (SQLite)
bash
python3.12 -m venv .venv # python3 works if it already reports 3.12+
source .venv/bin/activate
pip install -e ".[dev]"
pytestTests use an in-memory SQLite database (create_all in the fixture). Alembic
migration 0001_initial is also shipped for the file/Postgres profiles.
Run the API locally (SQLite)
bash
cp .env.example .env
uvicorn app.main:app --reload --app-dir src- API: http://localhost:8000/api/v1/orders
- Health: http://localhost:8000/health
- Ready: http://localhost:8000/ready
- OpenAPI: http://localhost:8000/docs
.env.example contains only DATABASE_URL=sqlite:///./order_service.db.
Do not add secrets or tokens.
Optional PostgreSQL
bash
docker compose up db
pip install -e ".[dev,postgres]"
# then point DATABASE_URL at postgresql+psycopg://orders@localhost:5432/orders
# (compose uses trust auth; no password is stored in this repo)
alembic upgrade head
uvicorn app.main:app --reload --app-dir srcOr the containerized API (SQLite inside the image):
bash
docker compose up --build apiThe image runs as a non-root user. Health checks hit GET /health.
API
| Method | Path | Notes |
|---|---|---|
POST | /api/v1/orders | Requires Idempotency-Key. Same key + body replays the first order. |
GET | /api/v1/orders/{order_id} | 404 when missing |
GET | /api/v1/orders | page / size, optional customer_id and status |
PATCH | /api/v1/orders/{order_id}/status | If-Match or body version → 409 on stale version |
DELETE | /api/v1/orders/{order_id} | Soft cancel (status=CANCELLED). Row is kept. |
GET | /health | Liveness |
GET | /ready | Readiness (database ping) |
Create example:
bash
curl -sS -X POST http://localhost:8000/api/v1/orders \
-H 'Content-Type: application/json' \
-H 'Idempotency-Key: checkout-42' \
-H 'X-Correlation-Id: demo-1' \
-d '{
"customer_id": "11111111-1111-1111-1111-111111111111",
"items": [
{ "product_id": "22222222-2222-2222-2222-222222222222", "quantity": 2, "unit_price": "19.99" }
]
}'Statuses: CREATED → CONFIRMED → PROCESSING → SHIPPED, or CANCELLED
from a non-terminal state. Money fields are Decimal, never float.
Standard error JSON:
json
{
"timestamp": "2026-09-12T00:00:00Z",
"status": 404,
"code": "ORDER_NOT_FOUND",
"message": "Order not found: …",
"correlationId": "…",
"errors": []
}Validation failures (quantity <= 0, empty items) return 422.
Design notes
- Idempotency: unique constraint on
idempotency_keys.key. Concurrent
inserts with the same key are caught and replayed; a different body is 409.
- Optimistic lock:
orders.versionstarts at 0.If-Matchor
{"version": N} must match; mismatch is 409 OPTIMISTIC_LOCK_CONFLICT.
- Outbox:
outbox_eventsis written in the same transaction. A publisher
worker is conceptual and is not implemented here.
- Logging: structured JSON with
correlation_id. Authorization / token
fields are never logged.
- DELETE: cancellation only. Documented here and on the OpenAPI operation.
What this lab does not include
- Remote code execution or an online compiler
- Secrets, API keys, or passwords in source or images
- A real message broker (outbox publisher is conceptual)
Lab walkthrough
Lab walkthrough
Order Service lab — LAB-PF-501
In one sentence: Build a thin, production-shaped POST /orders you can run with pytest on your laptop — Pydantic, SQLAlchemy 2.x, optimistic locking, idempotency, one event, tests.
What you are building
The lab lives at labs/order-service/ (Python 3.12+, FastAPI, Pydantic v2, SQLAlchemy 2.x, Alembic). BayLearn will not execute this for you. Success is pytest on your machine against SQLite.
See it
Read the diagrams, then say: In 35 minutes I ship the accept path: request model, validation, SQLAlchemy, version column, idempotent create, one event, tests. Workers and the broker are the *story* after commit — not a second service I have to deploy.
Minimum slice:
POST /orders(or/api/v1/orders) accepts a JSON command (customer, lines, optional currency).- Pydantic on the request; one error envelope for 400/409/422 and domain errors.
OrderServiceis constructed viaDepends; it owns the session /begin().- Persist
Order+OrderLine. Do not return mapped objects as the public contract — use a response model. - Idempotent create via
Idempotency-Keystored uniquely with a body hash. - Optimistic version on status changes (
versioncolumn). - After commit, publish
OrderCreated(in-process or outbox row). - Log
correlation_id+order_idon accept and reject. No secrets. - Tests: validation, happy create, replayed key, key conflict, version conflict.
SQLite is enough. A compose file may offer Postgres. You do not need Redis, Celery, or a cloud account to finish the sprint.
Whiteboard in 60 seconds
- Router / service / repository. Row never enters the router as the API type.
- Key store + order row, one commit. Replay vs 409.
versionon PATCH status.- After commit:
OrderCreated. Correlation id on the log line.
Build It (live-coding warm-up)
Before you open the lab, write one of these on a blank file, talking out loud:
- Frozen dataclass
Money(plusrejects mixed currencies) - Idempotency handler that returns the cached response on the same hash
- A function that does not use a mutable default
Ten minutes. If you freeze, you found the skill to drill — not a reason to skip the lab.
Scale It (the service shape)
text
orders.router models in/out, no logic
→ OrderService unit of work, ports
→ OrderRepository
→ IdempotencyStore
→ OrderEvents after commit or outboxSettings from the environment (.env.example has DATABASE_URL=sqlite:///./order_service.db — no secrets). Lifespan owns the engine.
Event publication: after-commit in-process is acceptable for the lab. If you want the senior version, write an outbox table in the same transaction and a test that the row exists even if the publisher is mocked.
Explain It (what you say in the mock)
“Retries with the same key and body return the original order. A different body on the same key is 409. We version the order so two status writers cannot clobber. We do not charge inside this transaction in the lab; if we did, we would forward the same key to the PSP. The event fires after commit so listeners do not see a rolled-back order.”
Name the loser: after-commit events can still be lost on crash (outbox is the upgrade). In-memory idempotency does not survive two uvicorn workers.
How to run
bash
cd labs/order-service
python3.12 -m venv .venv # python3 works if it already reports 3.12+
source .venv/bin/activate
pip install -e ".[dev]"
pytestUse a local virtualenv. Do not paste the project into an online compiler. Do not ask the player to execute code — it will not.
Optional: docker compose for a Postgres-shaped walkthrough. Default tests stay on SQLite.
Interview questions while you demo
- Where is the transaction boundary?
- What happens if I replay the key?
- What happens if I replay the key with a different JSON body?
- Why SQLite in tests and Postgres in prod — what changes?
- What did you leave out on purpose?
COMMON MISTAKE: Spending the block on folder cleanup. One green POST plus a replay test beats empty ports-and-adapters.
SENIOR-LEVEL EXPECTATION: Point at the unique constraint and the version column. Those are the correctness mechanisms.
Read the lab source
Same files as the zip. Open one at a time — map the function to the interview sentence.
pyproject.toml
toml
[build-system]
requires = ["setuptools>=68", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "order-service"
version = "0.1.0"
description = "BayLearn LAB-PF-501 FastAPI Order Service"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"fastapi>=0.115,<0.142",
"pydantic>=2.9",
"pydantic-settings>=2.4",
"sqlalchemy>=2.0.36,<2.1",
"alembic>=1.13",
"uvicorn>=0.30",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"httpx>=0.27",
]
postgres = [
"psycopg[binary]>=3.2",
]
[tool.setuptools.package-dir]
"" = "src"
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-q"
filterwarnings = [
"ignore:Using `httpx` with `starlette.testclient`",
"ignore:The anyio.abc.BlockingPortal alias is deprecated",
]You will
- Walk the timed sections
- Leave with a score that does not predict hiring
Mock interview brief5 min
Mock interview brief
Mock interview process
In one sentence: Treat the mock like a real loop — clarify, build a small correct slice, scale it to two workers and a retry, and defend the production risk.
Before the timer
Read your Module 0 weak skills. Tell the interviewer (or the player) your target mode:
| Mode | Who |
|---|---|
PYTHON_BACKEND_ENGINEER | Correct code, structures, basic FastAPI |
SENIOR_PYTHON_BACKEND_ENGINEER | Transactions, N+1, asyncio, idempotency, tests |
LEAD_PYTHON_BACKEND_ENGINEER | Ownership, dual write, worker model, coaching |
If you stay quiet, they will probe the default for your enrollment profile.
Have a blank editor, not your notes. You may ask the same things you would Monday: “Is the payment API idempotent? What must not happen twice?”
Opening script (use it)
“I’ll clarify the unit of work and the unacceptable failure, then I’ll build a small correct version, then I’ll show how it scales under retry and two workers, and what we do if payment is late.”
That is the shape. Silence is not mysterious. It just sounds empty.
Shape of 45 / 60 minutes
text
5 min — prompt + clarifying questions
20 min — code or API sketch (Order create / payment / inventory)
15 min — spoken probes (mutability, GIL, Depends, SQLAlchemy)
10 min — production (idempotency, outbox, traces) # 60-min form
5 min — you recap trade-offsThe 45-minute form trims production to one follow-up and shortens probes. Same opening sentence.
During the coding block
- Repeat the prompt in one sentence (
POST /ordersmust not double-create). - Write types and the sad path (missing key, empty lines,
qty <= 0). - Implement the happy path.
- Narrate the test you would add.
- Stop and invite questions — do not gold-plate a mapper framework.
If you are stuck, say what you are deciding. “I’m choosing a unique constraint over an in-memory lock because we have two uvicorn workers” sounds senior. Staring does not.
Spoken probes (expect these)
- Mutable vs immutable + the tuple caveat
- Mutable default arguments in a worker
isvs==- GIL — and do not say Python cannot do concurrency
time.sleepvsasyncio.sleepDependsvs a global- Engine vs session; N+1
- Idempotency key + body hash
- Authn vs authz vs CORS
Answer in 60–90 seconds, then stop. If they want depth, they will ask.
Production follow-up
They will change one fact: “the client retried,” “we added a second worker,” “p99 doubled after a cache,” “payment captured, inventory write failed.” Evolve one box. Do not redraw the system. Name the loser.
Lead/staff: they may ask you to coach a junior who used a mutable default, returned an ORM row, and time.sleeped in async def. Teach in the room.
Scoring
The rubric is weighted (see downloads/mock-interview-scorecard.md):
| Dimension | Weight |
|---|---|
| Core Python | 12% |
| Pythonic Coding | 8% |
| Async / Concurrency | 12% |
| FastAPI | 14% |
| API / Data | 12% |
| Coding Quality | 12% |
| Testing / Debugging | 8% |
| Production Engineering | 10% |
| Architecture / Trade-offs | 7% |
| Communication | 5% |
Each dimension is 1–5. Weighted total = Σ (score/5 × weight × 100).
The number is a rehearsal score. It does not predict a hiring outcome. Say that to yourself so you do not negotiate the rubric instead of learning.
After the mock
Write three lines before you leave the chair:
- What you would keep
- The first follow-up that hurt
- The sentence you will memorize tonight
Then go to Module 7 and turn those lines into a 7-day plan.
COMMON MISTAKE: Arguing that a broker was required after they asked for a single-service design. You can evolve later. Starting complicated is hard to walk back.
INTERVIEW TIP: If you finish early, add the test names and the failure case, not a new microservice.
Mock interview50 min
Mock interview
Module 6 — Mock Interview
Duration: 45–60 minutes · Kind: interview
The mock is a rehearsal, not a verdict and not a hiring prediction. It uses the same shape as a Python backend loop: a short coding or API design prompt, spoken Python / FastAPI probes, and one production follow-up (retry, N+1, GIL, or inventory race).
Modes
| Profile | Mock mode | What gets heavier |
|---|---|---|
| ENGINEER | PYTHON_BACKEND_ENGINEER | Correct code, structures, basic FastAPI |
| SENIOR_ENGINEER | SENIOR_PYTHON_BACKEND_ENGINEER | Transactions, N+1, asyncio, idempotency, testing |
| LEAD_STAFF | LEAD_PYTHON_BACKEND_ENGINEER | Ownership, dual write, worker model, coaching the room |
Difficulty is selected from your enrollment profile. You can still practice a harder mode; say so at the start so the interviewer does not waste probes.
Shape of the hour
text
5 min — prompt + clarifying questions
20 min — code or API sketch (Order create / payment / inventory)
15 min — spoken probes (mutability, GIL, Depends, SQLAlchemy)
10 min — production (idempotency, outbox, traces)
5 min — you recap trade-offsOpen with a small correct version, then how it scales, then the risk.
Rubric (weighted)
Core Python 12% · Pythonic Coding 8% · Async / Concurrency 12% · FastAPI 14% · API / Data 12% · Coding Quality 12% · Testing / Debugging 8% · Production Engineering 10% · Architecture / Trade-offs 7% · Communication 5%
The player scorecard matches downloads/mock-interview-scorecard.md. The disclaimer is mandatory: this measures rehearsal against the BayLearn rubric. It does not predict a hiring outcome.
How to fail the mock (avoid these)
- Silent typing for ten minutes
- “Python cannot do concurrency”
- Mutable default “because it is convenient”
- “I’d add Kafka” with no owner for the write
- Arguing the interviewer instead of naming a loser
How to pass the room
Ask what must not happen twice. Write the sad path. When they change the scale, evolve one box. Do not redraw the whole system.
Open the mock process lesson before you start the timer.
You will
- Leave with practice, not a hiring prediction
Feedback and interview plan10 min
Feedback and interview plan
Feedback and 7-day plan
In one sentence: Turn the mock into three drills and a week of spoken practice — the certificate is optional, the plan is the product.
How to read the report
Do not average the bars. Interviews fail closed on the dimension the loop cares about. A 90 in Core Python and a 40 in Production means you will write a clean dataclass and then double-charge.
Disclaimer: The mock score measures rehearsal performance against the BayLearn Python Backend rubric. It does not predict a hiring outcome.
Compare Module 0 to the mock:
| If Module 0 was low in… | And the mock still wobbled… | The plan is… |
|---|---|---|
| Python Fundamentals | is vs ==, tuple caveat | Rewrite the types table from memory |
| Pythonic Coding | Mutable default / wrong structure | Teach the decision table out loud |
| Advanced Python | Decorators without wraps | Write one timed decorator + generator |
| Async & Concurrency | GIL slogan / time.sleep | Draw the matrix; fix one async handler |
| FastAPI | Globals instead of Depends | Rebuild the dependency graph |
| REST/API Design | 200-with-error | Recite statuses + error envelope |
| Data/Persistence | N+1 / session leak | Count queries on a list endpoint |
| Testing | “I would test it” | Write three TestClient names |
| Production Readiness | Retry / secrets / probes | Write the paragraph until it is boring |
If a bar went up, keep a light review (one question) so it does not decay. Spend the hours on the bar that did not move.
Three artifacts to keep
- First sentences — write the opening line of your five weakest answers. Example: “The GIL serializes bytecode in one process; I still do concurrent I/O with asyncio or threads.”
- One coding kata —
Money, idempotency handler, or boundedgather. Timebox 15 minutes. - One production paragraph — idempotency + outbox + correlation ID. This is the senior discriminator.
7-day plan (45–70 minutes a day)
Day 1 — Core Python + data structures. Mutability, identity vs equality, list/dict/set table. Speak each answer once without notes.
Day 2 — Iterators, generators, decorators, typing. Stream a file. @wraps. Protocol vs Pydantic. Frozen dataclass Money.
Day 3 — GIL + threading + multiprocessing + asyncio. Decision matrix. time.sleep vs asyncio.sleep. Timeout + cancellation + semaphore.
Day 4 — FastAPI + Pydantic + REST. Depends graph. Request vs response models. Status codes. Authn vs authz vs CORS.
Day 5 — SQLAlchemy + transactions + testing. N+1 fix. Session lifecycle. Idempotency store. Outbox vs after-commit. Re-run pytest in LAB-PF-501.
Day 6 — Production + bank & review. Ten questions from the 190+ bank out loud. One code-review exercise. One debugging scenario. Logs / jitter / health.
Day 7 — Dress rehearsal. 45-minute self-mock. Use the scorecard honestly. Run downloads/final-interview-checklist.md the night before the real loop.
What not to do
- Rebuild a side project instead of speaking answers.
- Collect more decorators.
- Retake the readiness test until the number is pretty.
- Add a broker to the lab to feel senior.
- Treat a high mock score as an offer prediction.
Certificate
When the sprint path is complete, BayLearn can issue a course-completion certificate. It is a BayLearn course-completion certificate, not an industry certification, and it is not a hiring recommendation. Put the 7-day plan on your calendar; put the certificate in a folder.
Interview questions to leave on a sticky note
- Mutable default — what leaks in a worker?
isvs==— when isiscorrect?- Can Python do concurrency? (Yes. Walk the GIL matrix.)
time.sleepinasync def— what dies?- Why two Pydantic models?
- Engine vs session?
- How do you see and fix N+1?
- How is
POST /ordersidempotent across two workers? - What happens if you publish then crash?
- Authn vs authz vs CORS?
If you can teach those ten to a colleague, you used the sprint.
How you know the week worked
You can teach the ten sticky-note questions without notes, pytest is still green in LAB-PF-501, and you have one recorded (or spoken-aloud) 45-minute self-mock. If any of those is missing, do not add more reading — repeat the missing day.
COMMON MISTAKE: A 14-day list of blog posts. Seven focused days beat a syllabus you will not touch.
INTERVIEW TIP: Book the spoken practice like a meeting. You will have to say the answer out loud, then write the code.
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 Your Interview Sprint
Request a slot. Invoicing is handled by BayAreaLa8s after the request — no Stripe checkout.