Lesson 17 of 32Question banks
Backend and Web Questions
Answer the common backend questions on HTTP, auth, databases, caching, and deployment with clear trade-offs.
Backend and full-stack interviews include a block of rapid-fire questions: "What does 409 mean?", "Sessions or JWTs?", "What is an N+1 query?". Each one has a short, standard answer, and missing them signals you have not shipped a real API. This lesson covers the ones you are most likely to hear, grouped by topic, each with the trade-off that makes an answer sound experienced.
HTTP and APIs
"REST vs GraphQL?" REST exposes resources at URLs (GET /users/42) and uses HTTP methods and status codes; it is simple, cacheable by HTTP caches and CDNs, and the default for most APIs. GraphQL exposes one endpoint where the client sends a query describing exactly the fields it wants; it avoids over-fetching and multiple round trips for complex UIs, but needs more server work (resolvers, query cost limits, harder HTTP caching, N+1 risks). Choose REST by default; GraphQL when many clients need very different shapes of deeply related data.
| Code | Meaning | Typical use |
|---|---|---|
200 OK | Success with a body | GET, or an update that returns data |
201 Created | A resource was created | POST that creates, with a Location header |
204 No Content | Success, no body | DELETE |
301 / 302 / 304 | Moved permanently / found / not modified | Redirects; 304 for cache revalidation |
400 Bad Request | Malformed request | Invalid JSON |
401 Unauthorized | Not authenticated | Missing or invalid token |
403 Forbidden | Authenticated but not allowed | Wrong role |
404 Not Found | No such resource | Unknown ID |
409 Conflict | Clashes with current state | Duplicate email, version conflict |
422 Unprocessable Content | Valid syntax, invalid data | FastAPI validation errors |
429 Too Many Requests | Rate limited | With a Retry-After header |
500 / 502 / 503 | Server bug / bad upstream / unavailable | Errors on your side |
DELETE /projects/7, which needs 'admin'. Which status should the API return?"What is idempotency?" An operation is idempotent if doing it once or many times leaves the server in the same state. GET, PUT, and DELETE are idempotent by definition; POST is not (two POSTs create two orders). It matters because networks retry: a client that times out does not know whether the request landed. For non-idempotent operations like payments, clients send an idempotency key header; the server stores the key with the result and returns the stored result on a retry.
Press Run (⌘ Enter) to see what happens.What happens when you type a URL
This is one of the most common open-ended questions. Go in order and say one sentence per step; the interviewer will ask you to go deeper where they care.
The browser checks its caches, then asks a DNS resolver, which walks root, .com, and the domain's name servers.
Put these steps in order for a first visit to an HTTPS site.
- Tap the steps below in the right order.
Auth and the browser
Model answer: sessions vs JWT
With sessions, the server stores session data (in memory, Redis, or a database) and the browser holds only a random session ID in a cookie. Revoking is easy (delete the session), but every request needs a lookup. With a JWT, the server signs a token containing the claims (user ID, expiry); any server can verify it with the key and no lookup, which suits multiple services. The downside is revocation: a JWT is valid until it expires, so use short-lived access tokens (minutes) plus a refresh token you can revoke. For browser apps, store tokens in HttpOnly, Secure, SameSite cookies, not localStorage, to keep them away from injected scripts.
Model answer: CORS
Browsers enforce the same-origin policy: a page from one origin (scheme + host + port) cannot read responses from another. CORS (Cross-Origin Resource Sharing) is how a server opts in: it returns headers like Access-Control-Allow-Origin: https://app.example.com. For non-simple requests (custom headers, PUT, JSON bodies) the browser first sends an OPTIONS preflight to ask permission. CORS is enforced by the browser, not the server, so it does not protect an API from curl or other servers; it protects users' browsers.
Model answer: WebSockets
HTTP is request/response: the client asks, the server answers. A WebSocket upgrades an HTTP connection into a long-lived, two-way channel where either side can send messages at any time. Use it for chat, live collaboration, multiplayer games, and live dashboards. Alternatives: Server-Sent Events for one-way server-to-client streams (simpler, plain HTTP), or polling for low-frequency updates. WebSockets are stateful, so scaling needs sticky connections or a pub/sub layer (like Redis) to fan messages out across servers.
Databases
"SQL or NoSQL?" SQL (relational) databases like Postgres store data in tables with a fixed schema, support joins and ACID transactions, and are the right default for most apps. NoSQL covers several models: document (MongoDB), key-value (Redis, DynamoDB), wide-column (Cassandra), and graph. They trade joins and some consistency for flexible schemas, simple horizontal scaling, or very high write throughput. A strong answer starts from the access pattern, not from fashion.
"What does ACID mean?" Atomicity: a transaction fully happens or not at all. Consistency: constraints (foreign keys, uniqueness) always hold. Isolation: concurrent transactions do not see each other's half-finished work. Durability: once committed, data survives a crash (it is in the write-ahead log).
"How does an index work?" Most database indexes are B-trees: a sorted, balanced tree of column values pointing to rows. A lookup becomes O(log n) instead of scanning every row. The cost: extra storage and slower writes, because every insert and update must update each index. Index columns you filter, join, or sort on; check with EXPLAIN ANALYZE.
Caching and rate limiting
"Where would you cache, and how do you keep it fresh?" Caches live at many layers: the browser (Cache-Control headers), a CDN for static files and public pages, an app-level cache like Redis for expensive queries, and the database's own buffer cache. The common app pattern is cache-aside: read from the cache, on a miss read the database and fill the cache with a TTL. Freshness comes from a TTL (time to live), deleting the key on writes, or both. The hard part is invalidation; say which stale window you can accept.
"How would you rate limit an API?" The token bucket is the standard answer: each client has a bucket that refills at a steady rate up to a maximum; each request takes a token; an empty bucket means 429. It allows short bursts while capping the average. In production the counters live in Redis so all app servers share them.
Press Run (⌘ Enter) to see what happens.What does this print?
tokens = 2.0
rate = 1.0
last = 0.0
for now in [0, 0, 0, 2]:
tokens = min(2, tokens + (now - last) * rate)
last = now
if tokens >= 1:
tokens -= 1
print("ok")
else:
print("429")Deployment
Model answer: Docker vs a virtual machine
A VM virtualises hardware: each VM runs a full guest operating system on a hypervisor, so it is strongly isolated but heavy (gigabytes, boots in tens of seconds). A container shares the host's Linux kernel and isolates only the process, filesystem, and network with namespaces and cgroups, so it is light (megabytes, starts in about a second). Docker packages an app with its dependencies into an image that runs the same everywhere. In the cloud, containers usually run inside VMs.
Model answer: CI/CD
Continuous integration runs automated checks (lint, type check, tests, build) on every push and pull request, so broken code is caught before merging. Continuous delivery/deployment automatically builds and ships passing changes to staging or production. A typical pipeline in GitHub Actions: install dependencies, lint, test, build a Docker image, push it to a registry, deploy, then run a smoke test. Strong answers mention fast feedback (tests in minutes) and safe rollouts (preview environments, rollbacks, feature flags).
FastAPI specifics
Model answer: Depends, Pydantic, and async in FastAPI
Dependsis FastAPI's dependency injection: a parameter likedb: Session = Depends(get_db)tells FastAPI to callget_dbper request and pass the result. Dependencies can depend on others, canyieldto run cleanup after the response (closing a DB session), and are easy to override in tests withapp.dependency_overrides.- Pydantic v2 models define request and response shapes with type hints. FastAPI validates incoming JSON against them (returning
422with details on failure), serialises responses throughresponse_model, and generates the OpenAPI docs at/docsfrom them. async defvsdef: FastAPI runsasync defendpoints on the event loop, so they must onlyawaitnon-blocking calls (async DB drivers,httpx.AsyncClient). Plaindefendpoints run in a thread pool, so blocking libraries are safe there. Calling a blocking function insideasync deffreezes every request on that worker.
Match the question to the core of a good answer.
- idempotent
- Repeating the operation leaves the server in the same state as doing it once.
- CORS
- Headers a server sends to let browsers on other origins read its responses.
- ACID
- Atomicity, consistency, isolation, durability: the guarantees of a database transaction.
- N+1 problem
- One query for a list plus one per item; fixed with a join or eager loading.
- token bucket
- A rate-limiting algorithm: tokens refill at a steady rate and each request spends one.
- cache-aside
- Read the cache first; on a miss, read the database and store the result with a TTL.