Skip to the content.

Backend Interview Questions and Answers: APIs, Databases, Caching, Queues, Security and Scaling (2027)

backend-interview-questions is a free, language-agnostic list of backend interview questions with clear answers for backend, platform and full-stack engineers. It covers HTTP and API design (REST, GraphQL, gRPC), databases and SQL (indexes, transactions, isolation levels, replication, sharding), caching with Redis, message queues and event streaming with Kafka, authentication and web security (OAuth 2.0, JWT, OWASP Top 10), distributed systems fundamentals (CAP, consistency, idempotency), reliability and observability, and how to scale a service. Every answer is written to be said out loud in an interview, with trade-offs and links to primary sources.

Last reviewed: December 2026. Product versions change often; where a version matters (PostgreSQL, Redis, Kafka) the answer says so and links the official docs.

Table of Contents

How to Use This List

What Backend Interviews Look Like

Round Content Where in this guide
Coding Data structures and algorithms, sometimes a practical task (build an endpoint, parse logs) Practice
Language and framework deep dive Your main language’s runtime, concurrency, framework internals Companion repos
Backend fundamentals HTTP, databases, caching, queues, security Sections 1 to 10
System design Design a URL shortener, rate limiter, chat, feed, payment system Sections 11 to 15 and system-design-case-studies
Debugging / scenario “The API got slow, what do you do?” Section 15
Behavioral Incidents, ownership, disagreements Have 5 to 6 STAR stories, including one outage

A 4-Week Preparation Plan

Week Focus Done when you can…
1 HTTP, API design, auth (sections 1, 2, 9, 10) Design a paginated, versioned, idempotent REST API with proper status codes and auth
2 Databases: SQL, indexes, transactions, replication (sections 3 to 6) Read an EXPLAIN plan, pick an index, explain isolation anomalies with examples
3 Caching, queues, distributed systems (sections 7, 8, 11) Explain cache-aside with invalidation, at-least-once delivery with idempotent consumers, and CAP/PACELC
4 Scaling, reliability, architecture, scenarios (sections 12 to 15) + 3 mock system design interviews Walk through a design end to end in 45 minutes, including failure modes

1. HTTP Fundamentals

Q1. What are the main HTTP methods, and which are safe and idempotent? [J]

Method Purpose Safe Idempotent
GET Read Yes Yes
HEAD Read headers only Yes Yes
OPTIONS Capabilities, CORS preflight Yes Yes
PUT Replace (or create at a known URL) No Yes
DELETE Remove No Yes
POST Create, or any non-idempotent action No No
PATCH Partial update No Not necessarily

Safe means no intended state change. Idempotent means repeating the request has the same effect as sending it once (the response may differ, for example 404 on a second DELETE). Idempotency matters because clients and proxies retry on timeouts. Definitions come from RFC 9110, HTTP Semantics.

Q2. Which status codes should every backend engineer know? [J]

Code Meaning Typical use
200 OK Success with body Reads, updates
201 Created Resource created POST that creates; include a Location header
202 Accepted Accepted for async processing Job queued
204 No Content Success, no body DELETE
301 / 308 Permanent redirect (308 keeps the method) Moved URLs
302 / 307 Temporary redirect (307 keeps the method)  
304 Not Modified Cached copy is still valid Conditional GET
400 Bad Request Malformed request Invalid JSON
401 Unauthorized Not authenticated Missing or invalid credentials
403 Forbidden Authenticated but not allowed Permission denied
404 Not Found No such resource Also used to hide existence from unauthorized users
409 Conflict Conflicts with current state Version conflict, duplicate
412 Precondition Failed If-Match failed Optimistic concurrency
422 Unprocessable Content Well-formed but semantically invalid Validation errors
429 Too Many Requests Rate limited Add Retry-After
500 Internal Server Error Unexpected server failure Bugs
502 / 503 / 504 Bad gateway / unavailable / gateway timeout Upstream problems, overload, maintenance

Q3. What is the difference between 401 and 403? [J]

401 Unauthorized really means unauthenticated: the server does not know who you are (send credentials, with a WWW-Authenticate header). 403 Forbidden means the server knows who you are and you are not allowed. Some APIs return 404 instead of 403 so they do not reveal that a resource exists.

Q4. What changed in HTTP/2 and HTTP/3? [M]

HTTP/2 (RFC 9113) multiplexes many request streams over one TCP connection with binary framing and header compression (HPACK), removing HTTP/1.1’s one-request-at-a-time limit per connection. Because TCP delivers bytes in order, one lost packet still stalls every stream. HTTP/3 (RFC 9114) runs over QUIC on UDP: streams are independent at the transport layer, TLS 1.3 is built in, handshakes take fewer round trips, and connections survive network changes. gRPC depends on HTTP/2 features.

Q5. What happens during a TLS handshake? [M]

With TLS 1.3, the client sends supported cipher suites and a key share; the server replies with its key share, certificate and a signature proving it owns the certificate’s private key. Both derive session keys from the (EC)DHE exchange, so the handshake takes one round trip (zero with resumption, with replay caveats). The client validates the certificate chain against trusted roots and checks the hostname. Forward secrecy means a stolen server key cannot decrypt past sessions. Mutual TLS (mTLS) adds a client certificate, which is common between internal services.

Q6. What are keep-alive and connection pooling, and why do they matter? [M]

Opening a TCP + TLS connection costs round trips and CPU. Keep-alive reuses a connection for many requests, and connection pools in HTTP clients and database drivers keep a set of open connections ready. Misconfigured pools are a classic production issue: too small and requests queue; too large and you overload the database (each PostgreSQL connection is a separate process, which is why tools like PgBouncer exist).

2. API Design

Q7. What makes an API RESTful? [J]

Resources identified by URLs (/orders/42), standard methods with their semantics, stateless requests (each carries what the server needs, such as an auth token), representations like JSON, correct status codes, and cacheability via HTTP headers. Use nouns, plural collections, and nesting only for real ownership (/orders/42/items). Most real APIs are “REST-ish”; hypermedia (HATEOAS) is rarely used.

