BayLearnBayAreaLa8s

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

Preview the 7-day plan

Four-hour agenda

  1. Hour 1

    Core concepts and interview patterns

  2. Hour 2

    Architecture / coding scenarios

  3. Hour 3

    Hands-on interview challenges

  4. 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 Call

FAQ

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 Programs

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 PLAN

What 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:

  1. Implement POST /orders so a retry does not create two payments.
  2. Explain why you chose Pydantic models at the edge and a service layer for the transaction.
  3. Find the N+1 query when listing orders with line items.
  4. 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

ModuleTimeTopic
015 minReadiness Assessment
135 minPython Interview Essentials
240 minAdvanced Python, Async & Concurrency
340 minFastAPI + REST + Pydantic
435 minSQLAlchemy, Data & Production Backend
535 minLive Coding + FastAPI Order Service
645–60 minMock Interview
710 minFeedback & 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:

  1. They recite “lists are mutable” and then ship a mutable default argument that leaks state across requests.
  2. They say “Python cannot do concurrency because of the GIL,” then cannot explain threads for I/O or processes for CPU.
  3. They ship POST /orders without an idempotency key, then cannot talk about double charges.

This sprint trains the spoken answer and the written code together.

What you will do

  1. Take a 20-question readiness assessment and see nine skill scores
  2. Review Python the way interviewers probe it: types, mutability, structures, functions
  3. Make iterator, typing, GIL, and asyncio decisions on order and payment examples
  4. Design REST + Pydantic the way a FastAPI service is actually reviewed
  5. Walk production patterns: SQLAlchemy 2.x, cache-aside, outbox, observability
  6. Build LAB-PF-501 locally with pytest — BayLearn does not execute your code
  7. Practice from a 190+ question bank and 25 coding challenges
  8. Run a scored 45–60 minute mock (ENGINEER / SENIOR / LEAD tracks)
  9. 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

SkillWhat a miss usually means in an interview
Python FundamentalsYou lecture types and then mutate a tuple’s inner list, or confuse is with ==
Pythonic CodingYou cannot choose list vs dict vs set, or you leak a mutable default
Advanced PythonGenerators, decorators, typing, and MRO become slogans
Async & Concurrency“Python cannot do concurrency”; time.sleep in async def
FastAPIYou cannot place routes, deps, or lifespan; you treat Pydantic as optional comments
REST/API Design200-with-error, no pagination story, auth confused with authz
Data/PersistenceSession-per-app, N+1 on order + lines, no transaction boundary
Testing“I would write tests” with no TestClient or fixture story
Production ReadinessRetry 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 /orders is 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

SkillWhat a miss usually means in an interview
Python FundamentalsYou lecture types and then mutate a tuple’s inner list, or confuse is with ==
Pythonic CodingYou cannot choose list vs dict vs set, or you leak a mutable default
Advanced PythonGenerators, decorators, typing, and MRO become slogans
Async & Concurrency“Python cannot do concurrency”; time.sleep in async def
FastAPIYou cannot place routes, deps, or lifespan; you treat Pydantic as optional comments
REST/API Design200-with-error, no pagination story, auth confused with authz
Data/PersistenceSession-per-app, N+1 on order + lines, no transaction boundary
Testing“I would write tests” with no TestClient or fixture story
Production ReadinessRetry 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 /orders is 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.

  1. True True True True — Python interned every equal string, so == and is are interchangeable.
  2. 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.
  3. True False True False — two literals of the same text are never the same object.
  4. 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

TypeMutable?Typical order-service use
intNoQuantity, version, status code
floatNoAvoid for money. Use Decimal or integer cents.
boolNoFlags; remember bool is a subclass of int
strNoSKUs, customer ids, idempotency keys
listYesLine items you will append
tupleSpine noFixed pair (sku, qty) — see caveat
dictYesJSON-shaped payloads, indexes by id
setYesMembership: “have we seen this SKU?”
frozensetNoHashable set of tags used as a map key
NoneN/AMissing optional; singleton
bytes / bytearrayNo / YesHashes vs buffers you mutate
DecimalNoMoney. 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

Names bind to objects — assignment never copies Names bind to objects — assignment never copies Name: order_idlives in a namespaceObject: 'ord-1'str · id() · typeName: aliassame object Rebind order_id = 'ord-2'alias still points at 'ord-1'Mutate a list in placeevery name that aliases it sees the changeInterview line: I rebind names for immutables. I mutate lists and dicts. id() is identity.
Names bind to objects — assignment never copies
Mutable vs immutable — and the tuple caveat Mutable vs immutable — and the tuple caveat Immutable (rebind, do not mutate)int float bool str frozenset Nonetuple spine cannot grow/shrinkSafe dict keys only if nested-hashableMutable (in-place change)list dict set bytearraymost user objects / Pydantic modelsDefault-arg trap: items=[]Tuple caveatrow = ('ord-1', ['A']); row[1].append('B') — legal. hash(row) fails. Not a dict key.
Mutable vs immutable — and the tuple caveat
Immutable names rebind; mutable objects alias Immutable names rebind; mutable objects alias n = 1; n = 2new int objectold name reboundlines.append(item)same list objectaliases see the appendtuple of a listspine frozenpayload still mutatesSay: rebind vs mutate. Then: a tuple is only as hashable as its children.
Immutable names rebind; mutable objects alias

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 items

