Skip to content

Backend Developer Interview Questions & Answers

40 questions for Backend Developer interviews — 1 easy, 33 medium, 6 hard.

About the Backend Developer role

Designs APIs, data models and business logic for web and mobile products. Focuses on correctness, performance and security: writing efficient queries, adding caching, handling authentication and making integrations reliable with retries and idempotency. Collaborates closely with frontend, QA and DevOps, and participates in code reviews and on-call rotations.

REST API design SQL and MongoDB JWT and OAuth Redis caching Unit testing
Solved for this roleStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

How do you run integration tests against a real database in CI?

Save to ▾
Show answer
Start a disposable database for the test run, using Docker Compose services in CI, Testcontainers from the test code, or mongodb-memory-server for MongoDB. Run migrations before tests, seed minimal data per test, and clean tables between tests or wrap each test in a rolled-back transaction. Use a separate DATABASE_URL so tests can never touch production data.
02

How do access tokens and refresh tokens work together?

Save to ▾
Show answer
The access token is short-lived, around 5 to 15 minutes, and sent with each API request. The refresh token is long-lived, stored securely in an HttpOnly cookie, and used only at a refresh endpoint to get a new access token. Rotate refresh tokens on every use and store their hashes server-side, so a stolen or reused token can be detected and the session revoked.
03

What is the OWASP Top 10 and which items matter most for Node.js APIs?

Save to ▾
Show answer
The OWASP Top 10 lists the most critical web application security risks. For Node APIs the most relevant are broken access control, injection, cryptographic failures, security misconfiguration, vulnerable and outdated components, authentication failures and server-side request forgery. OWASP also publishes an API Security Top 10, which highlights broken object level authorisation, where users access others' data by changing an ID.
04

How do you use a MongoDB transaction in Mongoose?

Save to ▾
Show answer
const session = await mongoose.startSession(); try { await session.withTransaction(async () => { await Account.updateOne( { _id: fromId, balance: { $gte: amount } }, { $inc: { balance: -amount } }, { session } ); await Account.updateOne({ _id: toId }, { $inc: { balance: amount } }, { session }); await Transfer.create([{ fromId, toId, amount }], { session }); }); } finally { await session.endSession(); } // Requires a replica set or Atlas cluster.
05

What is the MongoDB aggregation pipeline? Give an example.

Save to ▾
Show answer
// Top 5 cities by revenue in the last 30 days const since = new Date(Date.now() - 30 * 864e5); const result = await Order.aggregate([ { $match: { status: 'paid', createdAt: { $gte: since } } }, { $group: { _id: '$city', revenue: { $sum: '$amount' }, orders: { $sum: 1 } } }, { $sort: { revenue: -1 } }, { $limit: 5 } ]); // Each stage transforms documents; put $match early to use indexes.
06

How do you handle a breaking API change request from a product manager close to a release?

Save to ▾
Show answer
I would first understand why it is needed and who consumes the API. Then I explain the impact on existing clients, propose a non-breaking path such as adding a new field or a v2 endpoint, and estimate effort and risk. Result in a past case: we shipped the additive change on time and scheduled removal of the old field for the next quarter.
07

A security audit finds that users can see other users' orders by changing the order ID in the URL. How do you fix it?

Save to ▾
Show answer
This is broken object level authorisation. Every query must be scoped to the authenticated user: Order.findOne({ _id: id, userId: req.user.id }), returning 404 if not found. Put this check in a shared service or middleware so no route can skip it, add tests that try other users' IDs, and consider non-guessable IDs like UUIDs as defence in depth, not as the fix.
08

What is database normalisation and when would you denormalise?

Save to ▾
Show answer
Normalisation organises tables to remove duplicate data and update anomalies, typically up to third normal form, for example keeping customers and orders in separate tables linked by foreign keys. You denormalise for read performance, such as storing a product name on an order line or a precomputed order count on a user, when joins become expensive. Denormalised data must be kept in sync.
09

How would you add OTP-based login for an Indian mobile app?

Save to ▾
Show answer
Generate a random 6-digit OTP with crypto.randomInt, store only its hash in Redis with a 5-minute TTL and an attempt counter, and send it through an SMS provider on a DLT-registered template. Verify with a timing-safe compare, limit to about 3 to 5 attempts and rate limit sends per number and IP. On success, issue access and refresh tokens and delete the OTP.
10

Explain the Node.js event loop and its main phases.