Q8. REST vs GraphQL vs gRPC? [M]

  REST GraphQL gRPC
Transport HTTP/1.1+ Usually HTTP POST HTTP/2
Payload JSON (usually) JSON Protocol Buffers (binary)
Contract OpenAPI (optional) Schema (required) .proto files (required)
Strengths Simple, cacheable, universal Clients fetch exactly what they need; one endpoint for many screens Fast, typed, streaming, code generation
Weaknesses Over/under-fetching Caching, query cost control, N+1 resolvers Browser support needs a proxy (gRPC-Web); less human-readable
Typical use Public APIs Product APIs for varied frontends Internal service-to-service

Q9. How do you paginate an API? [M]

Return the next cursor in the response and keep cursors opaque so you can change their format later.

Q10. How do you version an API? [M]

Options: in the URL (/v1/orders, the most common and visible), in a header (Accept: application/vnd.example.v2+json), or by date (some large APIs pin each client to a dated version). Better still, avoid breaking changes: add fields instead of changing them, never change the meaning of existing fields, and make clients ignore unknown fields. When you must break, run versions side by side, publish a deprecation timeline, and use the Deprecation and Sunset headers.

Q11. What is an idempotency key, and how would you implement it? [M]

For non-idempotent operations like payments, the client sends a unique Idempotency-Key header (a UUID) with each logical request and reuses it on retries. The server stores the key with the request fingerprint and the final response; a retry with the same key returns the stored response instead of charging twice. Implementation details: insert the key in the same transaction as the side effect, or lock the key while the first request is processing (return 409 for concurrent duplicates); reject a reused key with a different body; expire keys after a retention window (for example 24 hours).

Q12. How should errors be returned? [J]

Use the right status code plus a consistent, machine-readable body. RFC 9457, Problem Details for HTTP APIs (which replaced RFC 7807) defines a standard JSON shape with type, title, status, detail and instance, which you can extend with fields like errors for validation. Never leak stack traces or SQL errors to clients; log them with a request ID and return that ID.

Q13. How do you design a rate limiter? [M]

Common algorithms:

Algorithm How it works Notes
Fixed window Count per key per minute Simple; allows bursts at window edges
Sliding window log Store a timestamp per request Exact; memory-heavy
Sliding window counter Weighted mix of current and previous window counts Good approximation, cheap
Token bucket Tokens refill at a steady rate; each request spends one Allows controlled bursts; widely used
Leaky bucket Requests drain from a queue at a fixed rate Smooths output

In a distributed system, keep counters in a shared store like Redis with atomic operations (a Lua script or INCR with EXPIRE), or rate-limit at the API gateway. Return 429 with Retry-After, and decide per key: user, API key, IP, or endpoint.

Q14. What is OpenAPI, and why use it? [J]

A machine-readable specification of an HTTP API (paths, parameters, schemas, auth). It drives documentation, client and server code generation, request validation, mocking and contract tests. Design-first (write the spec, then code) catches API design issues early.

Q15. How do webhooks work, and how do you make them reliable? [M]

The provider sends an HTTP POST to a URL the consumer registered when an event happens. Make them reliable by signing payloads (HMAC with a shared secret plus a timestamp to prevent replays), retrying with exponential backoff, expecting duplicates and out-of-order delivery (consumers dedupe by event ID and fetch current state when order matters), responding quickly with 2xx and processing asynchronously, and offering an API to list missed events.

3. Databases and SQL

Q16. SQL vs NoSQL: how do you choose? [J]

Start with a relational database (PostgreSQL or MySQL) unless you have a specific reason not to: they give you transactions, joins, constraints, flexible queries and mature tooling, and scale further than most products need. Choose NoSQL for a specific access pattern: key-value at very high throughput (DynamoDB, Redis), flexible documents (MongoDB), wide-column write-heavy workloads (Cassandra), graphs (Neo4j), time series, or full-text search (Elasticsearch, OpenSearch). Many systems use several, each for what it does best.

Q17. What does ACID mean? [J]

Q18. What is normalization, and when do you denormalize? [M]

Normalization removes redundancy so each fact is stored once (1NF: atomic values; 2NF: no partial dependency on a composite key; 3NF: no dependency between non-key columns). It prevents update anomalies. Denormalize deliberately for read performance (store order_total, keep a counter column, a materialized view, or a read-optimized copy in a search index), and accept the cost of keeping copies in sync.

Q19. Explain the types of JOIN. [J]

INNER JOIN returns matching rows from both tables. LEFT JOIN returns all rows from the left table, with NULLs where there is no match. RIGHT JOIN is the mirror. FULL OUTER JOIN returns all rows from both. CROSS JOIN is every combination. A self-join joins a table to itself (employees and their managers). Filtering a LEFT JOIN’s right table in WHERE instead of ON silently turns it into an inner join, which is a common bug.

Q20. WHERE vs HAVING? What is the logical order of a query? [J]

The logical order is FROM/JOIN → WHERE → GROUP BY → HAVING → SELECT → DISTINCT → ORDER BY → LIMIT. WHERE filters rows before grouping; HAVING filters groups after aggregation (HAVING COUNT(*) > 5). This order also explains why you usually cannot use a SELECT alias in WHERE.

Q21. What are window functions? [M]

They compute over a set of rows related to the current row without collapsing rows like GROUP BY does:

SELECT department, name, salary,
       RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS rank_in_dept,
       salary - AVG(salary) OVER (PARTITION BY department)          AS diff_from_avg
FROM employees;

Common ones: ROW_NUMBER, RANK, DENSE_RANK, LAG/LEAD, running totals with SUM(...) OVER (ORDER BY ...). “Top N per group” and “second highest salary” questions are usually answered with them.

Q22. What is the N+1 query problem? [J]

