More in Backend Dev — page 23
Write an async decorator that logs execution time for FastAPI
TESTS: Python closures, async/await, and decorator stacking in FastAPI. OUTLINE: use functools.wraps, wrap perf_counter around awaited call, log ms, and place decorator above path operation. RED FLAG: forgetting to await the coroutine or omitting wraps.

How does FastAPI leverage Pydantic for request validation and serialization?
This tests your understanding of FastAPI's declarative validation. Explain that type hints trigger auto-parsing, Pydantic enforces schemas and errors, and return types auto-serialize responses. Red flag: manually parsing request.body() or json.loads in routes.

What is the difference between def and async def in Python and FastAPI?
Tests event-loop boundaries: async def yields control via await for non-blocking I/O, def runs in a threadpool. Use async def only with async libraries; def covers blocking calls. Red flag: claiming async is automatically faster or awaiting inside def.

Explain Python type hints and their importance in FastAPI
WHAT IT TESTS: If you know FastAPI uses type hints for validation and docs. ANSWER OUTLINE: Define hints as declarations; explain FastAPI uses them with Pydantic to validate requests and OpenAPI docs. RED FLAG: Seeing hints as IDE-only.
Docker Compose for Local FastAPI Stacks
Docker Compose turns your laptop into a one-command datacenter. Define Postgres, Redis, and your FastAPI app in one YAML file and they boot as a networked stack.
Custom Field Serialization with @field_serializer
@field_serializer is an exit-only adapter for one field: it reshapes data leaving the Pydantic model without changing internals. Use it to format decimals, mask secrets, or tweak datetimes for FastAPI JSON. Never use it for validation; it only runs on output.
Per-Field Validation with @field_validator
@field_validator scrubs a single Pydantic field before it enters the model. Use it for rules like 'password must contain a digit' or 'port must exceed 1024'. It only sees one field at a time, so cross-field checks belong in a model validator instead.
Serialize Pydantic Models with model_dump
model_dump turns a Pydantic model into a plain Python dict, bridging typed objects and JSON serializers in FastAPI endpoints. Call it when you need raw data before returning a response. Do not confuse it with model_dump_json, which emits a string, not a dict.

FastAPI Container Build and Deploy Pipeline
Treat the Docker image as the immutable artifact: one build runs everywhere. Deploy FastAPI workers behind a load balancer, one process per container. The footgun is baking secrets into the image or running multiple processes; that breaks horizontal scaling.
Overriding FastAPI's OpenAPI Generator
FastAPI lets you swap app.openapi to reshape its generated schema without forking. Use this for vendor extensions, filtered operations, or merging external schemas. Forgetting to cache the result means every docs request rebuilds it and destroys performance.
Testing FastAPI Lifespan Events
FastAPI lifespan events only run when TestClient is used as a context manager. Use this to test startup logic like DB pools before endpoints. Using TestClient(app) without with skips lifespan, leaving your app uninitialized and tests silently wrong.
JWT: Signed JSON Claim Tokens
A JWT is a signed JSON envelope: it carries claim assertions in JSON, optionally encrypted, and proves who wrote it using either a private secret or a public/private key. Do not treat the payload as hidden unless encryption is actually enabled.

Async Path Operations in FastAPI
FastAPI path operations can be async, letting the server switch to other requests during I/O waits. Declare dependencies and sub-dependencies async when they await external calls.

Python Async Context Managers
Async context managers let you await during setup and teardown. Use async with for database connections or streams where acquiring and releasing both need I/O. The footgun is applying @contextmanager to async cleanup, which cannot await and will crash.
How does Node.js handle thousands of connections on one thread?
This tests non-blocking I/O: Node.js runs one thread for an event loop while the OS handles sockets via epoll or IOCP, resuming callbacks when data arrives. Mention the thread pool for DNS and fs work. A red flag is claiming threads spawn per request.
express-validator: Validate at the Edge
express-validator stops garbage before it hits your logic. Use it on any route that accepts user input like form data, query strings, or JSON payloads. The biggest mistake is validating but forgetting to check validationResult, so invalid requests pass.
Operational vs Programmer Errors in Node
Operational errors are expected problems like a failed network request; programmer errors are bugs like reading undefined. Handle the first gracefully, crash the second. The footgun is catching programmer errors and continuing, which corrupts process state.
Validation Checks Rules; Sanitization Cleans Input
Validation checks if input fits your rules and rejects failures. Sanitization cleans allowed input so it cannot cause harm. Validate at the boundary to enforce shape, then sanitize before rendering. Never swap them; scrubbing a bad date does not make it valid.
Bcrypt: Hash Passwords with Salt and Slowness
Bcrypt salts and slows every password hash so identical passwords never look the same and brute force stays expensive. Use it in register and login routes before the database. Never compare hashes with plain string equality; always call bcrypt.compare().
MongoDB Aggregation Pipeline: Server-Side Assembly Line
MongoDB's aggregation pipeline reshapes documents stage by stage on the server. Use it for reports, joins, or analytics without pulling whole collections into your app. Running $sort or $group before $match scans excess documents and kills performance.