Skip to content

PUBLIC QUESTION PREVIEW

Backend & APIs interview questions

REST design, auth, Node.js, microservices, message queues, rate limiting.

Showing 12 of 30 source questions. Sample answers are study material, not employer-specific hiring guidance.

How to work through this preview

Attempt each question before reading its answer. For a concept, give a definition and a concrete example. For code, state constraints, walk through a small input, and check complexity. For design, separate requirements from assumptions and explain failure handling. Use real situations for behavioral answers.

QUESTION 1 / easy / conceptual

What is the difference between authentication and authorization?

Sample answer

Authentication (AuthN): verifying identity. "Who are you?" — logging in with email/password, Google OAuth, biometrics. Authorization (AuthZ): verifying permissions. "What are you allowed to do?" — RBAC (role-based), can this user delete this resource? They're always separate concerns. A user can be authenticated (logged in) but not authorized (doesn't have admin role). A JWT token authenticates you; the route middleware checks if your role authorizes the action.

Hints to guide your next attempt

  • AuthN = who are you? AuthZ = what can you do?

Source tags: auth / authentication / authorization / security / jwt

QUESTION 2 / easy / conceptual

What is REST? What makes an API truly RESTful?

Sample answer

REST (Representational State Transfer) is an architectural style for distributed systems. Key constraints: 1. Stateless: each request has all info needed; server holds no session state 2. Uniform interface: standard HTTP methods (GET/POST/PUT/DELETE/PATCH), nouns as URLs (/users/123), self-descriptive messages 3. Client-server separation: UI and data storage are independent 4. Cacheable: responses should indicate cacheability 5. Layered system: client doesn't know if it's talking to origin or a proxy Most "REST" APIs are really just HTTP APIs. True REST requires HATEOAS (responses include links to related actions) — rarely implemented in practice.

Hints to guide your next attempt

  • 6 constraints: stateless, client-server, cacheable, uniform interface, layered system, code-on-demand

Source tags: rest / api / http / stateless

QUESTION 3 / medium / conceptual

What is JWT? How does token-based auth work? What are the security risks?

Sample answer

JWT = JSON Web Token. Three base64-encoded parts: Header (algo), Payload (claims), Signature. Flow: login → server issues JWT signed with secret → client stores it (httpOnly cookie or memory) → sends in Authorization: Bearer header → server verifies signature (no DB lookup needed). Security risks: - Algorithm confusion: always explicitly specify algorithm server-side, reject "none" - Storing in localStorage: vulnerable to XSS — prefer httpOnly cookies - No revocation: JWTs are valid until expiry — can't invalidate on logout without a denylist - Signature ≠ encryption: payload is readable — never put sensitive data in payload - Short expiry + refresh token rotation is best practice

Hints to guide your next attempt

  • Header.Payload.Signature — what does each part do?
  • JWT is signed, not encrypted

Source tags: jwt / authentication / token / security / backend

QUESTION 4 / easy / conceptual

Explain HTTP methods: GET, POST, PUT, PATCH, DELETE. What is idempotency?

Sample answer

GET: retrieve a resource. No body. Safe (no side effects) + idempotent. POST: create a new resource or trigger an action. Has body. NOT idempotent — calling twice creates two records. PUT: replace an entire resource. Idempotent — calling twice results in the same state. PATCH: partially update a resource. Not necessarily idempotent (depends on implementation). DELETE: remove a resource. Idempotent — deleting an already-deleted resource is still "deleted". Idempotency: f(f(x)) = f(x). Calling the same operation multiple times produces the same result. Critical for: payment APIs, retry logic. POST /orders should have an idempotency key header to prevent double charges on network retries. Safe methods: GET, HEAD, OPTIONS — no server state change. Unsafe methods: POST, PUT, PATCH, DELETE — modify state. REST URL conventions: GET /orders → list orders GET /orders/123 → get order 123 POST /orders → create order PUT /orders/123 → replace order 123 PATCH /orders/123 → update fields of order 123 DELETE /orders/123 → delete order 123

