Skip to content

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.

22 min read0/5 questions

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.

CodeMeaningTypical use
200 OKSuccess with a bodyGET, or an update that returns data
201 CreatedA resource was createdPOST that creates, with a Location header
204 No ContentSuccess, no bodyDELETE
301 / 302 / 304Moved permanently / found / not modifiedRedirects; 304 for cache revalidation
400 Bad RequestMalformed requestInvalid JSON
401 UnauthorizedNot authenticatedMissing or invalid token
403 ForbiddenAuthenticated but not allowedWrong role
404 Not FoundNo such resourceUnknown ID
409 ConflictClashes with current stateDuplicate email, version conflict
422 Unprocessable ContentValid syntax, invalid dataFastAPI validation errors
429 Too Many RequestsRate limitedWith a Retry-After header
500 / 502 / 503Server bug / bad upstream / unavailableErrors on your side
Quick check
A logged-in user with the 'viewer' role calls DELETE /projects/7, which needs 'admin'. Which status should the API return?
Need a nudge? A hint rules out a wrong answer.

"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.

Pythonidempotency.py
processed: dict[str, dict] = {} # idempotency key -> stored responsebalance = 100 def charge(key: str, amount: int) -> dict: global balance if key in processed: # a retry: return the original result return processed[key] balance -= amount result = {"status": "charged", "amount": amount, "balance": balance} processed[key] = result return result print(charge("order-81", 30))print(charge("order-81", 30)) # network retry: no double chargeprint("final balance:", balance)
Output
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.

Loading https://example.com
BrowserDNS resolverCDN / serverAppWhere is example.com?93.184.215.14TCP + TLS handshakeGET / (HTTP/2)cache miss: forward200 HTML200 HTML

The browser checks its caches, then asks a DNS resolver, which walks root, .com, and the domain's name servers.

1/7
Put it in order6 steps

Put these steps in order for a first visit to an HTTPS site.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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.

Quick check
An endpoint lists 50 blog posts and shows each post's author name. The logs show 51 SQL queries. What is this, and what fixes it?
Need a nudge? A hint rules out a wrong answer.

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.

Pythontoken_bucket.py
class TokenBucket: def __init__(self, capacity: int, refill_per_sec: float): self.capacity = capacity self.tokens = float(capacity) self.rate = refill_per_sec self.last = 0.0 def allow(self, now: float) -> bool: self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate) self.last = now if self.tokens >= 1: self.tokens -= 1 return True return False bucket = TokenBucket(capacity=3, refill_per_sec=1)for t in [0, 0, 0, 0, 0.5, 1.0, 3.0]: print(f"t={t}: {'allowed' if bucket.allow(t) else '429'}")
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

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")
Need a nudge? Hints walk you through it.

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
  • Depends is FastAPI's dependency injection: a parameter like db: Session = Depends(get_db) tells FastAPI to call get_db per request and pass the result. Dependencies can depend on others, can yield to run cleanup after the response (closing a DB session), and are easy to override in tests with app.dependency_overrides.
  • Pydantic v2 models define request and response shapes with type hints. FastAPI validates incoming JSON against them (returning 422 with details on failure), serialises responses through response_model, and generates the OpenAPI docs at /docs from them.
  • async def vs def: FastAPI runs async def endpoints on the event loop, so they must only await non-blocking calls (async DB drivers, httpx.AsyncClient). Plain def endpoints run in a thread pool, so blocking libraries are safe there. Calling a blocking function inside async def freezes every request on that worker.
Match the pairs0/5 matched

Match the question to the core of a good answer.

Choose an item, then its match on the other side.
Key terms
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.