Fetching a list with one query, then running one more query per item to load related data: N+1 queries instead of 1 or 2. It is common with ORMs and lazy loading. Fix it with a join, an IN (...) batch query, the ORM’s eager loading (JOIN FETCH, include, select_related/prefetch_related), or a DataLoader-style batcher in GraphQL resolvers.

Q23. What is a connection pool, and how do you size it? [M]

A set of reusable database connections shared by request handlers. Too few and requests wait; too many and the database spends its time context switching and holding memory per connection. A starting point is a small multiple of the database server’s CPU cores in total across all app instances, then tune using pool wait time and database metrics. With many app instances or serverless functions, put a pooler (PgBouncer, RDS Proxy) in front of PostgreSQL.

Q24. How do you run database migrations safely? [S]

Use versioned migrations (Flyway, Liquibase, Alembic, Prisma Migrate, Rails/Django migrations) applied by CI/CD. For zero-downtime changes use expand and contract: add the new column or table (nullable, no lock-heavy defaults), deploy code that writes to both, backfill in small batches, switch reads, then drop the old column in a later release. Watch out for operations that take long exclusive locks (some ALTER TABLE forms, index builds without CONCURRENTLY in PostgreSQL), and set a lock_timeout.

4. Indexes and Query Performance

Q25. How does a B-tree index work? [M]

A balanced tree of sorted keys with pointers to rows. Lookups, range scans (BETWEEN, <, ORDER BY) and prefix matches take O(log n) page reads. Leaf pages are linked, so range scans walk sideways. It is the default index type in PostgreSQL and MySQL/InnoDB. Each index speeds up reads but slows writes (every insert or update maintains it) and uses storage.

Q26. What is a composite index, and why does column order matter? [M]

An index on (a, b, c) is sorted by a, then b, then c. It can serve queries filtering on a, a AND b, or a AND b AND c (the leftmost prefix rule), but not b alone efficiently. Put equality-filtered columns first and range or sort columns after: for WHERE tenant_id = ? AND created_at > ? ORDER BY created_at, use (tenant_id, created_at).

Q27. What is a covering index? Clustered vs non-clustered? [M]

A covering index contains every column a query needs, so the database answers from the index alone (an “index-only scan”) without visiting the table (PostgreSQL’s INCLUDE (col) adds non-key columns). In a clustered index the table rows themselves are stored in index order: InnoDB tables are clustered on the primary key, so secondary indexes store the primary key and a lookup goes through both. PostgreSQL tables are heaps; all indexes are secondary.

Q28. When will the database not use your index? [M]

Q29. How do you investigate a slow query? [M]

Find it (slow query log, pg_stat_statements, APM traces). Run EXPLAIN (ANALYZE, BUFFERS) in PostgreSQL or EXPLAIN ANALYZE in MySQL and look for sequential scans on large tables, row estimates far from actual counts, nested loops over many rows, sorts spilling to disk, and high buffer reads. Fix with an index, rewriting the query, better statistics, pagination, or caching. Then check that the plan changed and measure again. Use The Index, Luke is an excellent free guide.

Q30. Besides B-trees, what index types exist? [S]

Hash (equality only), GIN (inverted index for arrays, JSONB and full-text search in PostgreSQL), GiST and SP-GiST (geometric data, ranges, nearest-neighbor), BRIN (tiny block-range summaries for huge, naturally ordered tables like time series), and vector indexes (HNSW, IVF) for similarity search, for example via the pgvector extension. LSM-tree storage engines (RocksDB, Cassandra) favor writes over B-trees’ read performance.

5. Transactions and Concurrency Control

Q31. What are the isolation levels and the anomalies they prevent? [M]

Isolation level Dirty read Non-repeatable read Phantom read Notes
Read uncommitted Possible Possible Possible PostgreSQL treats it as read committed
Read committed Prevented Possible Possible PostgreSQL default
Repeatable read Prevented Prevented Possible per the SQL standard MySQL InnoDB default; PostgreSQL’s version (snapshot isolation) also prevents phantoms
Serializable Prevented Prevented Prevented Behaves as if transactions ran one at a time; may abort transactions you must retry

Also know lost updates and write skew: two transactions read the same data and make decisions that are individually valid but conflict (two doctors both going off call). Snapshot isolation does not prevent write skew; serializable or explicit locks do.

Q32. What is MVCC? [M]

Multi-version concurrency control keeps several versions of a row so readers see a consistent snapshot without blocking writers, and writers do not block readers. PostgreSQL stores old row versions in the table and cleans them with VACUUM; InnoDB keeps undo logs. Long-running transactions keep old versions alive, causing bloat and slower queries.

Q33. Optimistic vs pessimistic locking? [M]

Pessimistic: lock the row before changing it (SELECT ... FOR UPDATE), so others wait. Good when conflicts are frequent. Optimistic: read a version number, then UPDATE ... SET ..., version = version + 1 WHERE id = ? AND version = ?; if zero rows were updated, someone else won, so retry or report a conflict. Good when conflicts are rare. Over HTTP, the same idea uses ETag with If-Match and 412 Precondition Failed.

Q34. How do you prevent double-spending a balance or overselling inventory? [S]

Make the check and the change one atomic operation: UPDATE accounts SET balance = balance - 100 WHERE id = ? AND balance >= 100 and check the affected row count; or lock the row with SELECT ... FOR UPDATE inside a transaction; or use a constraint (CHECK (balance >= 0)). Combine with idempotency keys so retries do not apply the change twice. For ledgers, append immutable entries and derive balances rather than updating one mutable number.

Q35. What are deadlocks in databases, and how do you handle them? [M]

Two transactions each hold a lock the other needs. The database detects the cycle and aborts one with a deadlock error. Reduce them by touching rows in a consistent order (for example sorted by ID), keeping transactions short, and indexing foreign keys and filter columns so fewer rows get locked. The application should retry transactions that fail with deadlock or serialization errors.