PYTHON GOTCHA: += on a list mutates; += on a tuple rebinds a new tuple. lines += [item] vs pair += (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 list

A 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

is vs == — identity vs value is vs == — identity vs value a is bsame object · same id()use for None / sentinelsa == b__eq__ · valueuse for money, ids, JSONInterning trap256 is 256 often True257 is 257 often FalseNever write if status is 'PAID'. A JSON-loaded str is a different object.Custom __eq__ without a matching __hash__ breaks set / dict keys.
is vs == — identity vs value
  • a == b → __eq__ (value)
  • a is b → same object (same id())

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 unit

COMMON MISTAKE: Writing if status is "PAID" because it worked once on interned literals. A status loaded from JSON is a different str object.

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 == 1 and hash(True) == hash(1). {True: "flag", 1: "one"} keeps one key. Do not use bool as a numeric key.

Mutable default arguments

Mutable default is created once — at def time Mutable default is created once — at def time def add(line, acc=[])one list for the processRequest A appendsacc now has A's lineRequest B omits accsees A's line · leak Fix: acc=None then acc = [] inside. Same bug on dict/set and dataclass lines: list = [].
Mutable default is created once — at def time

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 lines

Same 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

  1. Two columns: immutable vs mutable. Put float in “don’t use for money.”
  2. Draw a tuple box holding a list; mark “unhashable / inner mutation.”
  3. is vs == with None as the only is you write by habit.
  4. def f(x, acc=None) — “default created once.”
  5. Arrow: worker process lives for hours → leaked default list.

Follow-up ladder

  1. What is mutable? → table + tuple caveat.
  2. Why is is wrong for status? → interned literal vs JSON str.
  3. Show the default-arg leak on a FastAPI worker. → one list, many requests.
  4. bool as a dict key? → True == 1 collapse.
  5. How would you make Money safe? → frozen dataclass / Decimal, no float.

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_factory cousin 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

NeedReach forAvoid
Sequence, duplicates OK, indexlistdeque unless you pop left a lot
Fixed record, hashable if contents aretuple / NamedTupletuple-of-lists as a key
Key → valuedictparallel lists of ids and objects
Unique membershipsetif x in big_list on hot paths
Unique + hashable set-as-keyfrozensetset as a dict key
Insertion-ordered uniquedict keys or dict.fromkeysrelying on set order as an API
FIFO / sliding windowcollections.dequelist.pop(0)
Counters / frequenciescollections.Counterrolling your own off-by-one
Default nested mapsdefaultdictsetdefault chains you cannot read
Bounded cacheOrderedDict / functools.lru_cacheunbounded dict of all SKUs
Heap / top-Kheapqsorting a million rows for “top 5”

See it

Pick the structure from the next operation Pick the structure from the next operation listsequence · indexO(n) membershipdictkey → valueO(1) avg lookupsetunique membershipO(1) avg indequeFIFO / windowO(1) popleftHashability is the gate for dict keys and set members. True == 1 collapses one slot.
Pick the structure from the next operation
dict / set lookup — key → hash → bucket → eq dict / set lookup — key → hash → bucket → eq keysku / (sku, qty)hash(key)must be stablebucketcollision chain== compareright object or miss Mutating a key after insert orphans the entry. That is the Python equals/hashCode disaster.
dict / set lookup — key → hash → bucket → eq

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”:

  1. hash(key)
  2. mask into a bucket
  3. compare with == until you hit or miss
  4. average O(1); worst-case degraded hashes exist — interviews want the average story

PYTHON GOTCHA: hash(True) == hash(1) and True == 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

Operationlistdict / setdeque
Index / key lookupO(1)O(1) averageO(n) middle
Membership x in …O(n)O(1) averageO(n)
Append / insert keyO(1) amortizedO(1) averageO(1) either end
Pop last / delete keyO(1)O(1) averageO(1)
Pop frontO(n)n/aO(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 mapping tests keys, not values.
  • dict.keys() / .values() / .items() are views — they change if the dict changes. Iterating a view while mutating the dict raises RuntimeError.
  • list(d) copies keys. dict(d) is a shallow copy. Nested lists inside values are still aliased.

COMMON MISTAKE: if line in orders when orders is a dict of id → order. You meant if 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

  1. Draw the decision table: sequence / key / membership / FIFO.
  2. Write O(1) vs O(n) for in.
  3. Hash path: key → hash → bucket → ==.
  4. dict insertion order since 3.7; set is not ordered API.
  5. One comprehension; one generator expression for a large export.

Follow-up ladder

  1. List vs set for SKU membership? → O(n) vs O(1).
  2. Why can’t a list be a key? → mutable, hash would change.
  3. Dedupe and keep first-seen? → dict.fromkeys.
  4. True and 1 in the same dict? → collapse.
  5. Sliding window of last N events? → deque(maxlen=N), not list.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/1 collapse, 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 reading kwargs["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

LEGB — Local, Enclosing, Global, Built-in LEGB — Local, Enclosing, Global, Built-in Localfunction bodyEnclosingclosure cellsGlobalmodule namesBuilt-inlen · Decimal global / nonlocal rebind. In FastAPI you almost never need global — that is process state.
LEGB — Local, Enclosing, Global, Built-in

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 price

global 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 + 1

Closures and the late-binding gotcha

Closures capture the variable, not the value Closures capture the variable, not the value Wrongfor status in states: handlers.append(lambda: status)all see the last statusBind nowlambda status=status: statusor a helper that takes statusSame bug building asyncio.create_task in a loop when url is rebound.
Closures capture the variable, not the value

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 now

Same 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 · copy is shallow · deepcopy recurses Assignment aliases · copy is shallow · deepcopy recurses b = atwo names, one objectcopy.copy(a)new outer dictshared child listdeepcopy(a)new graph · slownever deepcopy an ORM rowEditing shallow['lines'][0]['qty'] mutates the original. Build a new Pydantic model instead.
Assignment aliases · copy is shallow · deepcopy recurses
  • 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 9

On 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 alias

PRODUCTION 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:

  1. Catch specific types. Bare except: swallows KeyboardInterrupt and bugs.
  2. except Exception is for a boundary (middleware) that must return JSON, not for a service core.
  3. Raise domain errors; map them once to HTTP (Module 3).
  4. raise (bare) preserves the traceback; raise e resets it. raise e from err chains.
  5. Use exception groups / except* only if they ask about asyncio.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

  1. Signature: required, *args, keyword-only, **kwargs.
  2. LEGB boxes. Circle nonlocal as rare.
  3. Loop + lambda: bind with default.
  4. Shallow vs deep: one shared child arrow in red.
  5. raise vs raise e vs raise e from err.

Follow-up ladder

  1. What do *args / **kwargs bind? → tuple and dict.
  2. Why did every lambda print SHIPPED? → late binding.
  3. Show a shallow-copy bug on lines. → shared child dict.
  4. When is deepcopy wrong? → ORM, sockets, locks.
  5. 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 global caches in a handler. Put shared clients on app.state via 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 → iterator → values (one pass) Iterable → iterator → values (one pass) Iterable__iter__()list · file · queryIterator__next__()exhausts · one passGeneratoryield / genexplazy · close the cursor You can iterate a list twice. An iterator / generator is spent. Holding a DB cursor must close.
Iterable → iterator → values (one pass)
  • Iterable — has __iter__ that returns an iterator. list, dict, files, query results.
  • Iterator — has __next__ (and usually __iter__ returning self). 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) -> StopIteration

A 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 sku

In an interview, a generator is the version you would ship:

python

def iter_skus(skus: list[str]):
    yield from skus

yield 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 named iter_…. You just loaded the file.

Decorators and functools.wraps

Decorator wraps a callable — preserve the name Decorator wraps a callable — preserve the name def createoriginal handler@timed + wrapskeep __name__ / docswrapperpre / post / timingcallcreate(*args) Without @wraps, OpenAPI and tracebacks say wrapper. Do not call the function at decorate time.
Decorator wraps a callable — preserve the name

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 wrapper

Without @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) without wrapper (calling at decoration time) runs the handler at import. That can take the app down.

Context managers

with always runs cleanup — even on raise with always runs cleanup — even on raise withenter protocol__enter__session / file / lockbodyuse the resource__exit__commit / rollback / close Returning True from __exit__ swallows the exception. Do not. FastAPI lifespan is process-level with.
with always runs cleanup — even on raise

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

  1. Three boxes: iterable / iterator / generator.
  2. yield as “pause and hand a row.”
  3. @wraps so __name__ survives.
  4. with session commit/rollback/close.
  5. Arrow: unconsumed generator → leaked connection.

Follow-up ladder

  1. Is a list an iterator? → No. Iterable.
  2. Stream a 2 GB export? → generator / StreamingResponse.
  3. Why @wraps? → name, docs, annotations, unwrap.
  4. When is a decorator wrong? → request-scoped state that Depends already gives you.
  5. 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 * unit

Hints 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.”

ToolWhenRuntime?
AnnotationsInternal functions, editor helpNo (unless you add a library)
dataclassesSimple in-process recordsNo validation unless you add it
Pydantic BaseModelHTTP, settings, JSON edgesYes
TypedDictUntyped dicts you cannot upgrade yetNo
NamedTupleTiny immutable recordsNo

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 | None

A 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; cls so 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

Three shapes — command, view, row Three shapes — command, view, row OrderCreateclient may sendPydantic validatesOrder (ORM)version · internalsOrderReadpromised fields onlyOne model for create, update, ORM, and JSON leaks version and accepts client ids.
Three shapes — command, view, row
Names bind to objects — assignment never copies Names bind to objects — assignment never copies Name: order_idlives in a namespaceObject: 'ord-1'str · id() · typeName: aliassame object Rebind order_id = 'ord-2'alias still points at 'ord-1'Mutate a list in placeevery name that aliases it sees the changeInterview line: I rebind names for immutables. I mutate lists and dicts. id() is identity.
Python object / reference model

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

  1. Hints = static; Pydantic = runtime boundary.
  2. Frozen dataclass for Money; default_factory for lists.
  3. Protocol box for PaymentPort.
  4. MRO as a list, not a tree you invent on the fly.
  5. Three shapes: command / view / row.

Follow-up ladder

  1. Do hints enforce types? → No.
  2. Dataclass vs Pydantic vs ORM? → value / boundary / persistence.
  3. Show Money.plus that cannot mutate self. → frozen, return new.
  4. Why Protocol? → test doubles without an ABC tax.
  5. 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 OrderService features. 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

The GIL serializes bytecode — not all concurrency The GIL serializes bytecode — not all concurrency One processone GIL · one bytecode runnerI/O waitGIL releasedthreads overlap waitsTwo processestwo GILs · two corestwo connection poolsDo not say Python cannot do concurrency. Say: overlap waits; parallel CPU needs processes.
The GIL serializes bytecode — not all concurrency

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

Pick the concurrency tool from the wait vs the CPU Pick the concurrency tool from the wait vs the CPU Many I/O waits · async libsasyncio + awaitone loop per workerBlocking I/O · sync SDKthreads / to_threadGIL released on waitCPU-bound Pythonprocesses · queuebypass the GILA Python Lock does not protect inventory across uvicorn workers. Use SQL.
Pick the concurrency tool from the wait vs the CPU

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 out

Shared 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.append is atomic in CPython practice; d[k] += 1 is 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

WorkToolWhy
Many HTTP/DB waits, async libsasyncioOne thread, cooperative overlap
Many waits, sync SDKthreadsGIL released on I/O
CPU: PDF, image, crypto in Pythonprocesses or queueBypass GIL
Shared counter in one processthreading.Lock / QueueGIL ≠ correctness
Inventory decrementSQL constraint / versionNot a Python lock
Use all cores for FastAPIuvicorn workers + queueOne 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

  1. One box: process + GIL. One thread runs bytecode.
  2. Arrow out of GIL: “I/O wait.”
  3. Two process boxes: two GILs, two cores, two pools.
  4. Matrix: I/O / CPU / correctness (DB).
  5. Write workers × pool_size.

Follow-up ladder

  1. What is the GIL? → bytecode mutex, not “no concurrency.”
  2. Can two threads wait on HTTP? → yes, GIL released.
  3. Speed up JSON parse with threads? → no, CPU.
  4. Four cores for FastAPI? → four workers + pool math.
  5. 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

Event loop — await parks a task; sleep freezes everyone Event loop — await parks a task; sleep freezes everyone Loopready queueawait I/Othis task parksother requestruns while parkedtime.sleepfreezes the worker await asyncio.sleep parks. time.sleep inside async def is a production outage.
Event loop — await parks a task; sleep freezes everyone
Asyncio loop — overlap waits, never block the thread Asyncio loop — overlap waits, never block the thread Task A await paysocket waitTask B await invsame threadLoop interleaveswhen each await yieldsAn async def that never awaits is a sequential function in costume.
Asyncio loop — overlap waits, never block the thread

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

time.sleep vs asyncio.sleep in an async handler time.sleep vs asyncio.sleep in an async handler time.sleep(2) in async defthe only loop thread is stuckevery request on this worker waitsawait asyncio.sleep(2)this task parksother checkouts continuerequests.get inside async def is the same class of bug. Use httpx.AsyncClient or to_thread.
time.sleep vs asyncio.sleep in an async handler
CallEffect on the loop
await asyncio.sleep(2)Parks this task; other requests run
time.sleep(2) inside async defFreezes the worker for two seconds
time.sleep(2) inside def FastAPI routeBlocks 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.

Sync SDK in an async route — offload, do not block Sync SDK in an async route — offload, do not block async def checkoutawait to_thread(sdk)threadpool · still scarceCPU / PDFprocess pool or queueto_thread is for blocking I/O. Burning cores belongs off the request worker.
Sync SDK in an async route — offload, do not block

COMMON MISTAKE: requests.get inside async def. Use an async client (httpx.AsyncClient) or to_thread. Otherwise you blocked the loop.

gather, timeouts, cancellation

gather overlaps I/O — bound it and time it out gather overlaps I/O — bound it and time it out payments.getinventory.getgathertimeout + sem 200 unbounded gathers open 200 sockets. Semaphore(10) + wait_for / asyncio.timeout.
gather overlaps I/O — bound it and time it out
Bound fan-out or you will melt the dependency Bound fan-out or you will melt the dependency gather(*200 calls)file descriptors · 429sSemaphore(10)only 10 in flighttimeout scopecancel the restOn cancel: close the socket, roll back the DB work, do not leave a half charge.
Bound fan-out or you will melt the dependency

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, inv
  • asyncio.gather — run many; by default the first exception cancels siblings (3.11+ TaskGroup is 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 (a BaseException). Clean up in finally or try/except CancelledError.

python

async def with_timeout(coro, seconds: float):
    async with asyncio.timeout(seconds):
        return await coro

ASYNC WARNING: A gather of 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 def for truly sync libraries; FastAPI will run them in its threadpool. Do not then call def from async def without to_thread.
  • Lifespan: open a shared httpx.AsyncClient and dispose it on shutdown. Do not create a client per request.
  • Background: BackgroundTasks is 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

  1. Loop + two tasks parked on I/O.
  2. Red X on time.sleep / requests.get.
  3. gather + timeout + semaphore.
  4. Arrow “CPU → process pool / queue.”
  5. CancelledError in finally.

Follow-up ladder

  1. What does await do? → yield until done.
  2. Why is time.sleep a prod bug? → one thread, everyone waits.
  3. Sync payment SDK? → to_thread + timeout + pool size.
  4. Cancel a slow fan-out? → timeout scope; client must close.
  5. gather vs TaskGroup? → 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, never time.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

FastAPI request path — ASGI to response model FastAPI request path — ASGI to response model ASGIuvicornMiddlewareCID · CORSDependsauth · sessionRoutethinServicerules + txResponsefilter Middleware is the belt. Depends is per-request wiring. The route does not commit.
FastAPI request path — ASGI to response model
Request hits middleware, Depends, then the route Request hits middleware, Depends, then the route ClientMiddlewareDependsRoutemodel_dump response_model is the contract filter if you accidentally return an ORM row.
Request hits middleware, Depends, then the route
Router / service / repository — entity stays in persistence Router / service / repository — entity stays in persistence API / schemascommand in · view outServicetx · domain · portsRepositorySQLAlchemy only Interview line: the mapped Order never is the public JSON contract.
Router / service / repository — entity stays in persistence

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

KindHowExample
Path{order_id}/orders/{order_id}
Queryfunction arglimit: int = 20
HeaderHeader()Idempotency-Key
BodyPydantic modelpayload: OrderCreate
Form / FileForm, UploadFilerare on this sprint
CookieCookie()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.AsyncClient or an engine per request. You will leak sockets and exhaust the DB.

ASGI and uvicorn (conceptually)

Production FastAPI — stateless workers behind a balancer Production FastAPI — stateless workers behind a balancer ClientLBUvicorn procsN loops · N GILsFastAPIDB / cache / QSticky sessions and local disk are smells. Uploads go to object storage.
Production FastAPI — stateless workers behind a balancer

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 / GILs

uvicorn 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

  1. Client → uvicorn → middleware → Depends → route → service.
  2. Path / query / header / body labeled on one POST /orders.
  3. Lifespan: engine + HTTP client in, dispose out.
  4. Workers = processes = N pools.
  5. OpenAPI generated; status codes owned by you.

Follow-up ladder

  1. What is FastAPI built on? → Starlette + Pydantic.
  2. Middleware vs Depends? → whole-app wrap vs request graph.
  3. Where does the session live? → yield dep, not global.
  4. Two workers and an in-memory key map? → broken idempotency.
  5. 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: int will 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

Three shapes — command, view, row Three shapes — command, view, row OrderCreateclient may sendPydantic validatesOrder (ORM)version · internalsOrderReadpromised fields onlyOne model for create, update, ORM, and JSON leaks version and accepts client ids.
Three shapes — command, view, row

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 order

Request 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 Order model for create, update, ORM, and JSON. You will leak version internals or accept id from the client.

Depends

Depends is constructor injection for FastAPI Depends is constructor injection for FastAPI Settingsenv · cachedSession yieldclose in finallyOrderServiceports in ctorRouteoverride in tests Tests override get_session. Do not new up SQLAlchemy in the router.
Depends is constructor injection for FastAPI

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

  1. OrderCreate vs OrderRead vs mapped Order.
  2. Field(gt=0) on qty; extra="forbid" on commands.
  3. Depends graph: settings → session → service → route.
  4. Settings from env; .env.example only.
  5. dependency_overrides in pytest.

Follow-up ladder

  1. Why Pydantic if we have hints? → runtime at the edge.
  2. v1 vs v2 names? → model_dump, field_validator, from_attributes.
  3. Client sent qty: 0? → 422 before the service.
  4. How do you test without Postgres? → override get_session.
  5. 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 — and extra="forbid" on commands so clients cannot set status.

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

Status code + stable error envelope Status code + stable error envelope 201 / 200create / read409key reuse ≠ bodyor version clash422Pydantic401 / 403authn / authzNever 200 {error}. Replay of the same key returns the original 201 + body.
Status code + stable error envelope
CodeWhen on an order API
200Read or update that returns a body
201Create; include Location
204Delete / empty success (if you choose)
400Malformed / missing required header (Idempotency-Key)
401Missing or invalid credentials
403Authenticated but not allowed
404Order id does not exist (do not leak others’ ids if that is policy)
409Idempotency key reused with a different body; optimistic lock; conflict
422Validation (Pydantic)
429Rate limit
500Bug — you log it; you do not dump a traceback to the client
503Not 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

Idempotency-Key lives in the same commit as the order Idempotency-Key lives in the same commit as the order ClientIdempotency-Key+ bodyHash bodycanonical JSONSame TXorder + key rowReplaystored 201 Same key, different hash → 409. Unique constraint is the correctness mechanism.In-memory maps die across uvicorn workers. The table is the source of truth.
Idempotency-Key lives in the same commit as the order

POST /orders is not idempotent by HTTP definition. You make it idempotent with a key:

  1. Client sends Idempotency-Key (or client_order_id).
  2. You store key + payload hash + response in the same transaction as the order.
  3. Replay same hash → stored response.
  4. 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

Authn, authz, and CORS are three different circles Authn, authz, and CORS are three different circles Authnwho? JWT / sessionAuthzmay Alice cancel Bob?CORSbrowser onlycurl ignores itA valid token that can cancel any order is an authz bug. CORS did not cause it.
Authn, authz, and CORS are three different circles
  • Authentication — who is this? Token, session, mTLS. Result: a principal.
  • Authorization — what may they do? customer_id matches, role is agent, scope includes orders: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

  1. Table: 201 / 401 / 403 / 409 / 422.
  2. Error envelope with code + correlationId.
  3. Cursor pagination on (created_at, id).
  4. Authn vs authz vs CORS as three separate circles.
  5. Idempotency: same TX, unique key, hash, 409.

Follow-up ladder

  1. 201 vs 200 on create? → 201 + Location; replay may repeat 201.
  2. Same key, different body? → 409.
  3. Paginate all orders? → keyset, stable sort.
  4. Authn vs authz? → who vs what.
  5. 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.

Engine is the pool · session is the unit of work Engine is the pool · session is the unit of work RequestService.begin()order + keycommit / rollback The router does not commit. An HTTP charge already sent does not roll back.
Engine is the pool · session is the unit of work
One begin() around order + idempotency + outbox One begin() around order + idempotency + outbox begin()reserve keyinsert order + linesstore responseoutbox rowsame commitPublish after commit. Publish-before-commit creates side effects for a rolled-back order.
One begin() around order + idempotency + outbox
Pool math is per process, not per machine Pool math is per process, not per machine workers × (pool_size + overflow)4 × (5+10) = 60 connectionsPostgres max_connectionsexhaustion → checkout timeout → 503A leaked session (unfinished generator) looks like a 'DB outage'.
Pool math is per process, not per machine

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 order

session.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_timeout
  • pool_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

N+1 — one query for orders, then one per order for lines N+1 — one query for orders, then one per order for lines SELECT ordersthen order.lines in a loopN extra SELECTsserializer / templateselectinload(lines)2 queries, not N+1joinedload can multiply rows. lazy='raised' makes the bug loud in tests.
N+1 — one query for orders, then one per order for lines

python

orders = session.scalars(select(Order)).all()
for order in orders:
    _ = order.lines          # one extra SELECT per order  ← N+1

Fix 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

Optimistic version — UPDATE … WHERE version = :seen Optimistic version — UPDATE … WHERE version = :seen Worker Aread version=3Worker Bread version=3Second UPDATE0 rows → 409A Python Lock is worthless across processes. The WHERE clause is the lock.
Optimistic version — UPDATE … WHERE version = :seen

sql

UPDATE orders SET status = 'CANCELLED', version = version + 1
WHERE id = :id AND version = :seen

Zero rows → 409. A Python Lock is worthless across workers.

Alembic expand / contract

Expand / contract — never rename a live column in one deploy Expand / contract — never rename a live column in one deploy 1 Expandadd column · backfill2 Dual-writeapp reads new, writes both3 Contractstop old · then dropOld and new app versions overlap during a rolling deploy. One ALTER RENAME breaks one of them.
Expand / contract — never rename a live column in one deploy

Never ALTER … RENAME a live column in one deploy if old and new app versions overlap.

  1. Expand — add the new column / table, backfill, dual-write if needed.
  2. Deploy app that reads new, still writes both.
  3. 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

  1. Engine (pool) vs session (UoW).
  2. One begin() around order + idempotency.
  3. Red N+1 arrows; green selectinload.
  4. Expand then contract.
  5. UPDATE … WHERE version = :seen.

Follow-up ladder

  1. Engine vs session? → pool vs unit of work.
  2. Write a 2.x query? → select + scalars.
  3. How do you see N+1? → query count, lazy="raised".
  4. Two workers, last unit? → conditional UPDATE, not a Lock.
  5. 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 selectinload for 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 stale
Cache-aside — DB is truth; cache is a copy with a TTL Cache-aside — DB is truth; cache is a copy with a TTL ReadCache missPostgresSET + TTL Write: commit then delete the key. Do not cache available qty as reservation truth.
Cache-aside — DB is truth; cache is a copy with a TTL
Stampede — many misses rebuild the same key at once Stampede — many misses rebuild the same key at once TTL expires200 workers miss200 DB readsp99 worse after Redissingle-flightlock · jittered TTLFail-open on cache for catalog. Fail-closed on payments.
Stampede — many misses rebuild the same key at once

Read 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 Order aggregate including payment state with a 10-minute TTL. You will ship a paid order as CREATED.

Redis use cases (examples, not a vendor quiz)

Cloud-neutral first: “a cache” / “a key-value store.” Redis is the common example.

UseWhy Redis-shaped
Cache-asideFast get/set/ttl
Rate limitingINCR + EXPIRE
Idempotency *cache*Optional; DB unique key remains the source of truth
Session storeIf you must have server sessions
Leader / lockShort 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

Outbox row commits with the order — then a publisher drains it Outbox row commits with the order — then a publisher drains it Same TXorder + outboxPublisherat-least-onceConsumer inboxeffectively onceExactly-once is a brochure. You build idempotent effects + a unique event id.
Outbox row commits with the order — then a publisher drains it

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 id

Inbox / 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

Queue absorbs spikes — consumer must be idempotent Queue absorbs spikes — consumer must be idempotent APIOutbox / DBBrokerWorkerDLQ BackgroundTasks is in-process and dies with the worker. Not a charge queue.
Queue absorbs spikes — consumer must be idempotent

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 --> inbox

BackgroundTasks 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

  1. Cache-aside arrows; DB as truth.
  2. Invalidate on write; name stale window + stampede.
  3. Outbox in the same commit.
  4. Worker + DLQ + idempotent consumer.
  5. Fail-open cache / fail-closed payments.

Follow-up ladder

  1. When do you cache? → read-heavy, stale-OK.
  2. Cache-aside vs write-through? → aside default.
  3. Why outbox? → atomic write + intent to publish.
  4. Worker saw the event twice? → inbox / idempotent capture.
  5. 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

One correlation id across API, DB, and workers One correlation id across API, DB, and workers X-Correlation-IdLogs JSONMetrics REDTracesNever log Authorization, PAN, or raw request bodies. Redact or omit.
One correlation id across API, DB, and workers
  • Correlation / request id — accept X-Correlation-Id or 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 if safe — otherwise open the circuit Retry only if safe — otherwise open the circuit Retry408 / 429 / 502 / 503timeout + jitterCircuit openfail fast · shed loadDo not retryPOST /charge400 / 401 / 409409 on idempotency conflict is not 'retry with a new key'.
Retry only if safe — otherwise open the circuit
Exponential backoff with jitter — avoid a retry stampede Exponential backoff with jitter — avoid a retry stampede delay = base · 2^k± jittercap + total budgetAlign retries with the caller's timeout. A 30s retry behind a 3s gateway is waste.
Exponential backoff with jitter — avoid a retry stampede

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

Liveness vs readiness — restart vs drain Liveness vs readiness — restart vs drain /health livenessprocess alive? cheap · no DB/ready readinesssafe for traffic? engine + migrationsA DB blip that fails /health will kill-loop the container. That is why they are split.
Liveness vs readiness — restart vs drain
ProbeQuestionFail means
Liveness /healthIs the process alive?Restart the container
Readiness /readyCan 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

Production FastAPI — stateless workers behind a balancer Production FastAPI — stateless workers behind a balancer ClientLBUvicorn procsN loops · N GILsFastAPIDB / cache / QSticky sessions and local disk are smells. Uploads go to object storage.
Production FastAPI — stateless workers behind a balancer

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

  1. Log line with correlation_id, no token.
  2. Retry curve + jitter; “idempotent only.”
  3. /health vs /ready.
  4. Container: env config, non-root, graceful shutdown.
  5. Stateless: no local disk, no sticky sessions.

Follow-up ladder

  1. What do you log on POST /orders? → ids, duration, not bodies.
  2. Why jitter? → desynchronize retries.
  3. Health vs ready? → restart vs drain.
  4. SIGTERM mid-request? → finish or 503; dispose pool.
  5. 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.zip

You 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-Key header)
  • 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 watchThey punish
Pydantic at the HTTP edgeORM model in the request body
Service owns the sessionGlobal session, commit in the router
Idempotent createTwo rows for one retry
Version / constraint on statusBlind last-write-wins
Log order_id + correlation_idSecrets, tokens, or print as product

How to demo

  1. pytest in labs/order-service/
  2. Show the idempotency test: same key, one order
  3. Show conflict when the key is reused with a different body
  4. 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.

LabWhat you doSuccess
order-serviceBuild POST /api/v1/orders with schemas, SQLAlchemy, optimistic locking, idempotent create, transactional outbox write, and testspytest 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]"
pytest