Save to ▾
Show answer
The event loop lets Node.js run asynchronous callbacks on a single thread. Each iteration passes through phases: timers (setTimeout, setInterval), pending callbacks, poll (waits for and runs I/O callbacks), check (setImmediate), and close callbacks. Between phases Node drains the process.nextTick queue and the promise microtask queue. Understanding phases explains why setImmediate runs before a 0 ms timer inside an I/O callback.
11

Why is structured logging important and which libraries are used?

Save to ▾
Show answer
Structured logs are JSON lines with fields like level, timestamp, requestId, userId and message, so tools like ELK, Loki, Datadog or CloudWatch can search and aggregate them. pino is fast and popular, winston is flexible with many transports. Log at correct levels, include a correlation ID per request, and never log passwords, tokens, full card numbers or Aadhaar numbers.
12

What is a compound index and why does field order matter?

Save to ▾
Show answer
A compound index covers multiple fields, such as { userId: 1, createdAt: -1 }. It supports queries that use a prefix of the fields, so it helps queries on userId alone or userId plus createdAt, but not createdAt alone. A good rule in MongoDB is ESR: put equality fields first, then sort fields, then range fields, to avoid in-memory sorts.
13

What is HATEOAS and is it used in real projects?

Save to ▾
Show answer
HATEOAS, Hypermedia as the Engine of Application State, means responses include links telling the client what it can do next, for example an order response with links to cancel or pay. It makes APIs more discoverable and decoupled. In practice most JSON APIs only partly use it, such as pagination links, because clients are usually built against documented endpoints.
14

When would you choose NestJS or Fastify over Express?

Save to ▾
Show answer
Choose Fastify when raw performance and built-in schema validation matter; it is faster than Express thanks to optimised routing and serialisation. Choose NestJS for large teams that want structure: modules, dependency injection, decorators and first-class TypeScript, similar to Spring or Angular. Express still suits small to medium services and teams that prefer flexibility and a huge middleware ecosystem.
15

Your API's p99 latency is high during peak hours even though CPU is only 40 percent. What could be wrong?

Save to ▾
Show answer
Low CPU with high latency suggests waiting, not computing. Check database query times and connection pool wait, slow downstream APIs, Redis latency, DNS lookups without keep-alive agents, garbage collection pauses and event loop lag from occasional heavy requests. Use distributed tracing with OpenTelemetry to see where time goes, then add indexes, caching, timeouts or more pool connections.
16

What is NoSQL injection in MongoDB and how do you prevent it?

Save to ▾
Show answer
If you pass req.body directly into a query, an attacker can send { "password": { "$ne": null } } and bypass checks. Prevent it by validating and casting input types with zod or Joi, rejecting objects where strings are expected, enabling Mongoose strictQuery and sanitizeFilter, and never building queries from raw user objects. Avoid $where and server-side JavaScript evaluation.
17

How would you design authentication for a system of ten microservices?

Save to ▾
Show answer
Centralise login in an identity service or provider such as Keycloak, Auth0 or Cognito that issues short-lived JWTs signed with RS256. The API gateway validates tokens, and each service verifies the signature using the public keys from a JWKS endpoint, so no shared secret is needed. Use service-to-service tokens or mTLS for internal calls and keep authorisation checks inside each service.
18

How do you design a consistent error response format for an API?

Save to ▾
Show answer
Use one structure everywhere, for example { "error": { "code": "VALIDATION_FAILED", "message": "Email is invalid", "details": [{ "field": "email" }], "requestId": "abc123" } }. Many teams follow RFC 9457 Problem Details with type, title, status and detail. Use machine-readable codes for clients, human messages for display, and never leak stack traces or SQL errors.
19

Tell me about a time you found a security issue in code and how you handled it.

Save to ▾
Show answer
Situation: during code review I noticed an admin export route that only hid the button in the frontend. Task: make sure no regular user could call it. Action: I reproduced it with a normal user token, reported it privately to my lead, added role middleware and tests, and checked similar routes. Result: we fixed four endpoints before release and added an authorisation checklist to pull requests.
20

What are the common strategies for API versioning?

Save to ▾
Show answer
URL versioning like /api/v1/orders is the most common and easy to route and cache. Header versioning uses a custom header or Accept media type, keeping URLs clean but less visible. Query versioning like ?version=2 is simple but messy. Whatever you choose, version only for breaking changes, support old versions for a deprecation period and announce sunset dates.
21

Design endpoints for a simple e-commerce cart and checkout.

Save to ▾
Show answer
GET /api/v1/cart returns the current user's cart. POST /api/v1/cart/items adds an item with productId and quantity. PATCH /api/v1/cart/items/:itemId changes quantity, and DELETE removes it. POST /api/v1/orders creates an order from the cart with an Idempotency-Key header. GET /api/v1/orders/:id shows status, and POST /api/v1/orders/:id/cancel handles cancellation as an action.
22