6. Replication, Partitioning and NoSQL

Q36. How does replication work, and what is replication lag? [M]

A primary (leader) accepts writes and streams changes (WAL or binlog) to replicas (followers) that serve reads. Synchronous replication waits for a replica to confirm before acknowledging a commit (durable but slower); asynchronous does not (fast, but a failover can lose recent writes). Replication lag means a replica can return stale data, so a user may not see the comment they just posted. Fixes for “read your own writes”: read from the primary for a short time after a write, route by session, or wait for the replica to reach the write’s log position.

Q37. Partitioning vs sharding? [M]

Partitioning splits a table into pieces, often inside one database (PostgreSQL declarative partitioning by range, list or hash), which helps with pruning, maintenance and dropping old data. Sharding spreads data across multiple database servers to scale writes and storage beyond one machine. Choosing a shard key is the hard part: it must spread load evenly (avoid hot keys like a celebrity user) and keep related data together (shard by tenant ID so most queries hit one shard). Cross-shard queries, transactions and resharding are the costs. Consistent hashing reduces data movement when adding nodes.

Q38. What is consistent hashing? [M]

Nodes and keys are hashed onto a ring; each key belongs to the next node clockwise. Adding or removing a node only moves the keys in its neighboring range, instead of almost all keys as with hash(key) % N. Virtual nodes (many points per server) even out the load. Used by Cassandra and DynamoDB-style stores, and by distributed caches and load balancers.

Q39. Compare common NoSQL data stores. [M]

Type Examples Data model Good for Weak at
Key-value Redis, Valkey, DynamoDB Key → value Sessions, caching, counters, very high throughput by key Ad hoc queries
Document MongoDB, Couchbase JSON-like documents Varied or nested records read as a unit Many-to-many relationships
Wide-column Cassandra, ScyllaDB, Bigtable Partition key + sorted rows Write-heavy time series and event data at scale Joins, flexible queries
Graph Neo4j, Amazon Neptune Nodes and edges Relationship traversal Bulk analytics
Search Elasticsearch, OpenSearch Inverted index Full-text and faceted search, logs Being a primary store
Time series TimescaleDB, InfluxDB, Prometheus Timestamped points Metrics, IoT General workloads

In DynamoDB and Cassandra you design tables around queries (access patterns first), the reverse of relational modeling.

Q40. What is a write-ahead log? [S]

Before changing data pages, the database appends a record of the change to a sequential log and flushes it to disk. After a crash, it replays the log to reach a consistent state. The same log drives replication, point-in-time recovery and change data capture (CDC tools like Debezium read it to stream changes into Kafka).

7. Caching

Q41. Where can you cache in a backend system? [J]

Browser (HTTP cache), CDN and edge, reverse proxy (Nginx, Varnish), application in-process memory, a distributed cache (Redis, Valkey, Memcached), the database’s own buffer cache, and materialized views or precomputed results. Each layer closer to the user is faster but harder to invalidate.

Q42. Explain the caching patterns. [M]

Pattern How it works Trade-offs
Cache-aside (lazy loading) App reads the cache; on a miss, reads the DB and fills the cache Most common; first request is slow; stale data possible
Read-through Cache library loads from the DB on a miss Same as above, logic in the cache layer
Write-through Write to the cache and DB together Cache always fresh; slower writes
Write-behind (write-back) Write to the cache; flush to the DB later Fast writes; risk of data loss
Write-around Write to the DB only; cache fills on read Avoids caching data that is never read

Q43. How do you invalidate a cache? [M]

Options: a TTL (simple, bounded staleness), deleting the key on write (cache-aside: update the DB, then delete the key rather than setting it, which avoids races with concurrent readers writing stale values), versioned keys (user:42:v7), or events from the database (CDC) that evict keys. Combining a delete-on-write with a TTL as a safety net is a solid default answer.

Q44. What is a cache stampede, and how do you prevent it? [M]

When a popular key expires, many requests miss at once and all hit the database. Fixes: a lock or “single flight” so one request recomputes while others wait or get the stale value; early probabilistic refresh before expiry; adding jitter to TTLs so keys do not expire together; and serving stale while revalidating.

Q45. What eviction policies exist? [J]

LRU (least recently used), LFU (least frequently used), FIFO, random, and TTL-based expiry. Redis offers several maxmemory-policy options, including allkeys-lru, allkeys-lfu, volatile-ttl and noeviction. Choose LFU when a stable set of hot keys matters more than recency.

Q46. What is Redis used for beyond caching? [M]

Rate limiting and counters (INCR), sessions, leaderboards (sorted sets), queues and streams (LPUSH/BRPOP, Redis Streams with consumer groups), pub/sub, distributed locks (with care), geospatial queries, and deduplication with sets or HyperLogLog. Redis runs commands on a single main thread, so commands are atomic, and slow commands (KEYS *, big SMEMBERS) block everyone; use SCAN. Persistence is via RDB snapshots and/or the AOF log. After Redis changed its license in 2024, the Linux Foundation’s Valkey fork appeared; Redis 8 later added AGPLv3 as an option. Many managed services offer both.

Q47. Is a Redis lock safe for mutual exclusion? [S]

SET lock:key token NX PX 30000 gives a lock with a timeout; release it only if the token matches (a Lua script). It is fine for efficiency (avoiding duplicate work). For correctness it is fragile: a process can pause (GC, network) beyond the lease and continue after another process has taken the lock. If correctness matters, use fencing tokens (a monotonically increasing number the storage layer checks) or a consensus-based system (etcd, ZooKeeper), or use database constraints and transactions instead.

8. Message Queues and Event Streaming

Q48. Why use a message queue? [J]

To decouple producers from consumers, absorb traffic spikes (buffering), process slow work asynchronously (emails, image processing, reports), retry failures, and fan out events to multiple services. Costs: more infrastructure, eventual consistency, harder debugging, and duplicate or out-of-order messages to handle.