Hints to guide your next attempt

  • Idempotent = calling N times has same effect as calling once
  • GET/PUT/DELETE are idempotent, POST is not

Source tags: http-methods / rest / idempotency / api / backend

QUESTION 5 / easy / conceptual

What are common HTTP status codes? What does each range mean?

Sample answer

2xx — Success: 200 OK: successful request 201 Created: resource created (POST response, include Location header) 204 No Content: success with no body (DELETE response) 3xx — Redirects: 301 Moved Permanently: resource permanently moved (browser caches redirect) 302 Found: temporary redirect 304 Not Modified: cached version is still valid (used with ETags) 4xx — Client Errors: 400 Bad Request: malformed request, validation failed 401 Unauthorized: not authenticated (confusingly named — no valid token) 403 Forbidden: authenticated but not authorized 404 Not Found: resource doesn't exist 409 Conflict: state conflict (duplicate creation, version mismatch) 422 Unprocessable Entity: request valid but semantically wrong (invalid email format) 429 Too Many Requests: rate limit exceeded 5xx — Server Errors: 500 Internal Server Error: unhandled exception — never expose stack traces 502 Bad Gateway: upstream service error 503 Service Unavailable: server overloaded or down 504 Gateway Timeout: upstream service didn't respond in time Best practice: return specific codes, not just 200/500 for everything.

Hints to guide your next attempt

  • 2xx success, 3xx redirect, 4xx client error, 5xx server error

Source tags: http-status / rest / api / 200 / 404 / 500 / backend

QUESTION 6 / medium / conceptual

What is CORS? Why does it exist and how do you configure it correctly?

Sample answer

CORS (Cross-Origin Resource Sharing): a browser security mechanism that restricts web pages from making requests to a different domain than the one that served the page. Same-Origin Policy: browser blocks JS on https://app.com from fetching https://api.com — different origin (domain/port/protocol). CORS lets the server say "I allow requests from https://app.com". How it works: 1. Simple requests (GET/POST with basic headers): browser sends the request with Origin header. Server responds with Access-Control-Allow-Origin: https://app.com — browser allows it. 2. Preflight (for PUT/PATCH/DELETE or custom headers): browser first sends OPTIONS request. Server responds with what methods/headers are allowed. Then browser sends actual request. Key response headers: Access-Control-Allow-Origin: https://app.com (or * for public APIs) Access-Control-Allow-Methods: GET, POST, PUT, DELETE Access-Control-Allow-Headers: Content-Type, Authorization Access-Control-Allow-Credentials: true (required if sending cookies) Express/Node.js (using cors package): app.use(cors({ origin: 'https://app.com', credentials: true })); Security: never use Access-Control-Allow-Origin: * with credentials: true — browser blocks this. Always specify exact origins for APIs that handle auth.

Hints to guide your next attempt

  • Same-Origin Policy is the browser restriction CORS relaxes
  • Preflight OPTIONS request

Source tags: cors / same-origin-policy / preflight / security / backend

QUESTION 7 / medium / conceptual

What are different API versioning strategies? What are the trade-offs of each?

Sample answer

1. URL path versioning (most common): /v1/users, /v2/users Pros: explicit, easy to test in browser, visible in logs Cons: URL should identify resources not versions; can lead to duplication 2. Query parameter: /users?version=2 Pros: optional, backward compatible Cons: not RESTful, easy to forget, caching issues 3. Request header: Version: 2 or Accept: application/vnd.myapi.v2+json Pros: clean URLs, RESTful purists prefer it Cons: harder to test, less visible, clients must remember to set header 4. Subdomain: v2.api.myapp.com Pros: complete separation Cons: DNS/SSL overhead, complex routing Best practices: - Maintain backward compatibility as long as possible — avoid breaking changes - Deprecation policy: announce sunset date in headers (Sunset: Sat, 31 Dec 2025 23:59:59 GMT) - Version at the API level, not per-endpoint if possible - URL versioning is the pragmatic choice for most teams — /v1/ for all public APIs Internal APIs: use API gateway routing, version at the service level, not URL level.

Hints to guide your next attempt

  • URL path versioning is most common
  • Header versioning is cleaner but less visible