SQLite 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 install so 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]"
pytest

Tests 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 src

Or the containerized API (SQLite inside the image):

bash

docker compose up --build api

The image runs as a non-root user. Health checks hit GET /health.

API

MethodPathNotes
POST/api/v1/ordersRequires Idempotency-Key. Same key + body replays the first order.
GET/api/v1/orders/{order_id}404 when missing
GET/api/v1/orderspage / size, optional customer_id and status
PATCH/api/v1/orders/{order_id}/statusIf-Match or body version → 409 on stale version
DELETE/api/v1/orders/{order_id}Soft cancel (status=CANCELLED). Row is kept.
GET/healthLiveness
GET/readyReadiness (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.version starts at 0. If-Match or

{"version": N} must match; mismatch is 409 OPTIMISTIC_LOCK_CONFLICT.

  • Outbox: outbox_events is 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

Client → Order API → DB + outbox → broker → workers Client → Order API → DB + outbox → broker → workers ClientOrder APIOrders DBOutboxWorkersDo not deploy a second service to finish the sprint. pytest on SQLite is the bar.
Client → Order API → Orders DB + outbox → broker → workers. Lab scope is the sync accept path.
Order service — accept path vs after-commit story Order service — accept path vs after-commit story FastAPIPostgresOutboxWorkersLab scope is the sync accept path. Broker and workers are the story after commit.
Order service — accept path vs after-commit story
Request hits middleware, Depends, then the route Request hits middleware, Depends, then the route ClientMiddlewareDependsRoutemodel_dump response_model is the contract filter if you accidentally return an ORM row.
Router takes models. Service owns the transaction. Repository talks SQL.
Router / service / repository — entity stays in persistence Router / service / repository — entity stays in persistence API / schemascommand in · view outServicetx · domain · portsRepositorySQLAlchemy only Interview line: the mapped Order never is the public JSON contract.
Router / service / repository
Idempotency-Key lives in the same commit as the order Idempotency-Key lives in the same commit as the order ClientIdempotency-Key+ bodyHash bodycanonical JSONSame TXorder + key rowReplaystored 201 Same key, different hash → 409. Unique constraint is the correctness mechanism.In-memory maps die across uvicorn workers. The table is the source of truth.
Idempotency-Key is stored in the same transaction as the order.
Two in-flight creates with the same key Two in-flight creates with the same key Worker A inserts keyWorker B unique failB reads A's rowsame hash → 201The unique index, not a Python Lock, serializes the race.
Two in-flight creates with the same key
Optimistic version — UPDATE … WHERE version = :seen Optimistic version — UPDATE … WHERE version = :seen Worker Aread version=3Worker Bread version=3Second UPDATE0 rows → 409A Python Lock is worthless across processes. The WHERE clause is the lock.
Optimistic version — UPDATE … WHERE version = :seen

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:

  1. POST /orders (or /api/v1/orders) accepts a JSON command (customer, lines, optional currency).
  2. Pydantic on the request; one error envelope for 400/409/422 and domain errors.
  3. OrderService is constructed via Depends; it owns the session / begin().
  4. Persist Order + OrderLine. Do not return mapped objects as the public contract — use a response model.
  5. Idempotent create via Idempotency-Key stored uniquely with a body hash.
  6. Optimistic version on status changes (version column).
  7. After commit, publish OrderCreated (in-process or outbox row).
  8. Log correlation_id + order_id on accept and reject. No secrets.
  9. 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

  1. Router / service / repository. Row never enters the router as the API type.
  2. Key store + order row, one commit. Replay vs 409.
  3. version on PATCH status.
  4. 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 (plus rejects 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 outbox

Settings 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]"
pytest

Use 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

Client → Order API → DB + outbox → broker → workers Client → Order API → DB + outbox → broker → workers ClientOrder APIOrders DBOutboxWorkersDo not deploy a second service to finish the sprint. pytest on SQLite is the bar.
Client → Order API → Orders DB + outbox → broker → workers. Lab scope is the sync accept path.
Order service — accept path vs after-commit story Order service — accept path vs after-commit story FastAPIPostgresOutboxWorkersLab scope is the sync accept path. Broker and workers are the story after commit.
Order service — accept path vs after-commit story
Request hits middleware, Depends, then the route Request hits middleware, Depends, then the route ClientMiddlewareDependsRoutemodel_dump response_model is the contract filter if you accidentally return an ORM row.
Router takes models. Service owns the transaction. Repository talks SQL.
Router / service / repository — entity stays in persistence Router / service / repository — entity stays in persistence API / schemascommand in · view outServicetx · domain · portsRepositorySQLAlchemy only Interview line: the mapped Order never is the public JSON contract.
Router / service / repository
Idempotency-Key lives in the same commit as the order Idempotency-Key lives in the same commit as the order ClientIdempotency-Key+ bodyHash bodycanonical JSONSame TXorder + key rowReplaystored 201 Same key, different hash → 409. Unique constraint is the correctness mechanism.In-memory maps die across uvicorn workers. The table is the source of truth.
Idempotency-Key is stored in the same transaction as the order.
Two in-flight creates with the same key Two in-flight creates with the same key Worker A inserts keyWorker B unique failB reads A's rowsame hash → 201The unique index, not a Python Lock, serializes the race.
Two in-flight creates with the same key
Optimistic version — UPDATE … WHERE version = :seen Optimistic version — UPDATE … WHERE version = :seen Worker Aread version=3Worker Bread version=3Second UPDATE0 rows → 409A Python Lock is worthless across processes. The WHERE clause is the lock.
Optimistic version — UPDATE … WHERE version = :seen

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:

  1. POST /orders (or /api/v1/orders) accepts a JSON command (customer, lines, optional currency).
  2. Pydantic on the request; one error envelope for 400/409/422 and domain errors.
  3. OrderService is constructed via Depends; it owns the session / begin().
  4. Persist Order + OrderLine. Do not return mapped objects as the public contract — use a response model.
  5. Idempotent create via Idempotency-Key stored uniquely with a body hash.
  6. Optimistic version on status changes (version column).
  7. After commit, publish OrderCreated (in-process or outbox row).
  8. Log correlation_id + order_id on accept and reject. No secrets.
  9. 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

  1. Router / service / repository. Row never enters the router as the API type.
  2. Key store + order row, one commit. Replay vs 409.
  3. version on PATCH status.
  4. 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 (plus rejects 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 outbox

Settings 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]"
pytest

Use 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 install so 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]"
pytest