Write a retry function with exponential backoff for a flaky API call.

Save to ▾
Show answer
async function retry(fn, retries = 3, baseMs = 200) { for (let attempt = 0; ; attempt++) { try { return await fn(); } catch (err) { if (attempt >= retries) throw err; const delay = baseMs * 2 ** attempt + Math.random() * 100; await new Promise((r) => setTimeout(r, delay)); } } } await retry(() => paymentClient.getStatus(id));
23

Where should a web app store tokens: localStorage or cookies?

Save to ▾
Show answer
localStorage is readable by any JavaScript on the page, so an XSS bug can steal tokens. HttpOnly, Secure, SameSite cookies cannot be read by JavaScript, which is safer for refresh tokens and session IDs. Cookies require CSRF protection, which SameSite=Lax or Strict plus CSRF tokens provide. A common pattern keeps the access token in memory and the refresh token in an HttpOnly cookie.
24

How do you implement role-based access control (RBAC) in an API?

Save to ▾
Show answer
Define roles such as admin, manager and customer, and map them to permissions like order:read or order:refund. Put the role or permissions in the token or load them per request, and check them in middleware before handlers. For ownership rules, also check resource data, for example a customer can view only orders where order.userId equals req.user.id. Test both allowed and denied paths.
25

Compare offset pagination and cursor pagination.

Save to ▾
Show answer
Offset pagination uses page and limit, translated to LIMIT and OFFSET. It is simple and allows jumping to a page, but gets slow on large tables and can skip or repeat rows when data changes. Cursor pagination uses the last seen value, such as id or created_at, to fetch the next set with a WHERE clause. It is fast and stable, ideal for feeds and infinite scroll.
26

What is soft delete and what are its trade-offs?

Save to ▾
Show answer
Soft delete marks a record as deleted with a flag or deletedAt timestamp instead of removing it, so data can be restored and audited. Trade-offs: every query must filter out deleted rows, unique constraints need care, tables grow over time and privacy laws such as India's DPDP Act may require real deletion of personal data on request. Use partial indexes and periodic purging.
27

Tell me about a time a database change caused an issue and what you learned.

Save to ▾
Show answer
Situation: I added a NOT NULL column with a default to a large MySQL table during business hours. Task: the migration locked the table and checkout slowed down. Action: I rolled back, rewrote it as add nullable column, backfill in batches, then add the constraint, and ran it at low traffic after testing on a production-size copy. Result: no downtime, and we added a migration review checklist.
28

What is idempotency and how do you implement idempotency keys for a payment API?

Save to ▾
Show answer
An idempotent operation gives the same result when repeated. For POST /payments, the client sends a unique Idempotency-Key header. The server stores the key with the request hash and response, for example in Redis or a table with a unique index. If the same key arrives again, it returns the saved response instead of charging twice. Keys expire after about 24 hours.
29

How do you implement and secure webhooks that your API sends to customers?

Save to ▾
Show answer
Send a POST with a JSON event, a unique event ID and timestamp. Sign the body with HMAC-SHA256 using a per-customer secret and include it in a header, so receivers verify authenticity and reject old timestamps to stop replays. Retry failures with exponential backoff, log delivery attempts and make events idempotent so receivers can safely handle duplicates.
30

How do you implement filtering and sorting safely from query parameters?

Save to ▾
Show answer
const ALLOWED_SORT = ['price', 'createdAt', 'name']; router.get('/products', async (req, res) => { const filter = {}; if (req.query.category) filter.category = String(req.query.category); if (req.query.maxPrice) filter.price = { $lte: Number(req.query.maxPrice) }; const field = ALLOWED_SORT.includes(req.query.sort) ? req.query.sort : 'createdAt'; const dir = req.query.order === 'asc' ? 1 : -1; res.json(await Product.find(filter).sort({ [field]: dir }).limit(50)); }); // Whitelist fields and cast types to block injection.
31

What is connection pooling and why is it important in Node.js?

Save to ▾
Show answer
Opening a database connection is slow, so a pool keeps a set of open connections that requests borrow and return. pg Pool, mysql2 and the MongoDB driver all pool by default. Size the pool based on database limits and instance count; too small causes waiting, too large overloads the database. In serverless functions, reuse the client across invocations or use a proxy like RDS Proxy.
32

A mobile app team complains your API returns too much data and is slow on 4G. What would you change?