Q49. Message queue vs event log (RabbitMQ/SQS vs Kafka)? [M]

  Queue (RabbitMQ, Amazon SQS) Log (Apache Kafka, Redpanda, Kinesis, Pulsar)
Model Messages are deleted once acknowledged Messages are retained for a period; consumers track offsets
Consumers Competing consumers share work Many independent consumer groups each read everything
Replay No (once consumed) Yes, rewind offsets
Ordering Per queue, weakened by parallel consumers Per partition
Routing Rich routing (RabbitMQ exchanges) By topic and partition key
Typical use Task queues, work distribution Event streaming, CDC, analytics pipelines, event sourcing

Kafka 4.0 removed ZooKeeper; clusters now use KRaft, Kafka’s built-in Raft-based metadata quorum. Check the Kafka documentation for current features such as share groups (queue-like consumption).

Q50. What delivery guarantees exist? [M]

Q51. How do you keep message order? [M]

Ordering holds only within a partition (Kafka) or a FIFO queue/message group (SQS FIFO). Use a partition key that groups messages that must stay ordered (for example order_id), so all events for one order go to one partition and are processed by one consumer at a time. Retries can still reorder unless you block the partition on failure. Global ordering across everything does not scale; avoid needing it.

Q52. What is a dead-letter queue? [J]

A queue where messages go after failing processing a set number of times, so one bad message (a “poison pill”) does not block the rest or retry forever. Alert on DLQ depth, inspect messages, fix the bug, then replay them.

Q53. What is the transactional outbox pattern? [S]

The “dual write” problem: you update the database and publish an event, and one can succeed while the other fails. With an outbox, you write the business change and an event row to an outbox table in the same database transaction. A separate relay (polling or CDC with Debezium) publishes outbox rows to the broker and marks them sent. Delivery is at-least-once, so consumers must be idempotent. The inbox pattern on the consumer side records processed message IDs for deduplication.

Q54. How do you handle backpressure? [M]

When consumers cannot keep up, queues grow. Options: scale consumers (autoscale on queue depth or consumer lag), limit producers (rate limits, 429), bound queues and reject or shed low-priority work, batch processing, and make sure a slow downstream dependency cannot cascade into everything (timeouts, circuit breakers, bulkheads).

9. Authentication and Authorization

Q55. Authentication vs authorization? [J]

Authentication (authn) verifies who you are: passwords, passkeys, OAuth/OIDC login, API keys, mTLS. Authorization (authz) decides what you may do: roles, permissions, ownership checks. Most security bugs in APIs are authorization bugs: endpoints that check you are logged in but not that the object belongs to you.

Q56. Sessions vs JWTs? [M]

  Server sessions (opaque ID in a cookie) JWT (self-contained signed token)
State Stored server-side (DB or Redis) Claims inside the token
Revocation Delete the session: instant Hard: valid until expiry unless you keep a denylist
Scaling Needs a shared session store Any service can verify with the public key
Size Small cookie Larger, sent on every request
Best for Browser apps with your own backend Service-to-service, APIs, short-lived access tokens

A common hybrid: short-lived JWT access tokens (minutes) plus a refresh token that is stored server-side, can be revoked, and is rotated on each use. Verify the signature, exp, iss and aud, and pin the expected algorithm (never accept alg: none). JWTs are signed, not encrypted: do not put secrets in them.

Q57. Explain OAuth 2.0 and OpenID Connect. [M]

OAuth 2.0 is for delegated authorization: a user lets an app access their data at another service without sharing their password. In the authorization code flow with PKCE, the app redirects the user to the authorization server, the user logs in and consents, the app receives a short-lived code, and exchanges it (plus the PKCE verifier) for an access token and optionally a refresh token. Client credentials is for machine-to-machine access. The implicit and password grants are deprecated in current best practice. OpenID Connect adds authentication on top: an ID token (a JWT) that says who the user is. Read the OAuth 2.0 Security Best Current Practice (RFC 9700).

Q58. How should passwords be stored? [J]

Never in plain text or with fast hashes like MD5 or SHA-256. Use a slow, salted password hashing function: Argon2id (first choice), scrypt, or bcrypt, with parameters tuned so hashing takes meaningful time. The salt is unique per user and stored with the hash. Add rate limiting, breached-password checks, MFA, and offer passkeys (WebAuthn). See the OWASP Password Storage Cheat Sheet.

Q59. RBAC vs ABAC vs ReBAC? [S]

RBAC (role-based): users get roles, roles get permissions. Simple, but roles multiply. ABAC (attribute-based): policies evaluate attributes of the user, resource and context (“managers can approve expenses under $5,000 in their region”). ReBAC (relationship-based): permissions derive from relationships in a graph (“editors of a folder can edit its documents”), the model behind Google’s Zanzibar paper and open-source systems like OpenFGA and SpiceDB. Policy engines such as Open Policy Agent or Cedar keep rules out of application code.

Q60. How do services authenticate to each other? [M]

mTLS (often via a service mesh), signed short-lived tokens from an identity provider (OAuth client credentials, workload identity like SPIFFE), or cloud IAM roles. Avoid long-lived shared API keys; if you must use them, store them in a secrets manager and rotate them.

10. Backend Security

Q61. What is on the OWASP Top 10 (2025)? [M]

The OWASP Top 10:2025 lists:

  1. A01 Broken Access Control
  2. A02 Security Misconfiguration
  3. A03 Software Supply Chain Failures
  4. A04 Cryptographic Failures
  5. A05 Injection
  6. A06 Insecure Design
  7. A07 Authentication Failures
  8. A08 Software or Data Integrity Failures
  9. A09 Security Logging and Alerting Failures
  10. A10 Mishandling of Exceptional Conditions

For APIs, the OWASP API Security Top 10 (2023) adds API-specific risks, topped by Broken Object Level Authorization (BOLA): GET /orders/43 returning someone else’s order because the server never checked ownership.