Tests 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 src

Or the containerized API (SQLite inside the image):

bash

docker compose up --build api

The image runs as a non-root user. Health checks hit GET /health.

API

MethodPathNotes
POST/api/v1/ordersRequires Idempotency-Key. Same key + body replays the first order.
GET/api/v1/orders/{order_id}404 when missing
GET/api/v1/orderspage / size, optional customer_id and status
PATCH/api/v1/orders/{order_id}/statusIf-Match or body version → 409 on stale version
DELETE/api/v1/orders/{order_id}Soft cancel (status=CANCELLED). Row is kept.
GET/healthLiveness
GET/readyReadiness (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.version starts at 0. If-Match or

{"version": N} must match; mismatch is 409 OPTIMISTIC_LOCK_CONFLICT.

  • Outbox: outbox_events is 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 install so 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]"
pytest

Tests 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 src

Or the containerized API (SQLite inside the image):

bash

docker compose up --build api

The image runs as a non-root user. Health checks hit GET /health.

API

MethodPathNotes
POST/api/v1/ordersRequires Idempotency-Key. Same key + body replays the first order.
GET/api/v1/orders/{order_id}404 when missing
GET/api/v1/orderspage / size, optional customer_id and status
PATCH/api/v1/orders/{order_id}/statusIf-Match or body version → 409 on stale version
DELETE/api/v1/orders/{order_id}Soft cancel (status=CANCELLED). Row is kept.
GET/healthLiveness
GET/readyReadiness (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.version starts at 0. If-Match or

{"version": N} must match; mismatch is 409 OPTIMISTIC_LOCK_CONFLICT.

  • Outbox: outbox_events is 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.

LabWhat you doSuccess
order-serviceBuild POST /api/v1/orders with schemas, SQLAlchemy, optimistic locking, idempotent create, transactional outbox write, and testspytest 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]"
pytest