Save to ▾
Show answer
Add field selection like ?fields=id,name,price, smaller list representations with details on a separate endpoint, pagination with sensible limits and gzip or Brotli compression. Support ETag and Cache-Control so unchanged data returns 304. If many screens need combined data, consider a Backend-for-Frontend layer or GraphQL tailored to the mobile app.
33

What is the N+1 query problem and how do you fix it?

Save to ▾
Show answer
N+1 happens when you run one query to fetch a list and then one extra query per item, for example loading 100 posts and then each author separately, causing 101 queries. Fix it with joins or eager loading in SQL ORMs like include in Prisma or Sequelize, populate or $lookup in MongoDB, batching with an IN query, or DataLoader in GraphQL.
34

Implement cursor-based pagination for a products endpoint.

Save to ▾
Show answer
router.get('/products', async (req, res) => { const limit = Math.min(Number(req.query.limit) || 20, 100); const cursor = req.query.cursor; const filter = cursor ? { _id: { $lt: cursor } } : {}; const items = await Product.find(filter) .sort({ _id: -1 }) .limit(limit + 1); const hasMore = items.length > limit; if (hasMore) items.pop(); res.json({ data: items, nextCursor: hasMore ? items[items.length - 1]._id : null }); });
35

How do you implement rate limiting on a login endpoint?

Save to ▾
Show answer
const rateLimit = require('express-rate-limit'); const { RedisStore } = require('rate-limit-redis'); const loginLimiter = rateLimit({ windowMs: 15 * 60 * 1000, limit: 5, standardHeaders: 'draft-7', legacyHeaders: false, keyGenerator: (req) => `${req.ip}:${req.body.email}`, store: new RedisStore({ sendCommand: (...a) => redis.sendCommand(a) }) }); app.post('/auth/login', loginLimiter, login); // Add account lockout or CAPTCHA after repeated failures.
36

Compare Prisma, Sequelize and TypeORM for SQL databases in Node.js.

Save to ▾
Show answer
Prisma uses a schema file to generate a fully typed client and has excellent TypeScript support and migrations, though complex raw SQL needs escape hatches. Sequelize is mature, promise-based and widely used in older JavaScript projects. TypeORM uses decorators and entity classes, familiar to Java and NestJS developers. Drizzle is a newer lightweight, SQL-like typed option. Pick based on TypeScript use and team familiarity.
37

Compare session-based authentication with JWT-based authentication.

Save to ▾
Show answer
Sessions store state on the server, often in Redis, and the client holds only a session ID cookie; logout and revocation are easy. JWTs are stateless, so any service can verify them without a lookup, which suits microservices and mobile apps, but revoking a token before expiry needs a denylist or short lifetimes. Many systems combine short-lived JWT access tokens with server-stored refresh tokens.
38

Tell me about an API you designed that you are proud of.

Save to ▾
Show answer
Situation: our support team used spreadsheets to track refunds. Task: I designed a refund API used by the admin panel and payment service. Action: I wrote the OpenAPI spec first, reviewed it with frontend and finance, added idempotency keys, clear error codes and pagination, and wrote contract tests. Result: integration took two days instead of a week, and refund errors dropped sharply.
39

When should you embed documents versus reference them in MongoDB?

Save to ▾
Show answer
Embed when data is read together, owned by the parent and bounded in size, such as addresses inside a user or line items inside an order. Reference when the related data is large, grows without limit, is shared across many documents or changes independently, such as products referenced by orders or comments on a viral post. Remember the 16 MB document size limit.
40

How do you manage database schema migrations in a Node.js project?

Save to ▾
Show answer
Use a migration tool such as Prisma Migrate, Knex, Sequelize CLI or TypeORM migrations, and commit migration files to Git. Each migration has up and ideally down steps and runs in CI and before deployment. For zero downtime, use expand and contract: add new columns first, deploy code that writes both, backfill, switch reads, then drop old columns in a later release.

Frequently asked questions

What does a Backend Developer do?

Designs APIs, data models and business logic for web and mobile products. Focuses on correctness, performance and security: writing efficient queries, adding caching, handling authentication and making integrations reliable with retries and idempotency. Collaborates closely with frontend, QA and DevOps, and participates in code reviews and on-call rotations.

Which skills are tested in a Backend Developer interview?

Expect questions on REST API design, SQL and MongoDB, JWT and OAuth, Redis caching, Unit testing. Most rounds also ask you to explain a project and solve one practical problem live.

How do I prepare for a Backend Developer interview?

Revise REST API Design, Databases: MongoDB, SQL and Redis, Authentication and Security first using the topic sheets, practise the questions on this page aloud, then do one full mock interview to practise timing.