101 Backend Essentials interview questions with detailed answers, sorted from basic to advanced. Free to practice, with progress saved automatically.
A curated shortlist of topics that backend interviews tend to revolve around, gathered from several areas rather than one framework. It spans REST and HTTP API design, authentication with JWT and refresh tokens, large file uploads, dependency injection and creational patterns, SQL versus NoSQL, caching strategies, the CAP theorem, and web security issues such as SQL injection.
- Unit test: checks one small unit (function, class) in isolation with mocked/stubbed dependencies. Runs in milliseconds; a failure points at the exact spot → easiest to write, so write the most of these. - Integration test: checks several components working together — real DB,…
DI is the technique where an object receives its dependencies from the outside rather than creating them — it is the mechanism that implements DIP. Three types of DI: DI frameworks: NestJS uses an IoC container with @Injectable() and @Inject() decorators that automatically resolve the…
RabbitMQ is an open-source message broker that enables applications to communicate asynchronously by sending messages through a central broker rather than calling each other directly. The basic flow has four roles: - Producer: the application that sends a message. - Exchange: receives the message and…
Four exchange types: 1. Direct: exact routing key match, for task distribution to specific workers. 2. Fanout: broadcasts to all bound queues regardless of routing key, for notifications. 3. Topic: wildcard pattern matching ( matches exactly one word, matches zero or more words, words separated…
Retries in RabbitMQ are driven by consumer acks. When processing fails, the consumer can nack with requeue (retry immediately) or nack without requeue to push the message to a dead-letter exchange (DLX). A common pattern is delayed retry through a wait queue with a TTL:…
Merge: creates a merge commit that joins the two branches and keeps the full history. git log --graph still shows the branch splitting off and coming back. Merge never modifies existing commits. Rebase: takes each commit of the current branch and reapplies it on top…
The hardest conflict is not a simple add/delete but one where both sides refactored the structure: a function was renamed, logic was reorganized. The conflict markers then only show two different blocks of code, not what each side intended. Safe process: 1. Understand context before…
A commit already on main that others have pulled calls for git revert; use git reset only on a local branch nobody else has. git revert git reset --------- What it does Creates a new commit that undoes the old commit's changes Moves the branch…
REST (Representational State Transfer) is an architectural style for HTTP APIs. Core principles: - Client-server: the client owns the UI, the server owns the data; each evolves independently as long as the API holds. - Stateless: each request carries everything needed (including the auth token);…
A method is idempotent when sending the request once or many times produces the same effect on the server. - Idempotent: GET, HEAD, PUT, DELETE, OPTIONS. - Not idempotent: POST (usually creates a new record each time), PATCH (implementation-dependent). Practical meaning: clients can safely retry…
Five classes by leading digit: - 1xx Informational — received, processing. - 2xx Success: 200 OK, 201 Created, 204 No Content. - 3xx Redirection: 301 (moved permanently), 304 Not Modified (cache). - 4xx Client error: 400 (bad request), 401 (unauthenticated), 403 (forbidden), 404 (not found),…
Goal: evolve the API without breaking existing clients. Options: - URI versioning (/v1/users): explicit, easy to cache/route — most common, but mixes the version into the resource URL. - Query param (/users?version=1): simple, but easy to omit. - Header (Accept: application/vnd.app.v1+json or a custom header):…
SQL (relational): data in tables, fixed schema, relationships via primary/foreign keys, full ACID, typically vertical scaling. Fits transactional systems needing strong consistency and tight relationships (finance, orders). NoSQL: groups several different kinds of store — document (JSON), key-value, wide-column, graph. What they share: - Flexible…
An index is a separate, ordered data structure (usually a B-tree) holding a copy of the indexed column plus pointers to the rows. Being ordered, the DB traverses the tree instead of doing a full table scan → fast lookups on that column in WHERE,…
A cache keeps hot data in a fast layer (RAM, e.g. Redis) → offloads the DB and speeds up reads. Read/write strategies: - Cache-aside (lazy loading): the app reads the cache first; on a miss it reads the DB then populates the cache. Most common;…
SQL injection happens when an app concatenates user input into a SQL statement → the attacker injects SQL to expose/modify data or even take over the DB. Defenses (by effectiveness — OWASP): 1. Prepared statements / parameterized queries — separate SQL code from data; input…
- Authentication: who you are — verifying identity (password, OAuth, passkey). - Authorization: what you may do — checking access to resources (RBAC, scopes). Order: authenticate first, authorize second. Missing permission → 403; not authenticated → 401. How a server verifies a JWT: the token…
- REST: many resource endpoints, usually JSON over HTTP (not tied to any specific HTTP version). Simple, great HTTP caching, universally known. Weakness: over-/under-fetching (returning too much/too little, needing multiple round-trips). - GraphQL: a single endpoint where the client declares exactly which fields it needs…
All three let the server push data without the client constantly asking. - Long-polling: the client sends a request, the server holds it open until data exists, then responds; the client immediately re-requests. Works over plain HTTP, widely compatible, but connection-heavy and adds latency. -…
A webhook lets an external system call your URL when an event happens, instead of you continuously polling. Think "reverse API" / "push callback" — e.g. SePay signaling a successful payment, GitHub signaling a push. When receiving a webhook you should: - Verify the signature:…
Normalization: organize data to remove duplication — split into related tables joined by keys, each fact stored once (per the normal forms 1NF/2NF/3NF). - Pros: compact writes/updates, avoids contradictory data, saves space. - Cons: reads must JOIN many tables → more complex and potentially slower…
A reverse proxy (e.g. Nginx, HAProxy) sits in front of servers, receives requests on their behalf and forwards them. Shared infrastructure duties: TLS termination, load balancing, caching, compression, hiding internal topology. An API gateway is a reverse proxy specialized for APIs, adding application-layer concerns at…
Stateless: the server keeps no session state in memory between requests — each request carries everything needed, or state is pushed to shared external storage (DB, Redis, client-side JWT). Why it matters for horizontal scaling (adding more instances instead of one bigger machine): - Any…
Health check: an endpoint (e.g. /healthz) that lets the load balancer/orchestrator (Kubernetes) know whether an instance is alive and ready to take traffic. Two kinds are usually distinguished: - Liveness: is the process alive? Failing → restart the instance. - Readiness: is it ready to…
Observability is the ability to understand what a system is doing from the outside through the data it emits — to answer "what broke, where, and why", especially in distributed systems. Three pillars: - Logs: records of discrete events with timestamp and context ("event X,…
Hashing vs encryption: encryption is two-way (a key can decrypt it back). A hash is one-way — irreversible. Passwords must be hashed, not encrypted: the DB stores only the hash, so even a breach cannot recover the original password. Never store plaintext. Doing it right…
HTTPS = HTTP over TLS. TLS gives three guarantees: encryption (eavesdroppers cannot read), integrity (no tampering in transit), authentication (you are talking to the right server, via its certificate). The handshake (simplified) before any data flows: 1. The client sends ClientHello: supported TLS versions and…
The OWASP Top 10 is a periodically updated list (latest edition: 2025) of the ten most critical web security risk categories — a minimum checklist for reviewing an app. Core entries: - Broken Access Control: missing/incorrect permission checks → users see/modify others' data. Ranked first…
A transaction is a group of statements that runs as one atomic unit — either all succeed or none do. - BEGIN: start the transaction. - COMMIT: confirm; all changes become durable and visible to other transactions. - ROLLBACK: abort; return the DB to its…
A Kafka topic is split into partitions — each partition is an append-only, ordered log. Reading/writing across partitions in parallel is how Kafka scales throughput. - Ordering is guaranteed only within a partition, not across the whole topic. Messages with the same key always land…
A DLQ is a side queue holding messages that cannot be processed after enough retries (bad format, consumer bug, invalid data...). Why it exists: - Prevents a poison message from blocking or infinitely looping the main queue. - Isolates failures so the main queue keeps…
Both are authorization models: - RBAC (Role-Based): grant permissions via roles (admin, editor, viewer); users get access through their roles. Simple, easy to understand and audit; fits most apps. Downside: an explosion of roles when rules get too fine-grained ("role explosion"). - ABAC (Attribute-Based): decisions…
- Validation: check whether input is valid (type, length, range, format) and reject if not. Prefer an allow-list (accept only what is correct) over a deny-list (block the bad — easy to miss cases). - Sanitization: clean/transform input to make it safe to use (strip/escape…
Both reduce release risk and avoid downtime: - Blue-green: run two parallel environments — "blue" (live) and "green" (new). After testing, switch all traffic to green at once; on failure, switch back instantly. Rollback is very fast, but it doubles infrastructure and still flips 100%…
A race condition happens when multiple requests/processes access the same resource concurrently and the outcome depends on execution order. Classic example: two requests both read a balance of 100, both subtract 30 and write back → both write 70 instead of 40 (lost update). Another…
- Blocking I/O: the thread calling an I/O operation (file read, DB query, HTTP call) must wait until the result arrives — doing nothing else meanwhile. - Non-blocking I/O: the call returns immediately; the result comes back via a callback/event when ready, freeing the thread…
Four core principles: - One consistent format across the API: every endpoint returns errors in the same structure so clients write one shared handler — not { error } here and { message } there. - Semantically correct status codes: 400 malformed request, 401 unauthenticated,…
Middleware is a chain of functions forming a pipeline between request and response. The request flows through each middleware in order, and each one can: - read or modify the request and response, - short-circuit by responding immediately, - pass control on to the next…
- Virtual machine (VM): virtualizes hardware via a hypervisor; each VM runs a full guest OS. Strong isolation, but heavy (gigabytes, tens of seconds to boot). - Container: virtualizes at the OS level; containers share the host kernel but run in isolated process/filesystem space. Lightweight…
- Primary key: one or more columns that uniquely identify each row. Values must be unique and non-NULL; a table has at most one primary key (usually backed by an automatic B-tree index). - Foreign key: a column in a child table that references the…
A CDN (Content Delivery Network) is a network of geographically distributed servers placed near users, holding cached copies of content to serve from the closest point instead of always reaching the origin server. Benefits: - Lower latency: data travels a shorter distance to the user…
Sessions keep the session data on the server and the client holds only an id. Tokens/JWT pack the information into a signed token and the server stores nothing. Session (stateful) Token/JWT (stateless) --------- What the server stores Session data (memory/Redis/DB); the client holds an opaque…
Opening a DB connection is expensive: TCP handshake, TLS setup, authentication, server-side resource allocation — milliseconds and memory per connection. If every request opens and closes its own connection, latency and load climb fast. A connection pool keeps a set of open, reusable connections: a…
HTTP has built-in caching so browsers/CDNs/proxies can reuse old responses, cutting round-trips and origin load. Two layers: - Freshness — Cache-Control: - max-age=<seconds: how long it counts as fresh, served straight from cache without asking the server. - no-cache: may be stored but must revalidate…
CSRF (Cross-Site Request Forgery) abuses the fact that browsers auto-attach cookies to every request to a site. The attacker lures a logged-in user to a malicious page, which silently sends a request to the victim site (e.g. a transfer or email-change form). The request carries…
- Synchronous: the client sends a request and waits until it completes, receiving the result inline in the response. Simple and easy to reason about, but it holds resources (connection, thread) for the whole processing time, and latency equals the task duration. - Asynchronous: the…
Two asynchronous messaging models, differing in who receives a message: - Message queue (point-to-point): each message is processed by exactly one consumer. Multiple consumers on one queue share the work (competing consumers) for throughput, but a given message goes to only one of them. Fits…
- HTTP/1.1: a text protocol where each TCP connection handles one request at a time → head-of-line (HOL) blocking: a slow request stalls those behind it. It has keep-alive, but browsers must open several parallel connections (and use tricks like domain sharding) to load fast.…
- Vertical scaling (scale up): make one machine more powerful — add CPU, RAM, disk. Simple, no architecture/code changes, avoids distributed-systems complexity. Cons: a hardware ceiling, non-linear cost at high-end configs, and it remains a single point of failure. - Horizontal scaling (scale out): add…
- Continuous Integration (CI): developers merge changes into the mainline frequently (at least daily); each merge automatically builds + runs tests. Goal: catch integration conflicts/bugs early, while small, instead of one big end-of-cycle merge. Requires self-testing code and a fast automated build. - Continuous Delivery:…
Short-lived access token (5–15 min) sent via Authorization: Bearer; long-lived refresh token used only to obtain new access tokens. Where to store: refresh token in an httpOnly + Secure + SameSite cookie (JS cannot read it → mitigates XSS theft); keep the access token in…
Goal: only the true email owner can reset the password, and no information leaks about which accounts exist. Flow: 1. The user enters an email → always return the same message ("if the email exists, we sent a link") whether or not it exists →…
The core difference: a session keeps state on the server (the cookie only carries a session id, so revoking means deleting a row), while a JWT pushes state into a signed token each service verifies on its own without calling the auth service — at…
Layer several measures; do not rely on a single one: - Rate limit per IP and per account (e.g. max N attempts/minute). Per-account limits stop IP rotation; per-IP limits stop spraying many accounts from one IP. - Exponential backoff: each failure increases the wait (1s,…
Each location trades off two different risks — XSS and CSRF. - localStorage: easy JS read/write, convenient for attaching an Authorization header (so it is CSRF-immune). But XSS can read it → one injected script and the token is gone. Avoid it for sensitive tokens.…
Do not push all the bytes through the application server — it consumes memory/bandwidth and caps the payload. Use direct-to-storage with presigned URLs. Presigned flow (S3): 1. The client calls an API to request permission to upload. The server authenticates + authorizes, checks the file…
Separate ingesting the image from serving the image. Ingest (upload): the client uploads the original straight to object storage via a presigned URL (as in the large-file item). Validate type/size before issuing the URL. Transform: two common approaches — - Eager (pre-generate): after upload, an…
Three approaches, each suiting a context: - Object storage (S3/GCS/R2): store the bytes in storage, keep only metadata + key/URL in the DB. Pros: near-infinite scale, cheap, easy CDN serving, no load on the app server. Cons: needs an external service, and every read or…
Do not send inline in the request. SMTP/providers can be slow or fail transiently; if you wait, the response hangs, and a send failure fails the whole signup even though the user was already created. Design: write the user to the DB → push a…
For a table with millions of rows, settle on cursor (keyset) for the main API; keep offset only for an admin screen that must jump to page N over modest data. The query: the anchor is the last row of the previous page, compared as…
Settle the mechanism first: the client sends a unique idempotency key per ordering intent; the first time, the server creates the order and stores the result under that key, and on a repeat of the same key it replays the stored result instead of creating…
Problem: loading everything into memory and returning it in one synchronous HTTP request → high RAM, exceeds proxy/gateway timeouts. Two approaches: 1. Streaming response (moderate/large data): - Query in batches (cursor/LIMIT), write each chunk to the response stream with Transfer-Encoding: chunked, never holding it all…
Four common algorithms: fixed window (count per fixed time bucket — cheapest, but lets through twice the cap at a window boundary), sliding window (smoother, more memory), token bucket (refills steadily, allows spending up to the cap in a burst), leaky bucket (flattens the output…
JOIN types (example: users ↔ orders): - INNER JOIN: only rows matching in both tables — users with at least one order. - LEFT JOIN: all left-table rows + matches from the right; no match → right columns are NULL — every user, including those…
- PUT = replace the whole record: the client must send the full payload; omitted fields count as deleted/reset (RFC 9110). - PATCH = partial update: send only the fields that change (RFC 5789). Idempotency (repeat the call, same final state): - PUT is idempotent…
- Hard delete: a real DELETE — the data is gone, tables/indexes stay lean, but there is no recovery and no trace. - Soft delete: only mark the row deleted (a deletedat timestamp column, NULL = alive); every read query must filter WHERE deletedat IS…
Go from the nouns of the domain → tables, then settle relationships and constraints. Core order tables: The decisions worth voicing: - n–n relationships get a junction table: one order has many products, one product appears in many orders → orderitems. - Snapshot the price…
N+1 happens when you fetch a list then loop, issuing a sub-query for each element: 1 query for N parent records + N queries for children → N+1 round-trips to the DB. Common with ORMs when accessing a relation inside a loop (lazy loading). Example:…
Redis is an in-memory key–value store (data lives mainly in RAM) → extremely fast reads/writes (typically sub-millisecond). Its strength is that it stores more than strings — it is a "data structure server" with several native types: - String: a single value (page cache, tokens,…
Both are transport-layer protocols, but they trade off reliability vs speed differently. - TCP — connection-oriented, reliable: a 3-way handshake, guaranteed, in-order delivery, with error checking, retransmission, flow control and congestion control. Higher overhead and latency. Use when data loss is unacceptable: HTTP/HTTPS, email, SSH,…
DNS (Domain Name System) is the internet's "phone book": it translates memorable domain names (example.com) into the IP addresses machines use to connect. When you visit a name that is not cached yet, resolution goes like this: 1. The browser, then the operating system, checks…
A load balancer spreads traffic across servers to avoid overload and remove single points of failure. - L4 (transport): routes by IP/port without reading content → fast, high throughput, but less flexible. - L7 (application): reads HTTP (path, header, cookie) → content-based routing, TLS termination,…
- Monolith: the whole app in one codebase/deploy. Pros: simple, easy to develop/test/deploy early, in-process calls are very fast, no distributed complexity. Cons: at scale, builds/deploys slow down, coupling grows, and it is hard to scale parts independently. - Microservices: split into small independently deployable…
A design pattern is a reusable solution to a recurring software design problem — not copy-paste code, but a template for organizing classes/objects. Benefits: a shared vocabulary (saying "Observer" conveys intent instantly), avoiding reinvention, and more extensible designs. The "Gang of Four" (GoF) group the…
Singleton ensures a class has exactly one instance across the app and provides a global access point to it. Common for shared resources: config, logger, connection pool, cache. Typical implementation: a private constructor + a static field holding the instance + a getInstance() method that…
Problem: when code creates objects with new ConcreteClass() everywhere, it becomes tightly bound to concrete classes → changing/adding a type means editing many places. - Factory Method: defines a method for creating objects, letting subclasses decide which concrete type to make. Calling code works with…
Five object-oriented design principles for maintainable, extensible, low-coupling code (compiled by Robert C. Martin): - S – Single Responsibility: a class should have one reason to change (one responsibility). - O – Open/Closed: open for extension, closed for modification — add features with new code,…