SQLite 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 install so 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]"
pytest

Tests 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 src

Or the containerized API (SQLite inside the image):

bash

docker compose up --build api

The image runs as a non-root user. Health checks hit GET /health.

API

MethodPathNotes
POST/api/v1/ordersRequires Idempotency-Key. Same key + body replays the first order.
GET/api/v1/orders/{order_id}404 when missing
GET/api/v1/orderspage / size, optional customer_id and status
PATCH/api/v1/orders/{order_id}/statusIf-Match or body version → 409 on stale version
DELETE/api/v1/orders/{order_id}Soft cancel (status=CANCELLED). Row is kept.
GET/healthLiveness
GET/readyReadiness (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.version starts at 0. If-Match or

{"version": N} must match; mismatch is 409 OPTIMISTIC_LOCK_CONFLICT.

  • Outbox: outbox_events is 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

Client → Order API → DB + outbox → broker → workers Client → Order API → DB + outbox → broker → workers ClientOrder APIOrders DBOutboxWorkersDo not deploy a second service to finish the sprint. pytest on SQLite is the bar.
Client → Order API → Orders DB + outbox → broker → workers. Lab scope is the sync accept path.
Order service — accept path vs after-commit story Order service — accept path vs after-commit story FastAPIPostgresOutboxWorkersLab scope is the sync accept path. Broker and workers are the story after commit.
Order service — accept path vs after-commit story
Request hits middleware, Depends, then the route Request hits middleware, Depends, then the route ClientMiddlewareDependsRoutemodel_dump response_model is the contract filter if you accidentally return an ORM row.
Router takes models. Service owns the transaction. Repository talks SQL.
Router / service / repository — entity stays in persistence Router / service / repository — entity stays in persistence API / schemascommand in · view outServicetx · domain · portsRepositorySQLAlchemy only Interview line: the mapped Order never is the public JSON contract.
Router / service / repository
Idempotency-Key lives in the same commit as the order Idempotency-Key lives in the same commit as the order ClientIdempotency-Key+ bodyHash bodycanonical JSONSame TXorder + key rowReplaystored 201 Same key, different hash → 409. Unique constraint is the correctness mechanism.In-memory maps die across uvicorn workers. The table is the source of truth.
Idempotency-Key is stored in the same transaction as the order.
Two in-flight creates with the same key Two in-flight creates with the same key Worker A inserts keyWorker B unique failB reads A's rowsame hash → 201The unique index, not a Python Lock, serializes the race.
Two in-flight creates with the same key
Optimistic version — UPDATE … WHERE version = :seen Optimistic version — UPDATE … WHERE version = :seen Worker Aread version=3Worker Bread version=3Second UPDATE0 rows → 409A Python Lock is worthless across processes. The WHERE clause is the lock.
Optimistic version — UPDATE … WHERE version = :seen

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:

  1. POST /orders (or /api/v1/orders) accepts a JSON command (customer, lines, optional currency).
  2. Pydantic on the request; one error envelope for 400/409/422 and domain errors.
  3. OrderService is constructed via Depends; it owns the session / begin().
  4. Persist Order + OrderLine. Do not return mapped objects as the public contract — use a response model.
  5. Idempotent create via Idempotency-Key stored uniquely with a body hash.
  6. Optimistic version on status changes (version column).
  7. After commit, publish OrderCreated (in-process or outbox row).
  8. Log correlation_id + order_id on accept and reject. No secrets.
  9. 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

  1. Router / service / repository. Row never enters the router as the API type.
  2. Key store + order row, one commit. Replay vs 409.
  3. version on PATCH status.
  4. 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 (plus rejects 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 outbox

Settings 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]"
pytest

Use 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:

ModeWho
PYTHON_BACKEND_ENGINEERCorrect code, structures, basic FastAPI
SENIOR_PYTHON_BACKEND_ENGINEERTransactions, N+1, asyncio, idempotency, tests
LEAD_PYTHON_BACKEND_ENGINEEROwnership, 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-offs

The 45-minute form trims production to one follow-up and shortens probes. Same opening sentence.

During the coding block

  1. Repeat the prompt in one sentence (POST /orders must not double-create).
  2. Write types and the sad path (missing key, empty lines, qty <= 0).
  3. Implement the happy path.
  4. Narrate the test you would add.
  5. 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
  • is vs ==
  • GIL — and do not say Python cannot do concurrency
  • time.sleep vs asyncio.sleep
  • Depends vs 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):