Q62. How do you prevent SQL injection? [J]

Use parameterized queries (prepared statements) or a query builder/ORM that parameterizes for you; never concatenate user input into SQL. Values are sent separately from the query text, so they cannot change its structure. For identifiers you cannot parameterize (sort columns), use an allowlist. Also apply least-privilege database users.

Q63. What is SSRF? [M]

Server-side request forgery: an attacker makes your server fetch a URL they choose (a “fetch this image URL” or webhook feature), reaching internal services or cloud metadata endpoints that hand out credentials. Defenses: allowlist destinations, resolve and block private and link-local IP ranges (and re-check after redirects and DNS rebinding), use cloud metadata protections (for example AWS IMDSv2), and run fetchers in an isolated network. In the 2025 Top 10, SSRF is part of A01 Broken Access Control.

Q64. How should secrets be managed? [M]

Never commit them to Git (scan with tools like gitleaks or GitHub secret scanning). Store them in a secrets manager (HashiCorp Vault, AWS Secrets Manager, GCP Secret Manager, Azure Key Vault) or encrypted platform secrets, inject at runtime, prefer short-lived credentials (workload identity, dynamic database credentials), rotate regularly, and limit who and what can read them.

Q65. What is defense in depth for an API? [S]

Layers that each catch what others miss: TLS everywhere, an API gateway with authentication and rate limits, input validation with schemas, authorization checks on every object access, parameterized queries, least-privilege service accounts, encrypted data at rest, audit logging and alerting, dependency and container scanning, and a WAF for known attack patterns. Mention threat modeling during design (for example STRIDE).

11. Distributed Systems Fundamentals

Q66. Explain the CAP theorem and PACELC. [M]

CAP: when a network partition happens, a distributed data store must choose between consistency (every read sees the latest write, or fails) and availability (every request gets a non-error response, possibly stale). Partitions are not optional in real networks, so the real choice is CP vs AP during partitions. PACELC extends it: if there is a Partition, choose A or C; Else (normal operation), choose between Latency and Consistency. For example, DynamoDB and Cassandra default toward availability and low latency with tunable consistency; Spanner and etcd choose consistency.

Q67. Strong vs eventual consistency? [M]

Strong (linearizable): once a write completes, every later read sees it, as if there were one copy. Eventual: replicas converge if writes stop; reads may be stale for a while. In between: read-your-writes, monotonic reads, causal consistency. Quorums: with N replicas, writing to W and reading from R where R + W > N makes reads overlap the latest write (under normal conditions).

Q68. Why is idempotency so important in distributed systems? [M]

Networks fail ambiguously: a timeout does not tell you whether the request was processed. Safe retries require idempotent operations (idempotency keys, upserts, conditional writes, deduplication by message ID). Every retrying client, queue consumer and webhook handler should assume duplicates.

Q69. What are consensus algorithms used for? [S]

Getting nodes to agree on a value or log order despite failures: leader election, replicated configuration, distributed locks, metadata. Raft (etcd, Consul, CockroachDB, Kafka KRaft) and Paxos variants (Spanner, Chubby) need a majority (quorum) of nodes, so a 5-node cluster tolerates 2 failures. They are not used for every write in most systems because each decision costs a round trip to a majority.

Q70. What is the two-phase commit problem, and what is a saga? [S]

Two-phase commit coordinates a transaction across databases (prepare, then commit), but a coordinator failure can leave participants blocked holding locks, and it couples services tightly. A saga splits a business transaction into local transactions, each with a compensating action (cancel the reservation, refund the payment). Coordinate with choreography (services react to each other’s events) or orchestration (a central workflow engine such as Temporal or AWS Step Functions). Sagas give eventual consistency, so design for intermediate states users might see.

Q71. Why are clocks a problem, and what are logical clocks? [S]

Physical clocks drift and NTP can jump them backward, so timestamps from different machines cannot reliably order events; “last write wins” by timestamp can drop data. Lamport clocks give an ordering consistent with causality; vector clocks detect concurrent updates; hybrid logical clocks combine physical time with logical counters (used by CockroachDB). Spanner uses TrueTime with bounded uncertainty and waits it out.

Q72. What are timeouts, retries and circuit breakers? [M]

The Amazon Builders’ Library articles on timeouts, retries and backoff with jitter are excellent free reading.

12. Scaling and Performance

Q73. Vertical vs horizontal scaling? [J]

Vertical: a bigger machine. Simple, no code changes, but limited and a single point of failure. Horizontal: more machines behind a load balancer. Requires stateless services (sessions in a shared store, files in object storage), and data tier scaling via replicas, caching and sharding. Scale vertically first when it is cheap; design so you can scale horizontally.

Q74. How do load balancers work? [M]

They spread requests across healthy backends using algorithms like round robin, least connections, or consistent hashing, and remove unhealthy instances based on health checks. Layer 4 balancers route by IP and port (fast, protocol-agnostic); Layer 7 balancers understand HTTP (route by path or header, terminate TLS, retries, sticky sessions). Avoid sticky sessions when possible; they make scaling and deploys uneven.

Q75. How do you design a stateless service? [J]

Keep no per-user state in process memory between requests: sessions in Redis or a database, uploaded files in object storage (S3), background jobs in a queue, configuration from the environment (The Twelve-Factor App principles). Any instance can then serve any request, and instances can be added, removed or restarted at will.

Q76. A read-heavy system is slow. How do you scale it? [M]

Measure first, then in rough order of effort: add or fix indexes and queries, add caching (CDN for public content, Redis for hot objects), add read replicas, precompute expensive results (materialized views, denormalized tables, search indexes), and finally shard. Mention cache invalidation and replica lag as the new problems each step introduces.

Q77. A write-heavy system is slow. How do you scale it? [M]