Source tags: api-versioning / rest / backward-compatibility / api / backend

QUESTION 8 / medium / conceptual

What is GraphQL? How does it differ from REST? When should you use it?

Sample answer

GraphQL: a query language for APIs where the client specifies the exact shape of data it needs. Single endpoint (POST /graphql) for all queries. REST problem: over-fetching (GET /users returns 20 fields, you need 3) and under-fetching (need user + their orders = 2 separate requests). GraphQL solution: query { user(id: "123") { name email orders(last: 5) { id total } } } Returns exactly name, email, and 5 orders. One round trip. Advantages of GraphQL: - No over/under-fetching - Self-documenting via schema (introspection) - Strong typing - Great for mobile (bandwidth-sensitive) - Perfect for aggregating data from multiple microservices (BFF pattern) Disadvantages: - Caching harder than REST (all POST requests to same URL) - N+1 problem requires DataLoader - Learning curve (schema definition, resolvers) - Simple CRUD APIs are overkill Choose GraphQL when: multiple clients (web/mobile) need different data shapes, complex nested data, BFF (backend-for-frontend) for microservices aggregation.

Hints to guide your next attempt

  • Client specifies exactly what data it needs
  • Over-fetching and under-fetching problems

Source tags: graphql / rest / api / over-fetching / backend

QUESTION 9 / medium / conceptual

What are WebSockets? How do they differ from HTTP? When would you use them?

Sample answer

HTTP: request-response — client sends request, server responds, connection closes (or kept alive but only one outstanding request at a time). WebSocket: persistent, bidirectional, full-duplex TCP connection. Either side can send messages at any time after the initial handshake. Handshake: starts as HTTP (GET with Upgrade: websocket header) → server agrees → protocol upgrades to WebSocket. Same port (80/443). // Client (browser) const ws = new WebSocket('wss://api.example.com/chat'); ws.onmessage = (event) => console.log(event.data); ws.send(JSON.stringify({ type: 'message', text: 'Hello' })); When to use WebSockets: - Real-time chat (WhatsApp Web, Slack) - Live notifications - Collaborative editing (Google Docs) - Live dashboards / stock prices - Multiplayer games - Live sports scores When NOT to use WebSockets: - Simple CRUD APIs — HTTP is simpler - Infrequent updates — Server-Sent Events (SSE) is lighter - REST is sufficient — persistent connection has overhead Alternatives: - SSE (Server-Sent Events): one-direction server→client push, simpler, auto-reconnect - Long polling: HTTP request held open until data is available (legacy approach) - Socket.io: WebSocket with fallback + rooms/namespaces (popular in Node.js)

Hints to guide your next attempt

  • WebSocket = persistent bidirectional connection
  • HTTP is request-response, WebSocket is full-duplex

Source tags: websocket / real-time / http / sse / backend

QUESTION 10 / medium / conceptual

What is rate limiting? What algorithms are used to implement it?

Sample answer

Rate limiting: restricting how many requests a client can make in a time window. Protects against abuse, DoS, and resource exhaustion. Common algorithms: 1. Fixed Window Counter: count requests per fixed time window (0-60s, 60-120s...). Problem: burst at window boundary (100 at 0:59, 100 at 1:00 = 200 in 2 seconds). Redis: INCR key, EXPIRE key 60 on first request. 2. Sliding Window Log: store timestamp of each request, count in last 60s. Accurate but memory-intensive (stores every request timestamp). 3. Sliding Window Counter: blend of fixed windows, prorated by overlap. Good accuracy with low memory. Redis sorted sets (ZADD + ZCOUNT). 4. Token Bucket: bucket holds N tokens. Each request consumes 1 token. Tokens refill at fixed rate. Allows bursts up to bucket size. Used by most API gateways. 5. Leaky Bucket: requests go into a queue that processes at a fixed rate. Smooths bursty traffic into uniform output rate. Distributed rate limiting (multiple servers): use Redis as shared counter. Local in-memory counters don't work across instances. Limits by: IP address, user ID, API key, endpoint. Return 429 Too Many Requests with Retry-After header.