DimensionWeight
Core Python12%
Pythonic Coding8%
Async / Concurrency12%
FastAPI14%
API / Data12%
Coding Quality12%
Testing / Debugging8%
Production Engineering10%
Architecture / Trade-offs7%
Communication5%

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:

  1. What you would keep
  2. The first follow-up that hurt
  3. 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

ProfileMock modeWhat gets heavier
ENGINEERPYTHON_BACKEND_ENGINEERCorrect code, structures, basic FastAPI
SENIOR_ENGINEERSENIOR_PYTHON_BACKEND_ENGINEERTransactions, N+1, asyncio, idempotency, testing
LEAD_STAFFLEAD_PYTHON_BACKEND_ENGINEEROwnership, 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-offs

Open 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 Fundamentalsis vs ==, tuple caveatRewrite the types table from memory
Pythonic CodingMutable default / wrong structureTeach the decision table out loud
Advanced PythonDecorators without wrapsWrite one timed decorator + generator
Async & ConcurrencyGIL slogan / time.sleepDraw the matrix; fix one async handler
FastAPIGlobals instead of DependsRebuild the dependency graph
REST/API Design200-with-errorRecite statuses + error envelope
Data/PersistenceN+1 / session leakCount queries on a list endpoint
Testing“I would test it”Write three TestClient names
Production ReadinessRetry / secrets / probesWrite 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

  1. 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.”
  2. One coding kata — Money, idempotency handler, or bounded gather. Timebox 15 minutes.
  3. 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?
  • is vs == — when is is correct?
  • Can Python do concurrency? (Yes. Walk the GIL matrix.)
  • time.sleep in async def — what dies?
  • Why two Pydantic models?
  • Engine vs session?
  • How do you see and fix N+1?
  • How is POST /orders idempotent 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

$49

Small group

$119

Live 1:1

$349

Introductory $299

Book Your Interview Sprint

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

Log in or enroll to request a live session time.