# Backend Developer Interview Questions with Answers

24 Backend interview questions, each with a model answer, the points to cover, common mistakes and the follow-ups interviewers ask.

_Source: Astra (https://useastra.in). Updated 2026-09-05._

### 1. How do you optimize database query performance in high-traffic environments?

Optimizing database queries involves indexing frequently queried columns, profiling slow queries with EXPLAIN plans, and rewriting joins or subqueries for efficiency. Use covering indexes to avoid lookups, partition large tables by date or range, and implement read replicas for horizontal scaling. Caching results at the application or distributed layer (Redis, Memcached) reduces database load. Connection pooling and limiting transaction scope further minimize contention. Regular maintenance tasks like index rebuilds and statistics updates sustain performance.

**Points a strong answer covers:**

- Measure first: EXPLAIN/ANALYZE, slow-query log
- Index for WHERE/JOIN/ORDER BY; avoid SELECT *
- Then: query rewrite, caching, read replicas, denormalization

**Common mistakes:**

- Jumping to caching before indexing/measuring

**Likely follow-ups:**

- Read a query plan aloud -- what do you look for?
- When does adding an index make things worse?

**What the interviewer is assessing:**

- Tests a measurement-first optimization discipline.

### 2. Explain the concept of database normalization and its trade-offs.

Database normalization organizes tables to reduce redundancy via normal forms. First normal form enforces atomic fields; second normal form removes partial dependencies; third normal form eliminates transitive dependencies. Normalization improves data integrity and simplifies updates but can incur performance overhead from additional joins. In high-read scenarios, denormalization or materialized views may be applied selectively. Balancing normalization and denormalization depends on access patterns, consistency requirements, and acceptable maintenance complexity.

**Points a strong answer covers:**

- Normal forms remove redundancy -> single source of truth
- Fewer update anomalies; more joins
- Denormalize deliberately for read-heavy paths

**Common mistakes:**

- Reciting forms without the anomaly rationale

**Likely follow-ups:**

- Show an update anomaly 3NF prevents
- When did you denormalize on purpose?

**What the interviewer is assessing:**

- Tests schema-design judgment, not memorized forms.

### 3. How would you implement pagination in a REST API?

Implement pagination using limit and offset parameters or cursor-based approaches. Offset-based pagination accepts page and size parameters, but performance degrades on large offsets. Cursor-based pagination returns a token referencing the last item, enabling efficient retrieval of the next page without scanning skipped rows. Include metadata like nextCursor or hasMore in responses. Ensure stable sort ordering to prevent missing or duplicate records when underlying data changes during pagination.

**Points a strong answer covers:**

- Offset/limit: simple, degrades at depth, unstable under inserts
- Cursor/keyset: WHERE id > last -- stable + fast
- Return next-cursor token; index the sort key

**Common mistakes:**

- Only knowing offset pagination

**Likely follow-ups:**

- Why does OFFSET 100000 get slow?
- How do you paginate a feed sorted by score?

**What the interviewer is assessing:**

- Practical API craftsmanship check.

### 4. What strategies ensure secure authentication for backend services?

Use JSON Web Tokens (JWT) or opaque tokens with short lifespans to authenticate API clients, transmitting tokens via secure headers. Implement refresh tokens for session persistence, stored securely, and rotate them periodically. Protect credentials with salted, hashed passwords using bcrypt or Argon2. Enforce HTTPS/TLS to encrypt data in transit. Employ multi-factor authentication, role-based access control, and OAuth2 flows when integrating third-party identity providers. Regularly audit and revoke compromised tokens.

**Points a strong answer covers:**

- Short-lived tokens (JWT/opaque) over TLS only
- Refresh rotation, secure storage, revocation path
- Scope/least privilege; secrets in managers, MFA for humans

**Common mistakes:**

- Long-lived static API keys as the answer

**Likely follow-ups:**

- Access vs refresh token lifetimes -- why?
- Where do you store tokens in a browser app?

**What the interviewer is assessing:**

- Tests end-to-end auth threat thinking.

### 5. Describe how you would design a logging and monitoring system.

A robust logging system centralizes structured logs (JSON) from services into a log aggregator like ELK or Splunk. Include contextual metadata (request IDs, user IDs, timestamps) for traceability. Monitor metrics (latency, error rates) with time-series databases like Prometheus and visualize dashboards in Grafana. Set alerts on thresholds and anomalies (e.g., high 5xx rates). Implement distributed tracing (Jaeger, Zipkin) to follow requests across microservices. Retain logs per compliance requirements and archive older data periodically.

**Points a strong answer covers:**

- Structured logs (JSON) + correlation IDs
- Centralize (ELK/Loki); metrics + traces alongside (three pillars)
- Alert on symptoms (SLOs), not every error

**Common mistakes:**

- "Just use ELK" with no correlation/alerting story

**Likely follow-ups:**

- How does a correlation ID flow through 5 services?
- Logs vs metrics vs traces -- when each?

**What the interviewer is assessing:**

- Tests observability maturity beyond tooling names.

### 6. Explain the difference between optimistic and pessimistic locking."

Optimistic locking assumes minimal conflict, allowing concurrent transactions to read data and check a version or timestamp before committing updates. If the version changed, the transaction retries. It suits low-contention scenarios, maximizing throughput. Pessimistic locking acquires row or table locks to prevent other transactions from reading or writing until the lock is released. It ensures data integrity under high contention but can cause deadlocks and reduce concurrency. Choose based on conflict frequency and performance requirements.

**Points a strong answer covers:**

- Optimistic: version check at write; retry on conflict -- high concurrency, rare conflicts
- Pessimistic: lock up front -- contention-heavy flows
- Choose by conflict probability and cost of retry

**Common mistakes:**

- Cannot map each to a concrete use case

**Likely follow-ups:**

- Implement optimistic locking in SQL -- what column?
- Where do deadlocks come from in pessimistic mode?

**What the interviewer is assessing:**

- Concurrency-control judgment test.

### 7. How do you handle file uploads in a backend application?

Handle file uploads by streaming data directly to object storage (e.g., AWS S3) to avoid server memory bloat. Generate pre-signed URLs for clients to upload securely. Validate file types and size limits. Scan for viruses or malicious content. Store metadata (filename, size, content type, storage path) in the database. Implement chunked uploads and resumable sessions for large files. Delete unused or expired files via scheduled jobs to manage storage costs.

**Points a strong answer covers:**

- Stream to object storage (S3), not app memory/disk
- Validate type/size; virus scan; signed URLs for direct upload
- Metadata in DB, file in blob store; async post-processing

**Common mistakes:**

- Storing files in the database
- Loading whole file into memory

**Likely follow-ups:**

- Why presigned URLs?
- Resumable uploads for large files?

**What the interviewer is assessing:**

- Tests practical file-pipeline design.

### 8. Describe how webhooks work and how to implement retry logic."

Webhooks push events to external URLs via HTTP POST. Upon a triggering event, the backend serializes payload and HTTP headers, sending to subscriber endpoints. Implement idempotent receivers to handle repeated deliveries safely. Use a retry policy with exponential backoff for transient failures (5xx or timeouts) and dead-letter queues or administrative alerts for persistent errors. Sign payloads with HMAC to verify authenticity on the receiver side and prevent spoofing.

**Points a strong answer covers:**

- Webhook = provider POSTs events to your URL
- Verify signatures; respond fast, process async
- Retries with backoff + idempotent handlers (dedupe by event ID)

**Common mistakes:**

- No signature verification
- Sync heavy processing in the handler

**Likely follow-ups:**

- Provider retries and you double-process -- prevent how?
- Webhooks vs polling trade-offs?

**What the interviewer is assessing:**

- Tests event-integration robustness.

### 9. What considerations are important when designing microservices?

Microservices should be loosely coupled and bounded by business capabilities. Design clear, versioned APIs with backward compatibility. Choose appropriate communication patterns: synchronous HTTP/gRPC for real-time needs, asynchronous messaging (Kafka, RabbitMQ) for decoupling. Implement centralized configuration, service discovery, and distributed tracing. Use containerization and orchestrators (Kubernetes) for deployment. Ensure data ownership per service to avoid shared databases, enforcing eventual consistency through events. Monitor and handle failure gracefully with circuit breakers.

**Points a strong answer covers:**

- Service boundaries by business capability (DDD)
- Own data per service; API contracts; async where possible
- Platform cost: observability, deploys, service discovery

**Common mistakes:**

- Boundaries by tech layer instead of domain

**Likely follow-ups:**

- How small is too small?
- Shared database -- why is it an anti-pattern?

**What the interviewer is assessing:**

- Tests decomposition judgment.

### 10. How would you secure communication between microservices?

Secure microservice communication via mutual TLS to authenticate both client and server, encrypting data in transit. Use service mesh (Istio) for centralized certificate management and observability. Employ JWT or mTLS-based identity tokens for authorization at each service boundary. Encrypt sensitive payload fields at the application layer. Rotate certificates regularly and enforce least-privilege network policies. Audit access logs and monitor for unauthorized attempts or expired credentials.

**Points a strong answer covers:**

- mTLS for service identity + encryption
- Short-lived certs via mesh/SPIFFE; authZ per call
- Network policies + zero-trust: never rely on being "inside"

**Common mistakes:**

- Trusting the internal network

**Likely follow-ups:**

- mTLS vs JWT between services?
- How does a mesh rotate certs?

**What the interviewer is assessing:**

- Zero-trust literacy check.

### 11. Describe how you would manage environment-specific configurations."

Manage configurations using environment variables or a configuration service (Consul, etcd). Store secrets encrypted in vault services (HashiCorp Vault) and inject at runtime. Use separate configuration files per environment (development, staging, production) with hierarchical overrides. Automate configuration deployment via CI/CD pipelines. Validate configuration schemas at startup to catch errors early. Version control non-sensitive defaults and ensure secret rotation policies are in place.

**Points a strong answer covers:**

- Config per environment outside code (env vars, config service)
- Secrets separate from config; typed + validated at boot
- Same artifact deployed everywhere; only config differs

**Common mistakes:**

- Baking env-specific builds

**Likely follow-ups:**

- Config drift between envs -- prevention?
- Feature flags vs config?

**What the interviewer is assessing:**

- 12-factor operations check.

### 12. How do you implement transactional workflows spanning multiple services?"

Implement distributed transactions via Saga pattern: orchestrate local transactions across services, compensating on failure to undo partial work. Two variants include choreography (events trigger next steps) and orchestration (a central coordinator manages the workflow). Use idempotent operations and persistent state machines to track progress. Avoid two-phase commit due to blocking and single point of failure in microservices. Ensure visibility with audit logs and monitoring dashboards.

**Points a strong answer covers:**

- Distributed transaction -> saga with compensations
- Outbox pattern: DB write + event publish atomically
- Idempotent steps; monitor for stuck sagas

**Common mistakes:**

- Proposing 2PC across microservices

**Likely follow-ups:**

- Explain the outbox pattern mechanics
- What does a compensation look like for shipping?

**What the interviewer is assessing:**

- Tests distributed-consistency toolkit.

### 13. What is the fundamental difference between HTTP (Hypertext Transfer Protocol) and HTTPS, and why is HTTPS non-negotiable for modern web applications?

HTTP is the standard protocol for web communication, but it transmits data in plain text, making it vulnerable to eavesdropping. HTTPS (HTTP Secure) adds a layer of security by using SSL/TLS (Secure Sockets Layer/Transport Layer Security) to encrypt the data. This encryption ensures that data transferred between the user's browser and the server is private and integral, which is essential for protecting sensitive user information like passwords and credit card numbers.

**Points a strong answer covers:**

- HTTPS = HTTP over TLS: encryption, integrity, authentication
- Prevents eavesdropping and MITM attacks
- Required for SEO, browser trust, modern APIs (cookies, HTTP/2)

**Common mistakes:**

- Saying HTTPS is just "secure" without naming encryption/integrity/authentication
- Not knowing certificates involve a trusted CA

**Likely follow-ups:**

- How does the TLS handshake establish a shared key?
- What is certificate pinning?

**What the interviewer is assessing:**

- Tests if you understand the transport security layer every backend sits on, not just the acronym.

### 14. What is an API (Application Programming Interface), and what is its primary role in backend development for connecting services?

An API is a set of rules and protocols that allows different software applications to communicate with each other. In backend development, its primary role is to expose the application's business logic and data to external consumers, such as a frontend web application, a mobile app, or another backend service. It acts as a contract, defining the 'how-to' for requesting and receiving information, without exposing the internal implementation details.

**Points a strong answer covers:**

- API = contract for programmatic interaction between services
- Decouples client from server implementation
- Defines endpoints, inputs/outputs, error semantics

**Common mistakes:**

- Defining API only as "a URL you call"
- No mention of contracts or versioning

**Likely follow-ups:**

- What makes an API well-designed?
- REST vs RPC -- when each?

**What the interviewer is assessing:**

- Checks you see APIs as stable contracts, not just routes.

### 15. Explain the client-server model and how a backend developer's code fits into this common architecture.

The client-server model is a distributed architecture that separates tasks between 'clients' (service requesters) and 'servers' (service providers). The client, often a web browser or mobile app, is responsible for the user interface. The backend developer's code runs on the server, which is responsible for business logic, data processing, and database interactions. The server 'serves' data to the client upon request via a network, typically using an API.

**Points a strong answer covers:**

- Client requests, server processes and responds
- Backend owns business logic, persistence, auth
- Statelessness lets servers scale horizontally behind LBs

**Common mistakes:**

- Describing only the browser side
- Ignoring where state lives

**Likely follow-ups:**

- Where do CDNs fit in this model?
- How do websockets change it?

**What the interviewer is assessing:**

- Tests basic architectural orientation -- where your code runs and why.

### 16. What is the purpose of a database index, and how does it improve query performance in a relational database?

A database index is a data structure, typically a B-Tree, that improves the speed of data retrieval operations on a database table. It works like an index in a book: instead of scanning the entire table (a 'full table scan') to find a specific row, the database can use the index to find the exact location of the data quickly. This dramatically speeds up `SELECT` queries with `WHERE` clauses, but it comes at the cost of slightly slower writes (`INSERT`, `UPDATE`), as the index must also be updated.

**Points a strong answer covers:**

- Index = sorted structure (usually B-Tree) for fast lookup
- Turns O(n) scans into O(log n) seeks
- Costs: slower writes, storage overhead
- Index columns used in WHERE/JOIN/ORDER BY

**Common mistakes:**

- Saying indexes "make queries fast" with no mechanism
- Not knowing writes get slower

**Likely follow-ups:**

- Why not index every column?
- What is a covering index?

**What the interviewer is assessing:**

- Tests if you understand the read/write trade-off, not just that indexes exist.

### 17. Can you describe the precise difference between 'GET' and 'POST' requests in the context of a RESTful API?

A `GET` request is used to retrieve or 'get' data from a server. It is considered a safe and idempotent method, meaning it can be called multiple times without changing the server's state. Parameters are sent via the URL. A `POST` request is used to send new data to the server to create a new resource (e.g., creating a new user). It is not idempotent, as calling it multiple times will create multiple new resources. Its payload is carried in the request body.

**Points a strong answer covers:**

- GET: read, no body, idempotent, cacheable, params in URL
- POST: create/mutate, body payload, not idempotent
- Semantics matter for caches, proxies, retries

**Common mistakes:**

- Only saying "GET gets, POST posts"
- Missing idempotency and caching implications

**Likely follow-ups:**

- Is DELETE idempotent? PUT vs POST?
- Why should GET never mutate state?

**What the interviewer is assessing:**

- Checks command of HTTP semantics that correctness and caching depend on.

### 18. What is JSON (JavaScript Object Notation), and why has it become the standard format for data exchange in modern APIs?

JSON is a lightweight, text-based data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is language-independent but uses conventions from JavaScript. It has become the standard for APIs because it is less verbose than XML and maps directly to objects and data structures used in modern programming languages, making data serialization and deserialization extremely efficient.

**Points a strong answer covers:**

- Lightweight text format, human-readable, language-agnostic
- Maps naturally to objects/dicts
- Beat XML on verbosity and parsing ease

**Common mistakes:**

- No comparison to alternatives
- Unaware of JSON type limitations (no dates, int precision)

**Likely follow-ups:**

- Where does JSON fall short (types, size)?
- When Protobuf instead?

**What the interviewer is assessing:**

- Tests whether you can reason about serialization trade-offs.

### 19. What is the 'public' keyword in object-oriented programming, and how does it differ from 'private' and 'protected' access modifiers?

Access modifiers control the visibility of classes, methods, and variables. 'Public' means the member is accessible from any other class in any package. 'Private' is the most restrictive; the member is only accessible from within its own class. 'Protected' is in-between; the member is accessible within its own package and by subclasses in other packages. These are crucial for encapsulation, which hides the internal state of an object and only exposes necessary functionalities.

**Points a strong answer covers:**

- public: accessible anywhere; private: class-only; protected: class + subclasses
- Encapsulation: hide internals, expose stable surface
- Smaller public surface = safer refactoring

**Common mistakes:**

- Reciting keywords without the encapsulation rationale

**Likely follow-ups:**

- Why default to private?
- How does encapsulation aid testing?

**What the interviewer is assessing:**

- Tests OOP fundamentals via the why, not the syntax.

### 20. What is the purpose of the 'try...catch' block in programming, and why is it important for robust backend error handling?

A 'try...catch' block is a mechanism for handling exceptions or runtime errors. Code that might fail (e.g., a database call or file read) is placed inside the 'try' block. If an exception occurs within that block, the program's normal execution is stopped, and control is passed to the 'catch' block. This block can then log the error and send a graceful response to the user (like an HTTP 500 error) instead of crashing the entire application server.

**Points a strong answer covers:**

- try/catch isolates failure handling from happy path
- Backend must catch, log, and translate errors to proper responses
- Uncaught errors crash processes or leak internals

**Common mistakes:**

- Catching and swallowing errors silently
- Returning stack traces to clients

**Likely follow-ups:**

- Checked vs unchecked exceptions?
- Global error middleware -- how?

**What the interviewer is assessing:**

- Tests production-mindedness about failure, not syntax.

### 21. What is 'middleware' in the context of a backend framework like Express.js or Django, and provide a common use case.

Middleware refers to functions that execute in the middle of the request-response cycle, after the server receives a request and before it sends a response. These functions have access to the request object, the response object, and the next middleware function in the chain. Common use cases include: logging every incoming request, parsing the body of a request (e.g., `bodyParser`), checking for user authentication tokens, or setting security headers.

**Points a strong answer covers:**

- Middleware = functions in the request pipeline before/after handlers
- Cross-cutting concerns: auth, logging, rate limiting, CORS
- Order matters; each can pass or short-circuit

**Common mistakes:**

- Only naming one use case
- Not knowing middleware order matters

**Likely follow-ups:**

- Order auth vs logging -- why?
- How does Express next() work?

**What the interviewer is assessing:**

- Tests understanding of request lifecycle architecture.

### 22. Explain the difference between SQL and NoSQL databases at a high level. When might you choose one over the other?

SQL databases (like PostgreSQL, MySQL) are relational, store data in structured tables with predefined schemas, and use SQL for queries. They guarantee ACID transactions, making them ideal for applications requiring strong consistency, like banking. NoSQL databases (like MongoDB, Cassandra) are non-relational, have flexible schemas, and are designed for horizontal scalability. They are often chosen for large-scale applications with unstructured or semi-structured data, like social media feeds or IoT data, where high availability is prioritized.

**Points a strong answer covers:**

- SQL: schema, joins, ACID transactions -- relational integrity
- NoSQL: flexible schema, horizontal scale, varied models (doc/KV/graph)
- Choose by access patterns, consistency needs, scale

**Common mistakes:**

- "NoSQL is faster" with no context
- Choosing by hype instead of access patterns

**Likely follow-ups:**

- Can Postgres do documents (JSONB)?
- What consistency do you give up and when is that OK?

**What the interviewer is assessing:**

- Tests decision-making by requirements, not tribal preference.

### 23. What does it mean for a web application to be 'stateless', and why is this a desirable property for scalability?

A stateless application is one where the server does not store any client-specific session data between requests. Each request from a client must contain all the information necessary for the server to fulfill it (e.g., a JWT token for authentication). This is highly desirable for scalability because any server in a cluster can handle any request. It simplifies horizontal scaling, as you can add or remove servers without worrying about losing session data or needing 'sticky sessions' at the load balancer.

**Points a strong answer covers:**

- No session state on the server between requests
- Any instance can serve any request -> easy horizontal scaling
- State moves to tokens (JWT) or shared stores (Redis)

**Common mistakes:**

- Confusing stateless app with stateless protocol
- Not saying where state goes instead

**Likely follow-ups:**

- Where do sticky sessions fit?
- Trade-offs of JWT vs server session?

**What the interviewer is assessing:**

- Tests if you connect statelessness to scalability mechanically.

### 24. What are HTTP status codes, and can you provide examples of codes from the 2xx, 4xx, and 5xx series?

HTTP status codes are standard responses from a server indicating the outcome of a client's request. **2xx (Success):** The request was successful. `200 OK` is standard, and `201 Created` is used after a successful `POST`. **4xx (Client Error):** The client made a mistake. `404 Not Found` means the resource doesn't exist, and `401 Unauthorized` (or `403 Forbidden`) means the user lacks credentials or permissions. **5xx (Server Error):** The server failed. `500 Internal Server Error` is a generic catch-all for an unhandled exception in the code.

**Points a strong answer covers:**

- 2xx success (200, 201, 204)
- 4xx client error (400, 401, 403, 404, 429)
- 5xx server error (500, 502, 503)
- Correct codes drive client behavior, retries, monitoring

**Common mistakes:**

- Returning 200 with an error body
- Not distinguishing client vs server fault

**Likely follow-ups:**

- 401 vs 403?
- When 422 vs 400?

**What the interviewer is assessing:**

- Tests API craftsmanship -- status codes are your error contract.

Full topic: https://useastra.in/interview-questions/topic/backend