Hints to guide your next attempt

  • Token bucket, sliding window, fixed window
  • Redis INCR + EXPIRE for distributed rate limiting

Source tags: rate-limiting / token-bucket / redis / api / backend

QUESTION 11 / medium / conceptual

What is caching? Explain cache-aside, write-through, and write-behind patterns.

Sample answer

Caching: storing computed or fetched data in a fast-access layer (Redis, in-memory) to avoid repeated expensive operations. Cache-aside (Lazy Loading — most common): - On read: check cache first; if miss, fetch from DB, store in cache, return - On write: update DB, then invalidate (delete) the cache entry - Pros: only cache what's actually read; resilient to cache failure - Cons: cache miss on first access (cold start); stale data possible Write-through: - On write: update DB AND cache simultaneously - Pros: cache always has fresh data - Cons: write latency increases; caches data that may never be read Write-behind (Write-back): - On write: update cache immediately, write to DB asynchronously later - Pros: very fast writes - Cons: data loss risk if cache dies before DB write; complex consistency Read-through: - Cache sits in front of DB; on miss, cache fetches from DB automatically (not the app) - App only talks to cache layer; DB writes go through cache Cache eviction policies: LRU (Least Recently Used), LFU (Least Frequently Used), TTL-based expiry. Cache invalidation is the hardest part — stale data bugs are common. Strategies: TTL expiry, event-driven invalidation, versioned cache keys.

Hints to guide your next attempt

  • Cache-aside (lazy loading) is most common — app manages cache explicitly

Source tags: caching / cache-aside / write-through / redis / backend

QUESTION 12 / medium / conceptual

What is the Node.js event loop? How does non-blocking I/O work?

Sample answer

Node.js is single-threaded but non-blocking. The event loop handles asynchronous operations. How it works: 1. Node starts, executes synchronous code (call stack) 2. Async operations (file read, HTTP request, DB query) are offloaded to libuv (which uses OS-level async I/O or a thread pool) 3. Event loop continuously checks if async operations have completed 4. Completed callbacks are put in queues and processed by the event loop Event loop phases (simplified): - timers: setTimeout, setInterval callbacks - I/O callbacks: most I/O event callbacks - poll: retrieve new I/O events (blocking if nothing else queued) - check: setImmediate callbacks - close: socket.destroy() etc. Microtask queues (highest priority, run between each phase): - process.nextTick (highest) - Promise callbacks (.then, async/await resumes) What blocks the event loop: - Synchronous heavy computation (crypto.generateSync, JSON.parse of huge payload) - Tight infinite loops - Synchronous file/disk operations Fix: use worker_threads for CPU-heavy work, never block the main thread. Why Node.js is great for I/O: 1000 simultaneous HTTP requests don't create 1000 threads — they share one event loop. Each waits for I/O without consuming CPU.

Hints to guide your next attempt

  • Single-threaded but non-blocking via event loop + libuv
  • I/O operations are offloaded to OS

Source tags: nodejs / event-loop / async / libuv / backend

Check understanding, not recognition

  • Can you explain the answer without reading it?
  • Can you show when the approach fails or needs a different assumption?
  • Can you connect the concept to a real project, task, or decision you have made?
  • Can you distinguish a simplified interview example from a production requirement?

A LITTLE MORE CLARITY

Frequently asked questions

How many Backend & APIs questions are shown here?

This public preview shows 12 questions with the supplied answers from the app's 30-question Backend & APIs bank. Full interactive practice requires signing in.

Should I memorize the sample answers?

Use them as reference explanations, not a script or a guarantee of technical correctness for every environment. Explain your assumptions, validate code against your language and version, and discuss trade-offs. Behavioral answers should be built from your own experience.

What do hints and solution steps mean?

Hints identify ideas to consider before reading the answer. When the source question includes steps, they are shown as a separate walkthrough. Example capacities and design targets in a solution are assumptions for that exercise, not real system statistics.

BUILD YOUR NEXT OPPORTUNITY

Practice Backend & APIs actively.

Sign in to use the full topic bank and interactive practice workspace.

Open Topic Practice