Batch writes, make them asynchronous through a queue where the business allows, reduce index overhead, use append-only designs (event logs, LSM-tree stores), partition hot tables, shard by a key that spreads load, and use stores built for heavy writes (Cassandra, time-series databases). Watch for hot keys (a single counter row) and spread them (sharded counters).

Q78. What is the difference between latency and throughput? Why use percentiles? [J]

Latency is how long one request takes; throughput is how many requests per second the system handles. Averages hide outliers, so track p50, p95, p99: if p99 is 2 seconds, 1 in 100 requests is that slow, and a page that makes 50 backend calls will hit it often. Little’s Law (concurrency = throughput × latency) helps size pools and capacity.

Q79. How do you handle a traffic spike you know is coming? [M]

Load test beforehand, pre-scale (autoscalers react with a delay), warm caches, raise limits with providers, add a queue or waiting room in front of the bottleneck, set rate limits, prepare feature flags to disable expensive non-essential features (graceful degradation), and have dashboards and an on-call plan ready.

13. Reliability, Observability and Operations

Q80. What are SLIs, SLOs, SLAs and error budgets? [M]

An SLI is a measurement (percentage of requests under 300 ms, success rate). An SLO is the target for it (99.9% of requests succeed over 30 days). An SLA is a contract with consequences if it is missed, usually looser than the SLO. The error budget is what the SLO allows to fail (0.1% here, about 43 minutes of full downtime in 30 days); when it is spent, teams slow feature releases and focus on reliability. The free Google SRE books explain this in depth.

Q81. What are the three pillars of observability? [J]

Logs (structured JSON events with request IDs), metrics (counters, gauges and histograms over time, such as the RED method: rate, errors, duration; or USE for resources: utilization, saturation, errors), and traces (the path of one request through services, with spans and timing). OpenTelemetry is the vendor-neutral standard for producing all three. Profiles (continuous profiling) are often called a fourth signal.

Q82. How do you deploy without downtime? [M]

Rolling deployments (replace instances gradually behind health checks), blue-green (switch traffic between two full environments), and canary releases (send a small percentage of traffic to the new version and watch metrics before continuing). All need backward-compatible database migrations (expand and contract), graceful shutdown (stop taking new requests, finish in-flight ones), readiness probes, and fast rollback. Feature flags separate deploying code from releasing features.

Q83. Liveness vs readiness probes? [M]

A readiness probe says whether an instance should receive traffic (dependencies reachable, warm-up done); failing it removes the instance from the load balancer. A liveness probe says whether the process is stuck and should be restarted. Do not check downstream dependencies in liveness probes, or one database blip restarts your whole fleet.

Q84. What do you do during an incident? [M]

Mitigate first, investigate later: roll back the recent deploy, fail over, scale up, or disable a feature. Communicate with an incident commander and a status page. Afterwards, write a blameless postmortem: timeline, impact, root causes and contributing factors, what went well, and action items with owners.

14. Architecture: Monoliths, Microservices and Events

Q85. Monolith vs microservices? [M]

  Modular monolith Microservices
Deploy One unit Independently per service
Data One database, enforced module boundaries Database per service
Consistency Local transactions Eventual consistency, sagas
Operations Simple Needs service discovery, observability, CI/CD maturity
Team scaling Harder past many teams Teams own services end to end
Failure modes Process-level Network failures, partial outages, version skew

Most teams should start with a well-structured modular monolith and extract services when a real need appears (independent scaling, deploy cadence, team ownership). “Distributed monolith” (services that must deploy together) is the worst of both.

Q86. What is an API gateway, and what is a service mesh? [M]

An API gateway is the entry point for external clients: routing, authentication, rate limiting, request transformation, and sometimes response aggregation (backend for frontend). A service mesh (Istio, Linkerd) handles service-to-service traffic inside the cluster with sidecar or node proxies: mTLS, retries, timeouts, traffic shifting and telemetry, without changing application code.

Q87. What are event-driven architecture, event sourcing and CQRS? [S]

Event-driven architecture: services communicate by publishing events (“OrderPlaced”) rather than calling each other directly, which reduces coupling but makes flows harder to follow. Event sourcing: store the sequence of events as the source of truth and derive current state by replaying them; you get a full audit history and can build new views, at the cost of complexity and schema evolution of events. CQRS: separate the write model from read models optimized for queries, often fed by events. Use them where they pay off (ledgers, audit-heavy domains), not by default.

Q88. How do you design for multi-tenancy? [S]

Options from most shared to most isolated: shared tables with a tenant_id column (cheap; enforce with row-level security and tenant-scoped queries), schema per tenant, database per tenant (strong isolation, harder operations). Also plan for noisy neighbors (per-tenant rate limits and quotas), per-tenant encryption keys for enterprise customers, and data residency requirements.

15. Scenario Questions

Q89. “Our API’s p99 latency doubled after a deploy. What do you do?” [M]

  1. Confirm and scope it with dashboards: all endpoints or some, all instances or some, correlated with the deploy time?
  2. Mitigate: roll back if the deploy is the likely cause.
  3. Investigate with traces of slow requests to find the slow span (database, downstream call, CPU, lock wait, GC pauses).
  4. Check usual suspects: a new N+1 query, a missing index, a changed query plan, a smaller connection pool, synchronous calls added to the request path, a cache key change causing misses.
  5. Fix, add a test or alert that would have caught it, and write it up.

Q90. “Design a URL shortener.” [M]

Key points: a short code generator (base62 of a unique ID from a sequence or a distributed ID generator like Snowflake, or random codes with collision checks), a key-value table code → long_url, 301 vs 302 redirects (302 if you need analytics on every click), heavy caching of hot codes (reads vastly outnumber writes), custom aliases with uniqueness checks, abuse prevention (rate limits, malware URL scanning), analytics events sent asynchronously to a queue, and expiry. Estimate storage and QPS out loud.

Q91. “Users sometimes get charged twice.” [S]

Likely causes: client or gateway retries on timeout without idempotency keys, a queue consumer processing a redelivered message, or a race between two submissions. Fix: idempotency keys stored with a unique constraint, idempotent consumers keyed by payment ID, a state machine for payments (pending → authorized → captured) with conditional updates, reconciliation jobs against the payment provider, and the provider’s own idempotency support.

Q92. “The database CPU is at 100%.” [M]

Find the top queries by total time (pg_stat_statements), check for missing indexes and new query plans, look for a traffic spike or a batch job, check lock contention and connection counts, and look at autovacuum and bloat. Short term: kill runaway queries, throttle batch jobs, add an index concurrently, add caching or a read replica. Long term: query review in code review, load tests, and capacity alerts before the limit.

Q93. “How would you build a job that runs every day at 2 a.m. across 10 servers?” [M]

Do not run it on all 10. Use a scheduler with a single leader (Kubernetes CronJob, a managed scheduler, or a workflow engine) or a distributed lock with fencing. Make the job idempotent and resumable (process in batches with checkpoints), record runs, alert on failures and on “did not run”, and handle time zones and daylight saving changes explicitly (schedule in UTC).

Q94. “How do you design a notification system?” [S]

An API to accept notification requests, user preferences and quiet hours, a queue per channel (email, SMS, push, in-app) with workers calling providers, templates and localization, deduplication and rate limits per user, retries with backoff and provider failover, delivery tracking via provider webhooks, and priority lanes so password resets are not stuck behind marketing campaigns.

Practice: SQL and Design Problems

SQL problems on LeetCode (free unless marked Premium):

Problem Skill
175. Combine Two Tables LEFT JOIN
176. Second Highest Salary Subqueries, LIMIT/OFFSET, NULL handling
177. Nth Highest Salary Functions, window functions
178. Rank Scores DENSE_RANK
180. Consecutive Numbers LAG/LEAD, self-joins
181. Employees Earning More Than Their Managers Self-join
184. Department Highest Salary Group-wise max
185. Department Top Three Salaries Top N per group
196. Delete Duplicate Emails DELETE with self-join
197. Rising Temperature Date arithmetic
262. Trips and Users Conditional aggregation
1179. Reformat Department Table Pivoting

Backend-flavored coding problems:

Problem Why it is asked
146. LRU Cache Cache eviction
460. LFU Cache Frequency-based eviction
359. Logger Rate Limiter (Premium) Rate limiting
362. Design Hit Counter (Premium) Sliding windows
981. Time Based Key-Value Store Versioned storage, binary search
535. Encode and Decode TinyURL URL shortener basics
1396. Design Underground System Aggregation with hash maps
355. Design Twitter Feed merging with heaps

Design exercises to do on paper: a rate limiter, a URL shortener, a job scheduler, a notification service, a chat backend, a payment flow with idempotency, a file upload service with resumable uploads, and a leaderboard.

Best Resources to Prepare

Resource Type Cost Best for
Designing Data-Intensive Applications, 2nd edition (2026), by Martin Kleppmann and Chris Riccomini (publisher page) Book Paid Best single book for databases, replication, partitioning, transactions and streams
Use The Index, Luke Online book Free SQL indexing and query performance
PostgreSQL documentation Docs Free Transactions, isolation (chapter 13), indexes, EXPLAIN
Redis documentation Docs Free Data structures, persistence, eviction
Apache Kafka documentation Docs Free Partitions, consumer groups, delivery semantics
Google SRE books Books Free online SLOs, error budgets, incident response
Amazon Builders’ Library Articles Free Timeouts, retries, load shedding, deployments at scale
The System Design Primer Guide Free Broad system design overview with exercises
OWASP Cheat Sheet Series Guides Free Authentication, sessions, injection, secrets
OWASP Top 10:2025 and API Security Top 10 Lists Free Security rounds
RFC 9110: HTTP Semantics Standard Free Exact meaning of methods, status codes, caching headers
The Twelve-Factor App Guide Free Cloud-native service design
Jepsen analyses Research Free How real databases behave under partitions (senior level)
OpenTelemetry docs Docs Free Tracing, metrics and logs
ByteByteGo Course, newsletter Free newsletter, course paid Visual system design explanations

If you pick only two: Designing Data-Intensive Applications for depth and the free System Design Primer for breadth.

FAQ

What backend topics come up most in interviews? HTTP and REST design, status codes, SQL and indexing, transactions and isolation levels, caching and invalidation, message queues and idempotency, authentication with sessions, JWT and OAuth, and scaling a service. Senior roles add distributed systems trade-offs, reliability and incident stories.

Do I need to know a specific language for backend interviews? You need one language deeply (Java, Go, Python, Node.js, C#, Ruby, Rust…) for coding rounds and its runtime questions. The fundamentals in this list are the same in every language.

How much SQL do backend developers need? Enough to write joins, aggregations, subqueries and window functions comfortably, read an execution plan, design indexes for your queries, and explain transactions and isolation. LeetCode’s SQL problems are good practice.

Should I learn Kafka or RabbitMQ for interviews? Learn the concepts: queues vs logs, consumer groups, partitions and ordering, delivery guarantees, DLQs, idempotent consumers, and the outbox pattern. Then know one tool’s specifics, ideally the one the company uses.

How is a backend interview different from a system design interview? Backend fundamentals rounds go deep on individual building blocks (an index, an isolation level, a cache pattern). System design rounds combine those blocks into an architecture under constraints. Good fundamentals make system design answers concrete.

What should juniors focus on? HTTP, REST design, SQL with joins and indexes, basic authentication, one framework, writing tests, and being able to explain a project you built end to end, including how you deployed it.

Where to Go Next

Contributing

Pull requests are welcome: new questions, clearer answers, corrections, and new scenario questions from real interviews (described in your own words, never copied from paid or confidential material). Please keep answers concise, explain trade-offs, mark the level ([J], [M], [S]), and link primary sources (RFCs, official docs) for factual claims.

License

Content is licensed under CC BY 4.0.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.