InterviewTreedInterviewTreed

InterviewTreed Question Bank

Backend & API Engineering Interview Questions and Answers

Prepare for backend engineering and API development interviews, covering server-side architecture, REST APIs, authentication, database integration, performance, scalability, and production-ready backend systems.

Total Questions

130

Beginner

45

Intermediate

65

Advanced

20

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1Backend Architecture

What is backend architecture?

Backend architecture defines how server-side components, data stores, APIs, and infrastructure collaborate to fulfill application requirements.

Answer

Backend architecture defines how server-side components, data stores, APIs, and infrastructure collaborate to fulfill application requirements. A good design balances correctness, maintainability, scalability, security, and operational simplicity.

Syntax

client -> API -> application service -> repository -> database

Example

An order API validates a request, applies order rules in a service, and persists the order through a repository.

Code example

Controller -> OrderService.create() -> OrderRepository.save() -> Database

Diagram

Client -> Controller -> Service -> Repository -> Database

Key Points

  • Understand the purpose of what is backend architecture?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q2Backend Architecture

What is the difference between monolithic and microservices architecture?

A monolith deploys most application capabilities as one unit; microservices split capabilities into independently deployable services.

Answer

A monolith deploys most application capabilities as one unit; microservices split capabilities into independently deployable services. Microservices can improve independent scaling but add network, observability, deployment, and data-consistency complexity.

Syntax

monolith: one deployable; microservices: multiple service deployables

Example

A small internal inventory app may start as a modular monolith; separate catalog and payments only when independent ownership or scaling justifies it.

Code example

// Modular monolith: CatalogModule + OrdersModule in one deployment

Diagram

Monolith: [Catalog | Orders | Payments] -> one deployment
Microservices: [Catalog] [Orders] [Payments] -> separate deployments

Key Points

  • Understand the purpose of what is the difference between monolithic and microservices architecture?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q3Backend Architecture

What is a modular monolith?

A modular monolith keeps one deployment while enforcing clear module boundaries.

Answer

A modular monolith keeps one deployment while enforcing clear module boundaries. Modules expose intentional interfaces and avoid reaching into each other's internals, making the system simpler to operate than microservices while retaining architectural discipline.

Syntax

module A -> public interface of module B

Example

Keep billing rules inside a BillingModule and let OrdersModule call its exported service.

Code example

// OrdersModule imports BillingModule's exported BillingService

Diagram

OrdersModule -> BillingService interface -> BillingModule internals

Key Points

  • Understand the purpose of what is a modular monolith?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q4Backend Architecture

Explain layered architecture.

Layered architecture separates concerns such as transport/controllers, application services, domain logic, and persistence.

Answer

Layered architecture separates concerns such as transport/controllers, application services, domain logic, and persistence. Each layer should have a clear responsibility and dependencies should flow according to the chosen architecture rules.

Syntax

Controller -> Service -> Repository

Example

The controller parses HTTP input; a service applies business rules; a repository performs database operations.

Code example

@Controller('orders') class OrdersController { constructor(private readonly orders: OrdersService) {} }

Diagram

HTTP -> Controller -> Service -> Repository -> Database

Key Points

  • Understand the purpose of explain layered architecture.
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q7Backend Architecture

What is dependency injection and why use it?

Dependency injection supplies a class's dependencies from outside rather than constructing them internally.

Answer

Dependency injection supplies a class's dependencies from outside rather than constructing them internally. It improves testability, makes dependencies visible, and allows implementations to be swapped.

Syntax

constructor(private readonly repo: UserRepository) {}

Example

Inject a fake UserRepository in a unit test rather than connecting to a real database.

Code example

constructor(private readonly users: UsersService) {}

Diagram

Container creates dependencies -> injects them into consumer

Key Points

  • Understand the purpose of what is dependency injection and why use it?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q13Backend Architecture

Explain the repository pattern.

A repository provides a collection-like interface for retrieving and persisting domain objects while hiding persistence details.

Answer

A repository provides a collection-like interface for retrieving and persisting domain objects while hiding persistence details. Avoid creating abstractions that merely duplicate an ORM without adding value.

Syntax

repository.findById(id); repository.save(entity)

Example

OrderService depends on OrderRepository rather than embedding SQL in the controller.

Code example

interface OrderRepository { findById(id: string): Promise<Order | null> }

Diagram

Service -> Repository Interface -> ORM/SQL Adapter -> DB

Key Points

  • Understand the purpose of explain the repository pattern.
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q14Backend Architecture

What is a service layer?

The service layer coordinates use cases and business rules.

Answer

The service layer coordinates use cases and business rules. It should own application workflows, transaction boundaries where appropriate, and calls to repositories or external services, while controllers remain thin.

Syntax

controller -> service method -> persistence

Example

A TransferService checks account rules and coordinates debit and credit within a transaction.

Code example

async createOrder(input: CreateOrderInput) { /* validate rules and save */ }

Diagram

Controller -> OrderService -> Repositories / Gateways

Key Points

  • Understand the purpose of what is a service layer?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q15Backend Architecture

What is a DTO and why use one?

A Data Transfer Object defines the shape of data crossing a boundary.

Answer

A Data Transfer Object defines the shape of data crossing a boundary. Request DTOs support validation and avoid binding untrusted input directly to persistence entities or internal domain objects.

Syntax

CreateUserDto { email: string; password: string }

Example

Accept only name and email in a profile update DTO, not an arbitrary isAdmin field.

Code example

export class CreateUserDto { email: string; name: string; }

Diagram

HTTP payload -> DTO validation -> application input

Key Points

  • Understand the purpose of what is a dto and why use one?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q16Backend Architecture

How should configuration and secrets be managed?

Keep environment-specific configuration outside source code and inject secrets from a secret manager or protected environment.

Answer

Keep environment-specific configuration outside source code and inject secrets from a secret manager or protected environment. Validate required settings at startup, restrict access, and rotate credentials.

Syntax

process.env.DATABASE_URL

Example

Use separate database credentials per environment and never commit .env files containing production secrets.

Code example

const databaseUrl = process.env.DATABASE_URL; if (!databaseUrl) throw new Error('Missing DATABASE_URL');

Diagram

Secret Manager -> Runtime Environment -> Config Validation -> App

Key Points

  • Understand the purpose of how should configuration and secrets be managed?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q17Backend Architecture

What is a health check endpoint?

A liveness check indicates whether a process is running; a readiness check indicates whether it can serve traffic.

Answer

A liveness check indicates whether a process is running; a readiness check indicates whether it can serve traffic. Readiness may verify critical dependencies, while liveness should avoid failing merely because a downstream service is temporarily unavailable.

Syntax

GET /health/live; GET /health/ready

Example

A load balancer removes an instance from traffic when readiness fails during startup.

Code example

app.get('/health/live', (_req, res) => res.status(200).json({ status: 'ok' }));

Diagram

Orchestrator -> /health/ready -> traffic decision

Key Points

  • Understand the purpose of what is a health check endpoint?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q19Backend Architecture

What is horizontal versus vertical scaling?

Vertical scaling increases resources on one machine; horizontal scaling adds instances.

Answer

Vertical scaling increases resources on one machine; horizontal scaling adds instances. Stateless services are easier to scale horizontally, but shared state, session storage, and database capacity need deliberate design.

Syntax

load balancer -> N stateless instances

Example

Run multiple API instances behind a load balancer and store sessions in a shared store if sessions are required.

Code example

// Keep request state out of process memory where possible

Diagram

Clients -> Load Balancer -> API 1 / API 2 / API 3

Key Points

  • Understand the purpose of what is horizontal versus vertical scaling?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q20Backend Architecture

What is a reverse proxy?

A reverse proxy receives client requests and forwards them to backend servers.

Answer

A reverse proxy receives client requests and forwards them to backend servers. It can provide TLS termination, routing, compression, load balancing, and request limits.

Syntax

client -> proxy -> upstream API

Example

Nginx routes /api to the Node.js service while serving other paths elsewhere.

Code example

location /api/ { proxy_pass http://backend_api; }

Diagram

Client -> Reverse Proxy -> API instances

Key Points

  • Understand the purpose of what is a reverse proxy?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q22Node.js

What is Node.js?

Node.

Answer

Node.js is a JavaScript runtime built on the V8 engine. It provides APIs for networking, files, streams, and processes, making it useful for I/O-heavy services.

Syntax

node server.js

Example

A Node.js API can accept HTTP requests while asynchronous database operations wait without blocking the JavaScript thread.

Code example

import { createServer } from 'node:http'; createServer((_req, res) => res.end('ok')).listen(3000);

Diagram

HTTP request -> Event Loop -> async I/O -> response

Key Points

  • Understand the purpose of what is node.js?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q24Node.js

What is the difference between synchronous and asynchronous I/O?

Synchronous I/O blocks the current execution until it completes; asynchronous I/O allows the runtime to continue processing other work while the operation is pending.

Answer

Synchronous I/O blocks the current execution until it completes; asynchronous I/O allows the runtime to continue processing other work while the operation is pending.

Syntax

readFileSync() vs await readFile()

Example

Prefer asynchronous file reads in a server request path to avoid blocking unrelated requests.

Code example

import { readFile } from 'node:fs/promises'; const text = await readFile('data.txt', 'utf8');

Diagram

Request -> async I/O pending -> other work -> completion callback

Key Points

  • Understand the purpose of what is the difference between synchronous and asynchronous i/o?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q25Node.js

Explain callbacks, promises, and async/await.

Callbacks pass a function to be invoked later; promises represent eventual completion or failure; async/await provides syntax for writing promise-based code in a sequential style.

Answer

Callbacks pass a function to be invoked later; promises represent eventual completion or failure; async/await provides syntax for writing promise-based code in a sequential style. Errors must still be handled.

Syntax

async function load() { return await fetchData(); }

Example

Use try/catch around awaited operations and propagate meaningful errors to centralized handling.

Code example

try { const user = await userService.find(id); } catch (error) { throw error; }

Diagram

Call -> Promise pending -> fulfilled/rejected -> handler

Key Points

  • Understand the purpose of explain callbacks, promises, and async/await.
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q29Node.js

How do you handle errors in async Node.js code?

Use try/catch for awaited operations, handle promise rejections, and centralize translation of known errors into safe HTTP responses.

Answer

Use try/catch for awaited operations, handle promise rejections, and centralize translation of known errors into safe HTTP responses. Log diagnostic details internally without exposing secrets or stack traces to clients.

Syntax

try { await work(); } catch (err) { next(err); }

Example

A database conflict can become a 409 response while unexpected failures become a generic 500.

Code example

app.use((err, req, res, next) => { if (res.headersSent) return next(err); res.status(500).json({ message: 'Internal server error' }); });

Diagram

Async operation -> error boundary -> logger -> safe response

Key Points

  • Understand the purpose of how do you handle errors in async node.js code?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q33Node.js

How do CommonJS and ES modules differ?

CommonJS uses require/module.

Answer

CommonJS uses require/module.exports; ES modules use import/export and have standardized module semantics. Package configuration and file extensions determine how Node interprets modules.

Syntax

import { readFile } from 'node:fs/promises';

Example

Use a consistent module system across application code and build tooling.

Code example

export function normalizeId(id) { return id.trim(); }

Diagram

Module A --import/export--> Module B

Key Points

  • Understand the purpose of how do commonjs and es modules differ?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q34Node.js

What is package.json used for?

package.

Answer

package.json declares project metadata, scripts, dependencies, and module configuration. Lockfiles pin resolved dependency versions for reproducible installs.

Syntax

npm run build; npm ci

Example

Use npm ci in CI to install from the lockfile and detect mismatch with package.json.

Code example

{ "scripts": { "start": "node dist/main.js", "test": "jest" } }

Diagram

package.json + lockfile -> package manager -> node_modules

Key Points

  • Understand the purpose of what is package.json used for?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q35Node.js

How do you manage environment variables in Node.js?

Environment variables provide runtime configuration such as port numbers and service URLs.

Answer

Environment variables provide runtime configuration such as port numbers and service URLs. Validate them on startup, avoid logging secrets, and use a secret manager for sensitive values.

Syntax

const port = Number(process.env.PORT ?? 3000);

Example

Fail fast if DATABASE_URL is absent instead of discovering it on the first request.

Code example

const port = Number(process.env.PORT ?? 3000); if (!Number.isInteger(port)) throw new Error('Invalid PORT');

Diagram

Deployment config -> env vars -> validated configuration

Key Points

  • Understand the purpose of how do you manage environment variables in node.js?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q41Node.js

How do you test Node.js code?

Use unit tests for pure logic, integration tests for database or HTTP boundaries, and end-to-end tests for critical user workflows.

Answer

Use unit tests for pure logic, integration tests for database or HTTP boundaries, and end-to-end tests for critical user workflows. Keep tests deterministic and isolate external dependencies.

Syntax

node --test; npm test

Example

Test a service with a fake repository, then separately verify repository behavior against a disposable database.

Code example

import test from 'node:test'; import assert from 'node:assert/strict'; test('sum', () => assert.equal(2 + 2, 4));

Diagram

Unit -> Integration -> End-to-end

Key Points

  • Understand the purpose of how do you test node.js code?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q42NestJS

What is NestJS?

NestJS is a Node.

Answer

NestJS is a Node.js framework for building structured server applications, commonly using TypeScript. It provides modules, controllers, providers, dependency injection, pipes, guards, interceptors, and filters.

Syntax

nest g module users; nest g controller users

Example

A UsersModule groups user routes and services behind a clear module boundary.

Code example

@Module({ controllers: [UsersController], providers: [UsersService] }) export class UsersModule {}

Diagram

HTTP -> Nest Controller -> Provider -> Data layer

Key Points

  • Understand the purpose of what is nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q43NestJS

Explain modules in NestJS.

A module groups related controllers and providers.

Answer

A module groups related controllers and providers. Providers are private to a module by default; export a provider to make it available to importing modules.

Syntax

@Module({ providers: [UsersService], exports: [UsersService] })

Example

AuthModule can import UsersModule to use its exported UsersService.

Code example

@Module({ imports: [UsersModule], providers: [AuthService] }) export class AuthModule {}

Diagram

AppModule -> AuthModule -> UsersModule

Key Points

  • Understand the purpose of explain modules in nestjs.
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q44NestJS

What is a controller in NestJS?

A controller handles incoming requests, maps routes, extracts parameters, and delegates work to providers.

Answer

A controller handles incoming requests, maps routes, extracts parameters, and delegates work to providers. Keep business logic out of controllers so it can be tested and reused.

Syntax

@Get(':id') findOne(@Param('id') id: string)

Example

A UsersController calls UsersService.findById rather than writing SQL itself.

Code example

@Controller('users') export class UsersController { @Get(':id') findOne(@Param('id') id: string) { return this.users.findById(id); } constructor(private users: UsersService) {} }

Diagram

HTTP route -> Controller -> Service

Key Points

  • Understand the purpose of what is a controller in nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q45NestJS

What is a provider in NestJS?

A provider is a class or value managed by Nest's dependency injection container.

Answer

A provider is a class or value managed by Nest's dependency injection container. Services, repositories, factories, and adapters can all be providers.

Syntax

@Injectable() export class UsersService {}

Example

Inject a MailerService into RegistrationService instead of creating it with new.

Code example

@Injectable() export class RegistrationService { constructor(private readonly mailer: MailerService) {} }

Diagram

Nest container -> constructs provider graph -> controller/service

Key Points

  • Understand the purpose of what is a provider in nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q47NestJS

What are pipes in NestJS?

Pipes transform input or validate it before a route handler executes.

Answer

Pipes transform input or validate it before a route handler executes. Built-in pipes include ParseIntPipe and ValidationPipe; DTO validation typically uses class-validator and class-transformer.

Syntax

@Param('id', ParseIntPipe) id: number

Example

Reject an invalid numeric route ID before the controller's business logic runs.

Code example

@Get(':id') find(@Param('id', ParseIntPipe) id: number) { return this.service.find(id); }

Diagram

Request input -> Pipe validation/transformation -> handler

Key Points

  • Understand the purpose of what are pipes in nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q48NestJS

How do you configure ValidationPipe globally?

A global ValidationPipe applies DTO validation consistently.

Answer

A global ValidationPipe applies DTO validation consistently. Common options include whitelist to strip non-decorated fields, forbidNonWhitelisted to reject them, and transform to convert compatible primitive/DTO values.

Syntax

app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }))

Example

A request containing an unexpected isAdmin property can be rejected when forbidNonWhitelisted is enabled.

Code example

app.useGlobalPipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true }));

Diagram

JSON -> DTO transform -> validation -> controller

Key Points

  • Understand the purpose of how do you configure validationpipe globally?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q49NestJS

What are guards in NestJS?

Guards decide whether a request may proceed, typically for authentication or authorization.

Answer

Guards decide whether a request may proceed, typically for authentication or authorization. They return a boolean or asynchronous equivalent and can inspect execution context and metadata.

Syntax

@UseGuards(AuthGuard)

Example

Require an authenticated principal before allowing access to a protected endpoint.

Code example

@UseGuards(AuthGuard('jwt')) @Get('me') getProfile() { return this.users.me(); }

Diagram

Request -> Guard -> allowed? -> handler

Key Points

  • Understand the purpose of what are guards in nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q52NestJS

What is middleware in NestJS?

Middleware runs before route handlers and is useful for cross-cutting request tasks such as correlation IDs or simple request logging.

Answer

Middleware runs before route handlers and is useful for cross-cutting request tasks such as correlation IDs or simple request logging. Prefer guards, pipes, interceptors, or filters when their semantics fit better.

Syntax

consumer.apply(LoggerMiddleware).forRoutes('*')

Example

Attach a request ID before the request reaches a controller.

Code example

use(req, res, next) { req.requestId = crypto.randomUUID(); next(); }

Diagram

Request -> Middleware -> Guards/Pipes -> Handler

Key Points

  • Understand the purpose of what is middleware in nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q56NestJS

How do you write unit tests for NestJS providers?

Use Test.

Answer

Use Test.createTestingModule to construct a focused dependency-injection container and provide mocks for collaborators. Test behavior and error cases without booting the full application.

Syntax

Test.createTestingModule({ providers: [UsersService, { provide: UsersRepo, useValue: mockRepo }] })

Example

Mock the repository to verify UsersService returns a user or throws NotFoundException.

Code example

const moduleRef = await Test.createTestingModule({ providers: [UsersService, { provide: UsersRepo, useValue: repoMock }] }).compile();

Diagram

Test module -> service + mocks -> assertions

Key Points

  • Understand the purpose of how do you write unit tests for nestjs providers?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q67REST

What is REST?

REST is an architectural style for networked systems emphasizing resources, representations, a uniform interface, stateless interactions, and cacheability where appropriate.

Answer

REST is an architectural style for networked systems emphasizing resources, representations, a uniform interface, stateless interactions, and cacheability where appropriate. HTTP APIs commonly use resource URIs and standard methods.

Syntax

GET /api/users/42

Example

Represent a user as a resource and use GET to retrieve its representation.

Code example

app.get('/api/users/:id', getUser);

Diagram

Client -> HTTP resource URI -> representation

Key Points

  • Understand the purpose of what is rest?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q68REST

What is the difference between PUT and PATCH?

PUT generally replaces the target resource representation and is idempotent; PATCH applies partial modifications.

Answer

PUT generally replaces the target resource representation and is idempotent; PATCH applies partial modifications. Exact semantics should be documented, and PATCH operations need clear validation and concurrency rules.

Syntax

PUT /users/42; PATCH /users/42

Example

PUT may send all editable profile fields; PATCH may send only {"displayName":"Ava"}.

Code example

app.patch('/users/:id', validatePatch, patchUser);

Diagram

PATCH payload -> validate allowed fields -> apply changes

Key Points

  • Understand the purpose of what is the difference between put and patch?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q70REST

Which HTTP status codes should an API use?

Use status codes consistently: 200 for successful retrieval/action, 201 for creation, 204 for success without a body, 400 for malformed/invalid input, 401 for unauthenticated, 403 for forbidden, 404 for missing resources, 409 for conflicts, 422 for semantic validation where adopted, 429 for rate limits, and 5xx for server failures.

Answer

Use status codes consistently: 200 for successful retrieval/action, 201 for creation, 204 for success without a body, 400 for malformed/invalid input, 401 for unauthenticated, 403 for forbidden, 404 for missing resources, 409 for conflicts, 422 for semantic validation where adopted, 429 for rate limits, and 5xx for server failures.

Syntax

res.status(201).json(resource)

Example

Return 201 and a Location header after creating a resource.

Code example

res.status(201).location(`/users/${user.id}`).json(user);

Diagram

Request -> outcome -> appropriate status + response body

Key Points

  • Understand the purpose of which http status codes should an api use?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q71REST

How should an API design resource URLs?

Use stable nouns for resources, plural collections where conventional, and nested paths only when the relationship is meaningful.

Answer

Use stable nouns for resources, plural collections where conventional, and nested paths only when the relationship is meaningful. Avoid encoding actions in URLs when standard HTTP methods and resource semantics suffice.

Syntax

GET /orders/123/items

Example

Use POST /orders for creation rather than /createOrder.

Code example

GET /api/orders/:orderId/items

Diagram

/orders -> collection; /orders/{id} -> individual resource

Key Points

  • Understand the purpose of how should an api design resource urls?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q82REST

What is the difference between 401 and 403?

401 means valid authentication credentials are absent or unacceptable; 403 means the server understood the request but refuses authorization.

Answer

401 means valid authentication credentials are absent or unacceptable; 403 means the server understood the request but refuses authorization. Avoid leaking resource existence where that creates a security risk.

Syntax

401 Unauthorized; 403 Forbidden

Example

A missing token yields 401; a valid user lacking the admin permission yields 403.

Code example

if (!req.user) return res.sendStatus(401); if (!req.user.isAdmin) return res.sendStatus(403);

Diagram

No valid identity -> 401; identity without permission -> 403

Key Points

  • Understand the purpose of what is the difference between 401 and 403?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q86GraphQL

What is GraphQL?

GraphQL is a query language and runtime for APIs in which clients request fields from a typed schema.

Answer

GraphQL is a query language and runtime for APIs in which clients request fields from a typed schema. It can reduce over-fetching but requires careful authorization, query-cost control, and caching strategy.

Syntax

query { user(id: "42") { id name } }

Example

A mobile screen requests only the user name and recent order IDs it needs.

Code example

const user = await userService.findById(args.id);

Diagram

Client query -> GraphQL schema/resolvers -> services/data

Key Points

  • Understand the purpose of what is graphql?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q87GraphQL

What are GraphQL schemas and types?

A schema defines the API's types, fields, arguments, and operations.

Answer

A schema defines the API's types, fields, arguments, and operations. Object types model data; scalar and enum types define values; input types represent arguments; Query and Mutation are common root types.

Syntax

type User { id: ID!, name: String! }

Example

A User type exposes a non-null ID and name fields.

Code example

type Query { user(id: ID!): User }

Diagram

Schema -> validation -> execution

Key Points

  • Understand the purpose of what are graphql schemas and types?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q88GraphQL

What is the difference between Query and Mutation?

Queries read data and mutations perform state-changing operations.

Answer

Queries read data and mutations perform state-changing operations. Mutations should enforce authorization, validation, transaction boundaries, and idempotency where retries are possible.

Syntax

type Mutation { createUser(input: CreateUserInput!): User! }

Example

Use a query to fetch a product and a mutation to place an order.

Code example

const resolvers = { Query: { user: (_, { id }) => users.findById(id) } };

Diagram

Query -> read path; Mutation -> command/write path

Key Points

  • Understand the purpose of what is the difference between query and mutation?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q89GraphQL

What are GraphQL resolvers?

Resolvers provide values for schema fields.

Answer

Resolvers provide values for schema fields. They should delegate to services and data loaders rather than embedding complex business rules or running uncontrolled database calls per field.

Syntax

user: (_parent, args, ctx) => ctx.users.findById(args.id)

Example

A resolver checks the principal and calls a domain service to load a user's orders.

Code example

const resolvers = { Query: { user: (_p, { id }, ctx) => ctx.userService.findById(id) } };

Diagram

Field -> resolver -> service/data source -> value

Key Points

  • Understand the purpose of what are graphql resolvers?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q97GraphQL

What are GraphQL input types?

Input object types define structured mutation arguments.

Answer

Input object types define structured mutation arguments. They are distinct from output object types and should be validated before business logic executes.

Syntax

input CreateUserInput { email: String!, name: String! }

Example

Pass a single input object to createUser and reject unsupported or invalid values.

Code example

mutation Create($input: CreateUserInput!) { createUser(input: $input) { id } }

Diagram

Input object -> validation -> mutation resolver

Key Points

  • Understand the purpose of what are graphql input types?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q101Validation

Why validate input on the server?

Client-side validation improves usability but can be bypassed.

Answer

Client-side validation improves usability but can be bypassed. Server-side validation is mandatory at trust boundaries and should check shape, types, ranges, formats, and business invariants before data reaches core logic.

Syntax

if (!emailPattern.test(input.email)) throw ValidationError

Example

Reject a negative quantity even if the browser UI normally prevents it.

Code example

if (!Number.isInteger(input.quantity) || input.quantity < 1) throw new Error('Invalid quantity');

Diagram

Untrusted input -> schema validation -> domain validation -> use case

Key Points

  • Understand the purpose of why validate input on the server?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q107Validation

How do you validate query and path parameters?

Validate route parameters and query strings because they arrive as strings and may be missing, repeated, malformed, or outside allowed ranges.

Answer

Validate route parameters and query strings because they arrive as strings and may be missing, repeated, malformed, or outside allowed ranges. Normalize values only after validating them.

Syntax

limit = integer in [1, 100]

Example

Reject ?limit=999999 and a nonnumeric /users/abc identifier.

Code example

const limit = Number(req.query.limit ?? 20); if (!Number.isInteger(limit) || limit < 1 || limit > 100) return res.sendStatus(400);

Diagram

Raw strings -> parse -> range check -> typed values

Key Points

  • Understand the purpose of how do you validate query and path parameters?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q112Validation

How do you avoid SQL injection?

Use parameterized queries or a well-configured ORM, never concatenate untrusted values into SQL.

Answer

Use parameterized queries or a well-configured ORM, never concatenate untrusted values into SQL. Dynamic identifiers such as column names need explicit allowlists because they usually cannot be bound as ordinary parameters.

Syntax

SELECT * FROM users WHERE email = $1

Example

Bind the email as a query parameter rather than interpolating it into SQL text.

Code example

await db.query('SELECT id FROM users WHERE email = $1', [email]);

Diagram

Untrusted value -> parameter binding -> database parser

Key Points

  • Understand the purpose of how do you avoid sql injection?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q116API Security

What are the core principles of API security?

Use defense in depth: TLS, strong authentication, object/function-level authorization, input validation, least privilege, rate limits, safe errors, secure secrets, logging, and timely dependency updates.

Answer

Use defense in depth: TLS, strong authentication, object/function-level authorization, input validation, least privilege, rate limits, safe errors, secure secrets, logging, and timely dependency updates. Threat-model the API and test controls continuously.

Syntax

TLS + authn + authz + validation + monitoring

Example

A valid login does not automatically authorize a user to read every tenant's records.

Code example

// Enforce authentication and resource-level authorization on every protected operation

Diagram

Client -> TLS -> gateway -> authn -> authz -> validated handler

Key Points

  • Understand the purpose of what are the core principles of api security?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q117API Security

What is the difference between authentication and authorization?

Authentication establishes who the caller is; authorization decides what that identity may do to a particular resource or operation.

Answer

Authentication establishes who the caller is; authorization decides what that identity may do to a particular resource or operation. Both checks are required for protected actions.

Syntax

authenticate(token); authorize(user, action, resource)

Example

A logged-in user may view their own invoices but cannot delete another customer's invoice.

Code example

if (invoice.ownerId !== user.id && !user.roles.includes('admin')) throw new ForbiddenError();

Diagram

Credentials -> identity -> permission decision -> action

Key Points

  • Understand the purpose of what is the difference between authentication and authorization?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q129API Security

How do you handle secrets and sensitive data in logs?

Do not log passwords, access tokens, API keys, payment data, or unnecessary personal data.

Answer

Do not log passwords, access tokens, API keys, payment data, or unnecessary personal data. Redact sensitive fields, restrict log access, set retention policies, and use correlation IDs to investigate without exposing payloads.

Syntax

redact: ['authorization', 'password', 'token']

Example

Log request ID and status code instead of the complete Authorization header and request body.

Code example

logger.info({ requestId, route, statusCode }); // omit credentials and sensitive payloads

Diagram

Request -> redaction -> access-controlled logs -> retention

Key Points

  • Understand the purpose of how do you handle secrets and sensitive data in logs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q5Backend Architecture

What is clean architecture?

Clean architecture places business rules at the center and makes infrastructure details depend on inner abstractions.

Answer

Clean architecture places business rules at the center and makes infrastructure details depend on inner abstractions. Domain and application logic should not need to know about Express, a database driver, or a cloud provider.

Syntax

UseCase -> RepositoryPort <- SqlRepositoryAdapter

Example

A CreateInvoice use case depends on an InvoiceRepository interface, while a PostgreSQL adapter implements that interface.

Code example

interface InvoiceRepository { save(invoice: Invoice): Promise<void> }

Diagram

HTTP Adapter -> Use Case -> Domain
                 ^
        Repository Port <- DB Adapter

Key Points

  • Understand the purpose of what is clean architecture?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q6Backend Architecture

What is hexagonal architecture?

Hexagonal (ports-and-adapters) architecture defines ports for capabilities the application needs and adapters for technologies that provide them.

Answer

Hexagonal (ports-and-adapters) architecture defines ports for capabilities the application needs and adapters for technologies that provide them. It allows databases, queues, and HTTP frameworks to be replaced or tested behind stable interfaces.

Syntax

port = interface; adapter = implementation

Example

A PaymentGateway port can be implemented by a Stripe adapter and a fake adapter for tests.

Code example

interface PaymentGateway { charge(amount: number): Promise<string> }

Diagram

HTTP/CLI Adapter -> Application Core <- Payment Adapter
                                  <- Database Adapter

Key Points

  • Understand the purpose of what is hexagonal architecture?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q8Backend Architecture

Explain SOLID principles in backend services.

SOLID is a set of design principles: single responsibility, open/closed, Liskov substitution, interface segregation, and dependency inversion.

Answer

SOLID is a set of design principles: single responsibility, open/closed, Liskov substitution, interface segregation, and dependency inversion. They help keep services cohesive and reduce brittle coupling when applied pragmatically.

Syntax

Depend on abstractions; keep interfaces focused

Example

A controller should not calculate tax, send email, and run SQL; delegate distinct responsibilities to services.

Code example

interface Notifier { send(message: string): Promise<void> }

Diagram

Controller -> Use Case -> small focused interfaces

Key Points

  • Understand the purpose of explain solid principles in backend services.
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q9Backend Architecture

What is domain-driven design (DDD)?

DDD models software around the business domain.

Answer

DDD models software around the business domain. It uses a shared language, bounded contexts, entities, value objects, aggregates, and domain services to keep business rules explicit.

Syntax

Order aggregate: Order + OrderLine invariants

Example

An Order aggregate can enforce that an order cannot be shipped before payment is confirmed.

Code example

class Money { constructor(readonly cents: number, readonly currency: string) {} }

Diagram

Sales Context | Billing Context | Shipping Context
       communicate through explicit contracts

Key Points

  • Understand the purpose of what is domain-driven design (ddd)?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q10Backend Architecture

What is an aggregate root?

An aggregate root is the entry point for changing an aggregate and enforcing its invariants.

Answer

An aggregate root is the entry point for changing an aggregate and enforcing its invariants. External code should not mutate child entities directly if doing so could bypass business rules.

Syntax

order.addLine(productId, quantity)

Example

Use Order.addLine() to validate quantity and pricing instead of directly editing an internal lines array.

Code example

class Order { addLine(line: OrderLine) { /* enforce invariants */ } }

Diagram

Caller -> Order (root) -> OrderLine children

Key Points

  • Understand the purpose of what is an aggregate root?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q11Backend Architecture

What is CQRS?

Command Query Responsibility Segregation separates operations that change state from operations that read state.

Answer

Command Query Responsibility Segregation separates operations that change state from operations that read state. It can optimize complex read/write workloads, but adds synchronization and operational complexity.

Syntax

Command -> write model; Query -> read model

Example

Checkout commands update order state; a query model returns a denormalized order history for fast display.

Code example

type CreateOrderCommand = { customerId: string; items: string[] };

Diagram

Commands -> Write Model -> Events -> Read Model -> Queries

Key Points

  • Understand the purpose of what is cqrs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q12Backend Architecture

What is event-driven architecture?

In event-driven architecture, components publish events describing facts and other components react asynchronously.

Answer

In event-driven architecture, components publish events describing facts and other components react asynchronously. It reduces direct coupling but requires idempotency, retries, schema evolution, and observability.

Syntax

OrderPlaced -> inventory / email / analytics consumers

Example

After an order is placed, a consumer reserves inventory while another sends a confirmation email.

Code example

await eventBus.publish({ type: 'OrderPlaced', orderId });

Diagram

Order Service -> Event Broker -> Inventory Consumer
                           -> Email Consumer

Key Points

  • Understand the purpose of what is event-driven architecture?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q18Backend Architecture

What is graceful shutdown?

Graceful shutdown stops accepting new work, allows in-flight requests to finish within a deadline, closes connections, and releases resources.

Answer

Graceful shutdown stops accepting new work, allows in-flight requests to finish within a deadline, closes connections, and releases resources. It reduces failed requests during deployments.

Syntax

SIGTERM -> stop intake -> drain -> close

Example

On container termination, stop the HTTP server and close the database pool after active requests drain.

Code example

process.on('SIGTERM', async () => { await app.close(); });

Diagram

SIGTERM -> stop accepting -> drain requests -> close DB/queues

Key Points

  • Understand the purpose of what is graceful shutdown?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q21Backend Architecture

How do you design for resilience?

Resilience combines timeouts, bounded retries, circuit breakers, bulkheads, graceful degradation, and observability.

Answer

Resilience combines timeouts, bounded retries, circuit breakers, bulkheads, graceful degradation, and observability. Retries should be limited and used only when operations are safe to repeat.

Syntax

timeout + retry budget + circuit breaker

Example

If a recommendation service fails, return a default recommendation rather than failing checkout.

Code example

// Retry only transient failures and use an idempotency key for writes

Diagram

API -> Timeout/Breaker -> Dependency
        failure -> fallback

Key Points

  • Understand the purpose of how do you design for resilience?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q23Node.js

Explain the Node.js event loop.

The event loop coordinates JavaScript callbacks and asynchronous work.

Answer

The event loop coordinates JavaScript callbacks and asynchronous work. I/O callbacks, timers, and other phases are scheduled so a process can handle many concurrent I/O operations, but CPU-heavy JavaScript can block progress.

Syntax

setTimeout(callback, 0)

Example

A slow synchronous loop delays timers and every other request handled by that event-loop thread.

Code example

setTimeout(() => console.log('timer'), 0); console.log('sync');

Diagram

Call stack -> event loop phases -> callbacks

Key Points

  • Understand the purpose of explain the node.js event loop.
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q27Node.js

What are streams in Node.js?

Streams process data incrementally rather than loading the entire payload into memory.

Answer

Streams process data incrementally rather than loading the entire payload into memory. Readable, writable, duplex, and transform streams support efficient file, network, and compression pipelines.

Syntax

readable.pipe(transform).pipe(writable)

Example

Stream a large download to the response instead of reading the whole file into a Buffer.

Code example

import { createReadStream } from 'node:fs'; createReadStream('large.csv').pipe(res);

Diagram

Source -> Transform -> Destination

Key Points

  • Understand the purpose of what are streams in node.js?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q31Node.js

When should you use worker threads?

Worker threads run JavaScript in separate threads and are useful for CPU-intensive tasks that would block the event loop.

Answer

Worker threads run JavaScript in separate threads and are useful for CPU-intensive tasks that would block the event loop. They have startup and communication costs, so use a pool for repeated jobs.

Syntax

new Worker('./worker.js')

Example

Move expensive report generation or image transformations to a bounded worker pool.

Code example

import { Worker } from 'node:worker_threads'; const worker = new Worker(new URL('./worker.js', import.meta.url));

Diagram

Main event loop <-> Worker thread (CPU work)

Key Points

  • Understand the purpose of when should you use worker threads?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q32Node.js

What is clustering in Node.js?

Clustering can run multiple Node.

Answer

Clustering can run multiple Node.js processes that share a server port, using multiple CPU cores. Process managers or containers can also scale instances; state should not rely on a single process's memory.

Syntax

multiple processes behind a load balancer

Example

Run several stateless API instances and share cache/session state through Redis when needed.

Code example

// Prefer process manager/container replicas for deployment-level scaling

Diagram

Load Balancer -> Process 1 / Process 2 / Process 3

Key Points

  • Understand the purpose of what is clustering in node.js?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q36Node.js

How should Node.js APIs handle process signals?

Handle SIGTERM/SIGINT to stop accepting new requests, drain in-flight work, close database and queue connections, and exit before the platform's termination deadline.

Answer

Handle SIGTERM/SIGINT to stop accepting new requests, drain in-flight work, close database and queue connections, and exit before the platform's termination deadline.

Syntax

process.on('SIGTERM', shutdown)

Example

Kubernetes sends SIGTERM before terminating a container; shutdown logic should be idempotent.

Code example

let shuttingDown = false; async function shutdown() { if (shuttingDown) return; shuttingDown = true; await server.close(); }

Diagram

Signal -> stop intake -> drain -> release resources

Key Points

  • Understand the purpose of how should node.js apis handle process signals?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q37Node.js

What is a memory leak in Node.js?

A memory leak occurs when objects remain reachable after they are no longer needed, preventing garbage collection.

Answer

A memory leak occurs when objects remain reachable after they are no longer needed, preventing garbage collection. Common causes include unbounded caches, retained closures, listeners, and global collections.

Syntax

heap snapshot -> compare retained objects

Example

Bound a cache with TTL/size limits and remove event listeners when a component is disposed.

Code example

const cache = new Map(); // add an explicit eviction policy

Diagram

Heap growth -> retained references -> GC cannot reclaim

Key Points

  • Understand the purpose of what is a memory leak in node.js?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q38Node.js

How do you profile a slow Node.js service?

Measure latency and resource use first, then use CPU profiles, heap snapshots, event-loop delay metrics, traces, and database query timings to isolate the bottleneck.

Answer

Measure latency and resource use first, then use CPU profiles, heap snapshots, event-loop delay metrics, traces, and database query timings to isolate the bottleneck. Optimize based on evidence.

Syntax

node --cpu-prof dist/main.js

Example

If p95 latency rises while CPU stays low, inspect downstream waits and connection-pool saturation.

Code example

import { monitorEventLoopDelay } from 'node:perf_hooks'; const h = monitorEventLoopDelay(); h.enable();

Diagram

Metrics -> identify bottleneck -> profile -> validate fix

Key Points

  • Understand the purpose of how do you profile a slow node.js service?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q39Node.js

What is the difference between concurrency and parallelism?

Concurrency means multiple tasks make progress over overlapping periods; parallelism means tasks execute simultaneously.

Answer

Concurrency means multiple tasks make progress over overlapping periods; parallelism means tasks execute simultaneously. Node.js can handle concurrent I/O on the event loop and parallel CPU work using workers or processes.

Syntax

Promise.all([fetchA(), fetchB()])

Example

Two network requests can overlap concurrently; CPU-heavy calculations need worker threads for parallel execution.

Code example

const [a, b] = await Promise.all([fetchA(), fetchB()]);

Diagram

Concurrent I/O overlaps waits; workers execute CPU tasks in parallel

Key Points

  • Understand the purpose of what is the difference between concurrency and parallelism?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q40Node.js

How do you prevent blocking the event loop?

Avoid long synchronous loops and synchronous filesystem or crypto calls in request handlers.

Answer

Avoid long synchronous loops and synchronous filesystem or crypto calls in request handlers. Chunk CPU work, use worker threads, and set payload and computational limits.

Syntax

setImmediate(processNextChunk)

Example

Process a large import in batches and yield between batches, or move it to a worker/job queue.

Code example

for (const batch of batches) { await processBatch(batch); await new Promise(setImmediate); }

Diagram

Request -> bounded work chunks -> event loop remains responsive

Key Points

  • Understand the purpose of how do you prevent blocking the event loop?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q46NestJS

What are NestJS lifecycle hooks?

Lifecycle hooks let providers or modules react to application initialization, bootstrap, shutdown, and module destruction.

Answer

Lifecycle hooks let providers or modules react to application initialization, bootstrap, shutdown, and module destruction. Use them to initialize or release resources, and enable shutdown hooks when handling OS signals.

Syntax

onModuleInit(); onApplicationShutdown(signal)

Example

A queue consumer starts during initialization and stops during shutdown.

Code example

@Injectable() class WorkerService implements OnModuleInit { onModuleInit() { /* connect consumer */ } }

Diagram

Bootstrap -> init hooks -> serving -> shutdown hooks

Key Points

  • Understand the purpose of what are nestjs lifecycle hooks?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q50NestJS

What are interceptors in NestJS?

Interceptors wrap handler execution and can add logging, timing, response mapping, caching, or timeout behavior.

Answer

Interceptors wrap handler execution and can add logging, timing, response mapping, caching, or timeout behavior. They work with the RxJS Observable pipeline.

Syntax

intercept(context, next) { return next.handle(); }

Example

Measure request duration before and after the route handler completes.

Code example

@Injectable() class TimingInterceptor implements NestInterceptor { intercept(ctx, next) { const start = Date.now(); return next.handle().pipe(tap(() => console.log(Date.now() - start))); } }

Diagram

Request -> Interceptor before -> Handler -> Interceptor after

Key Points

  • Understand the purpose of what are interceptors in nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q51NestJS

What are exception filters in NestJS?

Exception filters catch exceptions and format the HTTP response.

Answer

Exception filters catch exceptions and format the HTTP response. Use them to standardize error payloads and avoid exposing internal stack traces or implementation details.

Syntax

@Catch(HttpException)

Example

Return a consistent error shape with statusCode, message, and requestId.

Code example

@Catch() class AllExceptionsFilter implements ExceptionFilter { catch(exception, host) { const res = host.switchToHttp().getResponse(); res.status(500).json({ message: 'Internal server error' }); } }

Diagram

Thrown error -> Exception Filter -> standardized response

Key Points

  • Understand the purpose of what are exception filters in nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q53NestJS

How do you implement authentication in NestJS?

Authentication verifies the caller's identity, often through Passport strategies, sessions, or bearer tokens.

Answer

Authentication verifies the caller's identity, often through Passport strategies, sessions, or bearer tokens. After authentication, attach a trusted principal to the request and keep authorization as a separate decision.

Syntax

@UseGuards(AuthGuard('jwt'))

Example

A JWT strategy validates signature, issuer, audience, and expiry before populating req.user.

Code example

@UseGuards(AuthGuard('jwt')) @Get('profile') profile(@Req() req) { return req.user; }

Diagram

Credential -> Strategy validation -> Principal -> Route

Key Points

  • Understand the purpose of how do you implement authentication in nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q54NestJS

How do you implement role-based authorization in NestJS?

Role-based authorization checks a trusted user's roles against metadata required by an endpoint.

Answer

Role-based authorization checks a trusted user's roles against metadata required by an endpoint. Never trust role values supplied by the request body or query string.

Syntax

@Roles('admin') + RolesGuard

Example

Only a principal with the admin role can delete user accounts.

Code example

export const Roles = (...roles: string[]) => SetMetadata('roles', roles);

Diagram

JWT principal -> RolesGuard -> required role? -> endpoint

Key Points

  • Understand the purpose of how do you implement role-based authorization in nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q55NestJS

How do custom decorators help in NestJS?

Custom decorators encapsulate repeated metadata or request extraction.

Answer

Custom decorators encapsulate repeated metadata or request extraction. They can improve readability, but authorization must still be enforced by guards or service-level rules.

Syntax

@CurrentUser() user: AuthUser

Example

Use a CurrentUser decorator to retrieve the principal established by authentication middleware/guard.

Code example

export const CurrentUser = createParamDecorator((_data, ctx) => ctx.switchToHttp().getRequest().user);

Diagram

Authenticated request -> decorator extracts principal -> handler

Key Points

  • Understand the purpose of how do custom decorators help in nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q57NestJS

How do you configure environment variables in NestJS?

ConfigModule loads environment-based configuration and can validate required values at startup.

Answer

ConfigModule loads environment-based configuration and can validate required values at startup. Avoid reading process.env throughout business logic; inject typed configuration instead.

Syntax

ConfigModule.forRoot({ isGlobal: true })

Example

Inject ConfigService to read a validated API base URL or database setting.

Code example

constructor(private config: ConfigService) { const url = this.config.getOrThrow<string>('DATABASE_URL'); }

Diagram

Environment -> ConfigModule -> validated ConfigService -> providers

Key Points

  • Understand the purpose of how do you configure environment variables in nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q58NestJS

How do you connect NestJS to a database?

Use a database integration such as TypeORM, Prisma, or a query builder, and isolate persistence behind repositories or data-access services.

Answer

Use a database integration such as TypeORM, Prisma, or a query builder, and isolate persistence behind repositories or data-access services. Manage migrations, connection pooling, transactions, and shutdown deliberately.

Syntax

TypeOrmModule.forRoot({...})

Example

Register a User entity and inject its repository in a UsersService.

Code example

TypeOrmModule.forFeature([User])

Diagram

Service -> Repository/ORM -> Connection Pool -> Database

Key Points

  • Understand the purpose of how do you connect nestjs to a database?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q60NestJS

How do you schedule jobs in NestJS?

NestJS scheduling can run cron-like tasks within an application process.

Answer

NestJS scheduling can run cron-like tasks within an application process. For critical or distributed jobs, use a durable queue or scheduler with locking, retries, and idempotent handlers rather than relying on every replica running the same task.

Syntax

@Cron('0 * * * *')

Example

Run a periodic cleanup task, ensuring multiple replicas cannot execute destructive work concurrently without coordination.

Code example

@Cron('0 2 * * *') async cleanup() { await this.service.removeExpired(); }

Diagram

Scheduler -> job handler -> service -> datastore

Key Points

  • Understand the purpose of how do you schedule jobs in nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q63NestJS

How do you document NestJS APIs with OpenAPI?

The Nest Swagger integration generates an OpenAPI document from route and DTO metadata.

Answer

The Nest Swagger integration generates an OpenAPI document from route and DTO metadata. Add operation summaries, response schemas, auth requirements, and examples, then publish or export the specification.

Syntax

SwaggerModule.createDocument(app, config)

Example

Expose a versioned OpenAPI document for frontend developers and contract testing.

Code example

const document = SwaggerModule.createDocument(app, new DocumentBuilder().setTitle('API').setVersion('1.0').build());

Diagram

Controllers/DTO metadata -> OpenAPI schema -> Swagger UI

Key Points

  • Understand the purpose of how do you document nestjs apis with openapi?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q64NestJS

How do you implement file uploads securely in NestJS?

Use upload interceptors with file-size and count limits, validate content type and actual file signature, generate safe storage names, and store files outside executable paths.

Answer

Use upload interceptors with file-size and count limits, validate content type and actual file signature, generate safe storage names, and store files outside executable paths. Scan risky content where appropriate.

Syntax

@UseInterceptors(FileInterceptor('file', { limits: { fileSize: 5_000_000 } }))

Example

Do not trust the uploaded filename or extension; generate a UUID and validate the file's actual content.

Code example

@UseInterceptors(FileInterceptor('file', { limits: { fileSize: 5_000_000 } }))

Diagram

Client -> size/type checks -> malware scan -> object storage

Key Points

  • Understand the purpose of how do you implement file uploads securely in nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q65NestJS

How do you handle rate limiting in NestJS?

Use a throttling module or gateway to limit requests per identity or IP.

Answer

Use a throttling module or gateway to limit requests per identity or IP. For multiple instances, use a shared store and account for proxy headers carefully; return 429 with retry guidance.

Syntax

@Throttle({ default: { limit: 20, ttl: 60000 } })

Example

Limit password-reset requests to reduce abuse without locking legitimate users out unnecessarily.

Code example

@UseGuards(ThrottlerGuard) @Post('login') login() {}

Diagram

Request -> rate limiter -> allow or HTTP 429

Key Points

  • Understand the purpose of how do you handle rate limiting in nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q66NestJS

How do you version a NestJS API?

Versioning allows incompatible contract changes without unexpectedly breaking clients.

Answer

Versioning allows incompatible contract changes without unexpectedly breaking clients. NestJS supports URI, header, media-type, and custom versioning strategies; document support and deprecation timelines.

Syntax

app.enableVersioning({ type: VersioningType.URI })

Example

Keep /v1/users stable while introducing a compatible or intentionally breaking /v2 contract.

Code example

@Version('2') @Get('users') listV2() { return this.service.listV2(); }

Diagram

Client -> /v1 or /v2 -> version-specific controller

Key Points

  • Understand the purpose of how do you version a nestjs api?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q69REST

Explain safe and idempotent HTTP methods.

A safe method is intended not to change server state, while an idempotent method has the same intended effect when repeated.

Answer

A safe method is intended not to change server state, while an idempotent method has the same intended effect when repeated. GET is safe and idempotent; PUT and DELETE are idempotent by semantics; POST is not inherently idempotent.

Syntax

GET safe; PUT idempotent; POST not inherently idempotent

Example

Retrying a timed-out PUT to set a profile field should converge on the same state.

Code example

// Use an idempotency key for retryable create/payment POST operations

Diagram

Client retry -> same intended final state for idempotent operation

Key Points

  • Understand the purpose of explain safe and idempotent http methods.
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q72REST

How do you implement pagination?

Offset pagination is simple but can become slow or inconsistent for large changing datasets.

Answer

Offset pagination is simple but can become slow or inconsistent for large changing datasets. Cursor pagination uses a stable ordered key and works well for feeds and large collections; return next-cursor metadata.

Syntax

GET /users?limit=20&cursor=eyJpZCI6...

Example

Return items and nextCursor so clients can request the next page.

Code example

res.json({ items, nextCursor: last?.id ?? null });

Diagram

Client -> page/cursor -> ordered query -> items + nextCursor

Key Points

  • Understand the purpose of how do you implement pagination?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q73REST

How do you implement filtering and sorting safely?

Define an explicit allowlist of filter and sort fields, validate values, and parameterize database inputs.

Answer

Define an explicit allowlist of filter and sort fields, validate values, and parameterize database inputs. Never concatenate raw user-provided column names into SQL.

Syntax

GET /products?category=books&sort=price

Example

Map sort=price to a known SQL column and reject unknown sort values.

Code example

const sortColumn = allowedSorts[req.query.sort] ?? 'created_at';

Diagram

Query parameters -> allowlist/validation -> safe query

Key Points

  • Understand the purpose of how do you implement filtering and sorting safely?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q74REST

How should REST APIs handle errors?

Return a stable error schema with a machine-readable code, safe message, optional field details, and correlation ID.

Answer

Return a stable error schema with a machine-readable code, safe message, optional field details, and correlation ID. Do not expose stack traces, secrets, SQL, or internal topology.

Syntax

{ statusCode, code, message, requestId }

Example

A validation failure can return field errors for email and password in a predictable structure.

Code example

res.status(400).json({ code: 'VALIDATION_FAILED', message: 'Invalid input', requestId });

Diagram

Exception -> error mapper -> consistent JSON response

Key Points

  • Understand the purpose of how should rest apis handle errors?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q75REST

What is content negotiation?

Content negotiation lets clients express acceptable representations through headers such as Accept.

Answer

Content negotiation lets clients express acceptable representations through headers such as Accept. Servers respond with a compatible media type or 406 when no supported representation is available.

Syntax

Accept: application/json

Example

An API can return JSON by default and reject unsupported media types consistently.

Code example

res.type('application/json').send(JSON.stringify(data));

Diagram

Accept header -> representation selection -> Content-Type

Key Points

  • Understand the purpose of what is content negotiation?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q79REST

How do you deprecate a REST endpoint?

Announce deprecation, measure client usage, provide a migration path, document the replacement, and set a communicated sunset date.

Answer

Announce deprecation, measure client usage, provide a migration path, document the replacement, and set a communicated sunset date. Where appropriate, use deprecation and sunset response headers.

Syntax

Deprecation: true; Sunset: <date>

Example

Keep the old endpoint during a transition while clients migrate to a new version.

Code example

res.setHeader('Deprecation', 'true');

Diagram

Usage metrics -> notice -> migration window -> retirement

Key Points

  • Understand the purpose of how do you deprecate a rest endpoint?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q80REST

What is API contract testing?

Contract testing verifies that provider behavior matches an agreed API contract and consumer expectations.

Answer

Contract testing verifies that provider behavior matches an agreed API contract and consumer expectations. It can detect incompatible schema, status, or payload changes before deployment.

Syntax

OpenAPI schema validation in CI

Example

Fail CI if a response removes a required field used by a consumer.

Code example

// Validate example responses against the committed OpenAPI schema

Diagram

Consumer contract + provider implementation -> compatibility check

Key Points

  • Understand the purpose of what is api contract testing?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q81REST

How do you design bulk endpoints?

Bulk endpoints reduce round trips but need limits, per-item validation, and clear partial-failure semantics.

Answer

Bulk endpoints reduce round trips but need limits, per-item validation, and clear partial-failure semantics. Document whether the operation is atomic or returns a result for each item.

Syntax

POST /users/bulk

Example

Return one outcome per submitted record when partial success is allowed.

Code example

res.status(207).json({ results: [{ id: '1', status: 'created' }, { id: '2', status: 'rejected' }] });

Diagram

Bulk request -> bounded batch -> per-item outcomes

Key Points

  • Understand the purpose of how do you design bulk endpoints?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q83REST

How do you handle long-running API operations?

For work that exceeds normal request latency, create a job resource and return 202 Accepted with a status URL.

Answer

For work that exceeds normal request latency, create a job resource and return 202 Accepted with a status URL. Expose progress, completion, and failure states; use a durable queue and idempotent workers.

Syntax

POST /exports -> 202 + Location: /jobs/abc

Example

Client submits a large export and polls GET /jobs/abc until complete.

Code example

res.status(202).location(`/jobs/${job.id}`).json({ jobId: job.id, status: 'queued' });

Diagram

POST -> job ID -> queue -> worker -> GET job status

Key Points

  • Understand the purpose of how do you handle long-running api operations?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q84REST

What are API quotas and rate limits?

Rate limits bound request volume over a time window; quotas can limit longer-term consumption.

Answer

Rate limits bound request volume over a time window; quotas can limit longer-term consumption. Apply limits by identity, tenant, endpoint cost, and abuse risk, and expose clear 429 responses.

Syntax

RateLimit-Limit / RateLimit-Remaining

Example

Use a stricter limit for password-reset or expensive search endpoints than for cached reads.

Code example

res.setHeader('Retry-After', '30'); res.status(429).json({ code: 'RATE_LIMITED' });

Diagram

Request -> quota/rate policy -> allow or 429

Key Points

  • Understand the purpose of what are api quotas and rate limits?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q85REST

How should APIs handle dates and time zones?

Use ISO 8601 timestamps with explicit UTC offsets or Z for instants, and distinguish instants from date-only values.

Answer

Use ISO 8601 timestamps with explicit UTC offsets or Z for instants, and distinguish instants from date-only values. Store instants consistently and convert for presentation at the boundary.

Syntax

2026-10-28T09:30:00Z

Example

Send a booking timestamp with a timezone instead of an ambiguous local string.

Code example

const instant = new Date(req.body.startsAt); if (Number.isNaN(instant.valueOf())) throw new Error('Invalid date');

Diagram

Client timestamp + offset -> validated instant -> storage

Key Points

  • Understand the purpose of how should apis handle dates and time zones?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q90GraphQL

What is the N+1 problem in GraphQL?

The N+1 problem occurs when resolving a list triggers one additional data query per item.

Answer

The N+1 problem occurs when resolving a list triggers one additional data query per item. DataLoader batches and caches loads within a request to reduce round trips.

Syntax

const loader = new DataLoader(ids => users.findByIds(ids))

Example

Fetch 50 posts and batch their author IDs in one database query rather than 50 separate queries.

Code example

const authorLoader = new DataLoader(async (ids) => userRepo.findByIds(ids));

Diagram

List resolver -> N field resolvers -> DataLoader batch -> one query

Key Points

  • Understand the purpose of what is the n+1 problem in graphql?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q91GraphQL

How do you secure GraphQL resolvers?

Enforce authentication and object/field-level authorization in resolver context or the underlying service.

Answer

Enforce authentication and object/field-level authorization in resolver context or the underlying service. Hiding a field in the schema is not a substitute for checking permissions on sensitive data.

Syntax

if (!ctx.user) throw new AuthenticationError()

Example

A user may read their own profile but not another user's private fields unless permitted.

Code example

if (ctx.user.id !== user.id && !ctx.user.roles.includes('admin')) throw new ForbiddenError();

Diagram

Request identity -> resolver/service authorization -> data

Key Points

  • Understand the purpose of how do you secure graphql resolvers?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q93GraphQL

What is GraphQL introspection?

Introspection lets clients discover schema types and fields.

Answer

Introspection lets clients discover schema types and fields. It is useful for tooling but production policy should be deliberate; disabling introspection alone does not secure an API.

Syntax

{ __schema { types { name } } }

Example

Generate typed clients from a controlled schema artifact in CI.

Code example

// Export schema in CI and review schema changes as part of code review

Diagram

Schema -> introspection/tooling -> generated client types

Key Points

  • Understand the purpose of what is graphql introspection?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q94GraphQL

How does GraphQL error handling work?

GraphQL responses can include both data and errors, depending on execution and nullability.

Answer

GraphQL responses can include both data and errors, depending on execution and nullability. Map internal exceptions to safe client messages and use stable error codes/extensions for machine handling.

Syntax

{ data: null, errors: [{ message: "Not authorized" }] }

Example

Return a safe FORBIDDEN code without including SQL details or secrets.

Code example

throw new GraphQLError('Not authorized', { extensions: { code: 'FORBIDDEN' } });

Diagram

Resolver failure -> GraphQL error path/extensions -> response

Key Points

  • Understand the purpose of how does graphql error handling work?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q96GraphQL

How do you version a GraphQL API?

GraphQL often evolves additively: add fields, deprecate old fields with reasons, measure usage, and remove them only after clients migrate.

Answer

GraphQL often evolves additively: add fields, deprecate old fields with reasons, measure usage, and remove them only after clients migrate. Avoid breaking changes to existing fields without a migration plan.

Syntax

oldField: String @deprecated(reason: "Use newField")

Example

Add fullName while deprecating displayName and track remaining displayName usage.

Code example

type User { fullName: String! displayName: String @deprecated(reason: "Use fullName") }

Diagram

Add replacement -> deprecate -> usage monitoring -> remove

Key Points

  • Understand the purpose of how do you version a graphql api?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q99GraphQL

How do you test a GraphQL API?

Test schema validation, resolver behavior, authorization, error shape, and integration with data sources.

Answer

Test schema validation, resolver behavior, authorization, error shape, and integration with data sources. Include representative operations and regression tests for query complexity and nullability behavior.

Syntax

executeOperation({ query, variables })

Example

Verify a user cannot request another tenant's private record through a nested resolver.

Code example

await server.executeOperation({ query: '{ health }' });

Diagram

GraphQL operation -> execution -> assert data/errors

Key Points

  • Understand the purpose of how do you test a graphql api?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q100GraphQL

When should you choose REST versus GraphQL?

REST is often simpler for resource-oriented APIs, HTTP caching, and operational familiarity.

Answer

REST is often simpler for resource-oriented APIs, HTTP caching, and operational familiarity. GraphQL helps clients with varying data needs and nested relationships but adds schema, resolver, query-cost, and caching complexity. Choose based on consumers and requirements.

Syntax

REST: GET /users/42; GraphQL: user(id: "42") { name }

Example

A public CRUD service may use REST; a multi-screen product with diverse data needs may benefit from GraphQL.

Code example

// Choose based on client needs, caching, tooling, and operational cost

Diagram

Consumers + data shape + caching/security needs -> API style

Key Points

  • Understand the purpose of when should you choose rest versus graphql?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q102Validation

What is the difference between syntactic and semantic validation?

Syntactic validation checks structure and format; semantic validation checks meaning and business rules.

Answer

Syntactic validation checks structure and format; semantic validation checks meaning and business rules. Both are needed, and semantic checks may require database or domain context.

Syntax

email format vs account is active

Example

A date may be valid ISO syntax but invalid for a booking because it is in the past.

Code example

if (new Date(input.startAt) <= new Date()) throw new Error('Start must be future');

Diagram

Shape/format checks -> domain/business checks

Key Points

  • Understand the purpose of what is the difference between syntactic and semantic validation?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q103Validation

How does class-validator work with NestJS DTOs?

class-validator decorators define constraints on DTO properties, and ValidationPipe runs those constraints before controller execution.

Answer

class-validator decorators define constraints on DTO properties, and ValidationPipe runs those constraints before controller execution. Ensure DTO transformation and nested validation are configured as intended.

Syntax

@IsEmail() email: string; @MinLength(12) password: string;

Example

Reject a malformed email and a password below the minimum length.

Code example

export class RegisterDto { @IsEmail() email: string; @MinLength(12) password: string; }

Diagram

Payload -> DTO decorators -> ValidationPipe -> handler

Key Points

  • Understand the purpose of how does class-validator work with nestjs dtos?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q104Validation

What is schema validation with Zod?

Zod defines runtime schemas and infers TypeScript types from them.

Answer

Zod defines runtime schemas and infers TypeScript types from them. It is useful for validating external data, environment variables, and API inputs at runtime rather than relying only on compile-time types.

Syntax

const schema = z.object({ email: z.string().email() })

Example

Parse a request body with safeParse and return field issues on failure.

Code example

const result = schema.safeParse(req.body); if (!result.success) return res.status(400).json(result.error.flatten());

Diagram

Unknown value -> Zod schema -> typed parsed data or issues

Key Points

  • Understand the purpose of what is schema validation with zod?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q105Validation

How should you validate nested objects and arrays?

Validate every nested object and array element with explicit schemas, maximum lengths, and depth limits where applicable.

Answer

Validate every nested object and array element with explicit schemas, maximum lengths, and depth limits where applicable. Do not assume validating the outer object automatically validates all children.

Syntax

items: z.array(itemSchema).max(100)

Example

Reject a cart with 10,000 line items before expensive processing.

Code example

const cartSchema = z.object({ items: z.array(z.object({ sku: z.string(), qty: z.number().int().positive() })).max(100) });

Diagram

Payload -> outer schema -> each nested item -> accepted DTO

Key Points

  • Understand the purpose of how should you validate nested objects and arrays?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q108Validation

What is allowlist validation?

Allowlist validation accepts only explicitly permitted values or fields, making unexpected input fail closed.

Answer

Allowlist validation accepts only explicitly permitted values or fields, making unexpected input fail closed. It is especially important for sort fields, enum-like options, update DTOs, and file types.

Syntax

const allowed = new Set(['name', 'createdAt'])

Example

Reject a sort parameter such as 'passwordHash' because it is not in the allowlist.

Code example

if (!allowedSortFields.has(sort)) throw new BadRequestException('Unsupported sort');

Diagram

Input -> allowlist -> accepted value or rejection

Key Points

  • Understand the purpose of what is allowlist validation?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q109Validation

How do you validate file uploads?

Validate file size, count, detected content type, file signature, and any business restrictions.

Answer

Validate file size, count, detected content type, file signature, and any business restrictions. Use generated filenames, safe storage, malware scanning where needed, and never trust the client-provided MIME type alone.

Syntax

max file size = 5 MB

Example

An uploaded .jpg extension is not proof the bytes contain a safe image.

Code example

if (file.size > MAX_SIZE) throw new BadRequestException('File too large');

Diagram

Upload -> size/signature checks -> scan -> isolated storage

Key Points

  • Understand the purpose of how do you validate file uploads?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q110Validation

How should validation errors be structured?

Return a consistent schema with a stable error code and field-level details while avoiding echoing sensitive input.

Answer

Return a consistent schema with a stable error code and field-level details while avoiding echoing sensitive input. Keep messages actionable but do not expose internal implementation details.

Syntax

{ code: 'VALIDATION_FAILED', fields: [{ path: 'email', code: 'INVALID_FORMAT' }] }

Example

A frontend can associate the email error with the correct form control.

Code example

res.status(400).json({ code: 'VALIDATION_FAILED', fields: [{ path: 'email', code: 'INVALID_FORMAT' }] });

Diagram

Validator issues -> error mapper -> stable response contract

Key Points

  • Understand the purpose of how should validation errors be structured?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q111Validation

What is normalization and when should it happen?

Normalization converts equivalent representations into a canonical form, such as trimming surrounding whitespace or normalizing case for case-insensitive identifiers.

Answer

Normalization converts equivalent representations into a canonical form, such as trimming surrounding whitespace or normalizing case for case-insensitive identifiers. Preserve original values where case or formatting is meaningful.

Syntax

email.trim().toLowerCase()

Example

Normalize email before uniqueness checks if the application's identity policy treats email case-insensitively.

Code example

const normalizedEmail = input.email.trim().toLowerCase();

Diagram

Raw input -> normalize -> validate canonical form -> persist

Key Points

  • Understand the purpose of what is normalization and when should it happen?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q115Validation

How do you validate environment configuration at startup?

Validate required environment variables, types, ranges, URLs, and cross-setting rules at startup.

Answer

Validate required environment variables, types, ranges, URLs, and cross-setting rules at startup. Fail fast with safe diagnostics rather than allowing a misconfigured service to fail unpredictably at runtime.

Syntax

PORT: integer; DATABASE_URL: valid URL

Example

Reject an invalid port or missing database URL before opening the HTTP listener.

Code example

const port = Number(process.env.PORT ?? 3000); if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid PORT');

Diagram

Environment -> schema validation -> app starts or exits

Key Points

  • Understand the purpose of how do you validate environment configuration at startup?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q118API Security

How does JWT authentication work?

A JWT is a signed token containing claims.

Answer

A JWT is a signed token containing claims. The API must verify the signature and expected algorithm, issuer, audience, expiry, and other relevant claims; a decoded token is not trusted until validated. Avoid sensitive secrets in readable payloads.

Syntax

Authorization: Bearer <token>

Example

A guard verifies the token and then uses its subject claim as the authenticated user ID.

Code example

const claims = jwt.verify(token, publicKey, { algorithms: ['RS256'], issuer, audience });

Diagram

Login -> signed token -> API verifies claims -> principal

Key Points

  • Understand the purpose of how does jwt authentication work?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q119API Security

What are OAuth 2.0 and OpenID Connect?

OAuth 2.

Answer

OAuth 2.0 is an authorization framework for delegated access; OpenID Connect adds an identity layer on top of OAuth 2.0. Use Authorization Code with PKCE for public clients and validate tokens according to their purpose.

Syntax

authorization_code + PKCE

Example

A web/mobile client redirects to an identity provider and exchanges an authorization code with PKCE.

Code example

// Use a maintained OIDC client library; validate issuer, audience, state, nonce, and PKCE

Diagram

Client -> Authorization Server -> code/token -> API/resource

Key Points

  • Understand the purpose of what are oauth 2.0 and openid connect?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q122API Security

How do you prevent CORS misconfiguration?

CORS controls which browser origins may read cross-origin responses; it is not authentication and does not stop non-browser clients.

Answer

CORS controls which browser origins may read cross-origin responses; it is not authentication and does not stop non-browser clients. Use an explicit origin allowlist, careful credential settings, and correct preflight handling.

Syntax

Access-Control-Allow-Origin: https://app.example.com

Example

Do not reflect arbitrary Origin headers when credentials are enabled.

Code example

const allowed = new Set(['https://app.example.com']); if (allowed.has(req.headers.origin)) res.setHeader('Access-Control-Allow-Origin', req.headers.origin);

Diagram

Browser origin -> CORS policy -> response headers

Key Points

  • Understand the purpose of how do you prevent cors misconfiguration?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q124API Security

How do you protect against XSS in API-backed applications?

APIs should avoid returning unsafe HTML and should encode or sanitize content according to its eventual output context.

Answer

APIs should avoid returning unsafe HTML and should encode or sanitize content according to its eventual output context. Content Security Policy helps browsers, but it does not replace safe rendering or input handling.

Syntax

render text as text, not raw HTML

Example

Store user comments as data and render them with framework escaping instead of injecting raw markup.

Code example

// In React, render {comment.body}; avoid dangerouslySetInnerHTML for untrusted content

Diagram

Untrusted text -> safe encoding/rendering -> browser

Key Points

  • Understand the purpose of how do you protect against xss in api-backed applications?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q126API Security

How do you store passwords securely?

Use a dedicated password-hashing algorithm such as Argon2id, scrypt, or bcrypt with an appropriate cost.

Answer

Use a dedicated password-hashing algorithm such as Argon2id, scrypt, or bcrypt with an appropriate cost. Never store plaintext or reversible encryption of passwords; support safe reset and rate limiting.

Syntax

argon2.hash(password)

Example

Verify a login by comparing the submitted password through the hashing library's verification function.

Code example

const hash = await argon2.hash(password); const ok = await argon2.verify(hash, submittedPassword);

Diagram

Password -> slow salted hash -> stored hash; login -> verify

Key Points

  • Understand the purpose of how do you store passwords securely?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q127API Security

How do you manage API keys?

Generate high-entropy keys, show secrets only once where possible, store hashes for verification when feasible, scope permissions, set expiry/rotation, and audit usage.

Answer

Generate high-entropy keys, show secrets only once where possible, store hashes for verification when feasible, scope permissions, set expiry/rotation, and audit usage. Never put keys in URLs or logs.

Syntax

Authorization: Bearer <api-key>

Example

Revoke a leaked integration key without rotating every customer's credentials.

Code example

const presentedHash = sha256(apiKey); const keyRecord = await keyStore.findByHash(presentedHash);

Diagram

Client key -> hash/lookup -> scope + status check -> access

Key Points

  • Understand the purpose of how do you manage api keys?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q128API Security

How do you mitigate brute-force and credential-stuffing attacks?

Combine rate limits, progressive delays, breached-password checks, MFA, bot detection, monitoring, and generic login errors.

Answer

Combine rate limits, progressive delays, breached-password checks, MFA, bot detection, monitoring, and generic login errors. Avoid permanent account lockout policies that attackers can exploit to deny service.

Syntax

limit by account + IP + device signals

Example

Apply stricter limits to repeated login failures while preserving a safe recovery path for the legitimate account owner.

Code example

if (attempts.exceeded(identity, ip)) return res.status(429).json({ message: 'Try again later' });

Diagram

Login attempts -> risk/rate checks -> authenticate or throttle

Key Points

  • Understand the purpose of how do you mitigate brute-force and credential-stuffing attacks?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it

Advanced Questions

Architecture, optimization, and design trade-offs.

Q26Node.js

What is the difference between process.nextTick, queueMicrotask, and setImmediate?

They schedule work at different points.

Answer

They schedule work at different points. process.nextTick runs before the event loop continues and can starve I/O if abused; queueMicrotask schedules a microtask; setImmediate runs in the check phase. Exact ordering can depend on context.

Syntax

process.nextTick(fn); queueMicrotask(fn); setImmediate(fn);

Example

Do not recursively schedule unbounded nextTick callbacks in a high-throughput server.

Code example

queueMicrotask(() => console.log('microtask')); setImmediate(() => console.log('check phase'));

Diagram

Current callback -> microtasks/nextTick -> event-loop phases

Key Points

  • Understand the purpose of what is the difference between process.nexttick, queuemicrotask, and setimmediate?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q28Node.js

What is backpressure in streams?

Backpressure occurs when a destination consumes data more slowly than a source produces it.

Answer

Backpressure occurs when a destination consumes data more slowly than a source produces it. Stream piping and the write() return value help producers slow down instead of buffering unbounded data.

Syntax

if (!writable.write(chunk)) await once(writable, 'drain')

Example

Pause a file producer while a slow network client catches up.

Code example

if (!res.write(chunk)) await once(res, 'drain');

Diagram

Fast producer -> bounded buffer -> slow consumer

Key Points

  • Understand the purpose of what is backpressure in streams?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q30Node.js

What is the libuv thread pool used for?

libuv provides the event loop and a worker pool for selected operations such as many filesystem tasks, some DNS operations, and crypto work.

Answer

libuv provides the event loop and a worker pool for selected operations such as many filesystem tasks, some DNS operations, and crypto work. It is not a general worker for every JavaScript callback.

Syntax

UV_THREADPOOL_SIZE=8 node app.js

Example

Heavy password hashing can contend for worker-pool capacity, so benchmark before tuning.

Code example

// Benchmark crypto/fs workloads before changing UV_THREADPOOL_SIZE

Diagram

JS event loop -> libuv worker pool -> completion callback

Key Points

  • Understand the purpose of what is the libuv thread pool used for?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q59NestJS

How do you implement transactions in NestJS?

A transaction groups related database operations so they commit or roll back together.

Answer

A transaction groups related database operations so they commit or roll back together. The exact API depends on the ORM; all operations in the unit of work must use the same transaction context.

Syntax

dataSource.transaction(async manager => { ... })

Example

Create an order and its line items atomically so partial writes are not left behind.

Code example

await dataSource.transaction(async (manager) => { await manager.save(order); await manager.save(lines); });

Diagram

Begin -> writes -> commit; error -> rollback

Key Points

  • Understand the purpose of how do you implement transactions in nestjs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q61NestJS

How do you build a NestJS microservice?

NestJS supports message-based microservices with transport adapters.

Answer

NestJS supports message-based microservices with transport adapters. Define message contracts, validate payloads, handle retries and timeouts, and make handlers idempotent.

Syntax

@MessagePattern('orders.created')

Example

A billing service consumes an order-created message and records an idempotent billing operation.

Code example

@MessagePattern('orders.created') handle(@Payload() event: OrderCreated) { return this.billing.process(event); }

Diagram

Producer -> broker/transport -> Nest handler -> domain service

Key Points

  • Understand the purpose of how do you build a nestjs microservice?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q62NestJS

What is the difference between request-scoped and singleton providers?

Singleton providers are shared by default and are efficient for stateless services.

Answer

Singleton providers are shared by default and are efficient for stateless services. Request-scoped providers are created per request and can increase allocation and dependency-resolution overhead; use them only when request-specific lifecycle is necessary.

Syntax

@Injectable({ scope: Scope.REQUEST })

Example

Keep ordinary repositories singleton-scoped; pass request context explicitly unless request scope provides clear value.

Code example

@Injectable({ scope: Scope.REQUEST }) export class RequestContext {}

Diagram

Singleton shared across requests; request-scoped instance per request

Key Points

  • Understand the purpose of what is the difference between request-scoped and singleton providers?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q76REST

What are ETags and conditional requests?

An ETag identifies a representation version.

Answer

An ETag identifies a representation version. Clients can use If-None-Match for cache validation or If-Match to prevent lost updates; the server should return 304 or 412 as appropriate.

Syntax

If-Match: "version-7"

Example

Reject an update if the record changed since the client fetched it.

Code example

if (req.headers['if-match'] !== currentEtag) return res.sendStatus(412);

Diagram

GET -> ETag -> client edits -> If-Match -> update or 412

Key Points

  • Understand the purpose of what are etags and conditional requests?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q77REST

How do you prevent duplicate POST operations?

For operations that clients may retry, accept an idempotency key and persist the key, request fingerprint, and outcome atomically.

Answer

For operations that clients may retry, accept an idempotency key and persist the key, request fingerprint, and outcome atomically. Replays return the original result; key reuse with different input should be rejected.

Syntax

Idempotency-Key: 8e03978e-40d5-43e8-bc93-6894a57f9324

Example

A payment endpoint returns the stored result for a repeated key rather than charging twice.

Code example

const key = req.get('Idempotency-Key'); // look up and persist key with operation

Diagram

POST + key -> atomic key check/write -> one business effect

Key Points

  • Understand the purpose of how do you prevent duplicate post operations?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q78REST

What is HATEOAS?

HATEOAS exposes links or actions in resource representations so clients can discover available transitions.

Answer

HATEOAS exposes links or actions in resource representations so clients can discover available transitions. Many practical APIs use only parts of the REST constraints; if links are provided, keep their semantics stable.

Syntax

{ id: 7, links: [{ rel: 'self', href: '/orders/7' }] }

Example

An order response can include a cancel link only when cancellation is currently permitted.

Code example

res.json({ id: order.id, links: [{ rel: 'self', href: `/orders/${order.id}` }] });

Diagram

Resource representation -> links -> discoverable next actions

Key Points

  • Understand the purpose of what is hateoas?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q92GraphQL

How do you limit GraphQL query complexity?

Deep or broad GraphQL queries can amplify backend work.

Answer

Deep or broad GraphQL queries can amplify backend work. Apply depth and complexity limits, pagination, timeouts, rate limits, and query allowlisting for sensitive high-cost environments.

Syntax

maxDepth: 8; maxComplexity: 1000

Example

Reject a query that nests relationships excessively or asks for thousands of records at once.

Code example

// Configure schema validation with depth/complexity rules in the chosen GraphQL server

Diagram

Query -> validation/cost analysis -> execute or reject

Key Points

  • Understand the purpose of how do you limit graphql query complexity?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q95GraphQL

How do subscriptions work in GraphQL?

Subscriptions deliver event-driven updates, commonly over WebSockets or another supported transport.

Answer

Subscriptions deliver event-driven updates, commonly over WebSockets or another supported transport. Authenticate connections, authorize each subscription, bound fan-out, and clean up resources when clients disconnect.

Syntax

subscription { orderUpdated(orderId: "o1") { status } }

Example

A dashboard subscribes to updates for orders the current user is allowed to view.

Code example

// Publish orderUpdated events through a configured PubSub implementation

Diagram

Domain event -> PubSub -> authorized subscription -> client

Key Points

  • Understand the purpose of how do subscriptions work in graphql?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q98GraphQL

How do you cache GraphQL responses?

Caching can occur at HTTP, CDN, resolver, or data-loader layers.

Answer

Caching can occur at HTTP, CDN, resolver, or data-loader layers. Because queries may select different fields and authorization changes cacheability, define cache keys and private/public rules carefully.

Syntax

Cache-Control: public, max-age=60

Example

Cache public product catalog fields but avoid shared caching of private user-specific results.

Code example

// Set cache hints only for fields whose data and authorization permit shared caching

Diagram

Query + variables + identity/cache policy -> cache -> resolvers

Key Points

  • Understand the purpose of how do you cache graphql responses?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q106Validation

How do you prevent mass assignment?

Mass assignment occurs when untrusted fields are copied wholesale into a model.

Answer

Mass assignment occurs when untrusted fields are copied wholesale into a model. Use allowlisted DTOs and explicit field mapping, and protect privileged properties such as roles, tenant IDs, and ownership.

Syntax

const update = { displayName: dto.displayName }

Example

Ignore or reject isAdmin in a public profile update rather than spreading the request body into the user entity.

Code example

const patch = { displayName: dto.displayName, timezone: dto.timezone }; await repo.update(id, patch);

Diagram

Request fields -> allowlist -> explicit mapping -> entity

Key Points

  • Understand the purpose of how do you prevent mass assignment?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q113Validation

How do you validate business invariants?

Business invariants belong in domain/application logic, not only request DTOs, because they must hold regardless of whether data came from HTTP, a queue, or a scheduled job.

Answer

Business invariants belong in domain/application logic, not only request DTOs, because they must hold regardless of whether data came from HTTP, a queue, or a scheduled job. Enforce invariants close to the state change and use transactions where needed.

Syntax

assert balance >= amount before transfer

Example

A transfer service checks available balance and atomically debits and credits accounts.

Code example

await db.transaction(async tx => { const account = await tx.lockAccount(id); if (account.balance < amount) throw new Error('Insufficient funds'); await tx.transfer(id, targetId, amount); });

Diagram

Any input channel -> use case -> invariant check -> atomic state change

Key Points

  • Understand the purpose of how do you validate business invariants?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q114Validation

How do you prevent validation time-of-check/time-of-use bugs?

A value can change between a check and a later write.

Answer

A value can change between a check and a later write. For invariants involving shared state, use database constraints, transactions, optimistic versions, or locks rather than relying only on a prior read.

Syntax

UPDATE inventory SET qty = qty - 1 WHERE id = $1 AND qty > 0

Example

Use a conditional update and verify one row changed to avoid overselling inventory.

Code example

const result = await db.query('UPDATE inventory SET qty = qty - 1 WHERE id = $1 AND qty > 0', [id]); if (result.rowCount !== 1) throw new Error('Out of stock');

Diagram

Read/check + concurrent change risk -> atomic conditional write

Key Points

  • Understand the purpose of how do you prevent validation time-of-check/time-of-use bugs?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q120API Security

What is object-level authorization and BOLA?

Broken Object Level Authorization occurs when an API checks that a user is authenticated but fails to verify access to the specific object requested.

Answer

Broken Object Level Authorization occurs when an API checks that a user is authenticated but fails to verify access to the specific object requested. Enforce tenant and ownership rules on every object lookup or mutation.

Syntax

WHERE id = $1 AND tenant_id = $2

Example

Do not fetch /invoices/123 solely by ID and return it without checking tenant ownership.

Code example

const invoice = await repo.findByIdAndTenant(id, user.tenantId);

Diagram

User identity + object ID -> ownership/tenant check -> allow or deny

Key Points

  • Understand the purpose of what is object-level authorization and bola?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q121API Security

How do you prevent broken function-level authorization?

Function-level authorization ensures only permitted roles or capabilities can invoke sensitive operations.

Answer

Function-level authorization ensures only permitted roles or capabilities can invoke sensitive operations. Apply server-side policies to administrative and privileged endpoints; hiding buttons in the UI is not security.

Syntax

requirePermission(user, 'users:delete')

Example

A normal user must not access an admin endpoint by guessing its URL.

Code example

if (!permissions.has(user, 'users:delete')) throw new ForbiddenError();

Diagram

Request -> role/permission policy -> privileged handler

Key Points

  • Understand the purpose of how do you prevent broken function-level authorization?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q123API Security

How do you protect against CSRF?

CSRF exploits ambient browser credentials such as automatically sent cookies.

Answer

CSRF exploits ambient browser credentials such as automatically sent cookies. Use SameSite cookies, anti-CSRF tokens or appropriate origin checks, and avoid state-changing GET endpoints. Bearer tokens not automatically attached by browsers have different CSRF exposure but still need XSS protection.

Syntax

SameSite=Lax; CSRF token on state-changing form

Example

A cookie-authenticated transfer endpoint verifies a CSRF token and trusted Origin before processing.

Code example

if (!validCsrf(req)) return res.sendStatus(403);

Diagram

Browser cookie -> CSRF/origin check -> state-changing action

Key Points

  • Understand the purpose of how do you protect against csrf?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q125API Security

How do you prevent SSRF?

Server-Side Request Forgery occurs when an attacker makes the server request unintended destinations.

Answer

Server-Side Request Forgery occurs when an attacker makes the server request unintended destinations. Restrict outbound destinations, validate schemes/hosts, block private and link-local IP ranges, re-check redirects and DNS resolution, and use egress controls.

Syntax

allowlisted host + http/https only

Example

A URL preview feature must not fetch cloud metadata endpoints or internal admin services.

Code example

if (!allowedHosts.has(url.hostname) || !['https:'].includes(url.protocol)) throw new Error('URL not allowed');

Diagram

User URL -> parse/allowlist -> DNS/IP checks -> controlled egress

Key Points

  • Understand the purpose of how do you prevent ssrf?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it
Q130API Security

How do you keep dependencies and APIs secure in production?

Use lockfiles, dependency scanning, timely security updates, least-privilege service identities, TLS, secure headers, threat modeling, penetration testing, and incident response.

Answer

Use lockfiles, dependency scanning, timely security updates, least-privilege service identities, TLS, secure headers, threat modeling, penetration testing, and incident response. Monitor known vulnerabilities and test fixes in CI.

Syntax

npm audit; SCA scan in CI

Example

Fail or flag builds when a critical exploitable dependency vulnerability is detected according to the team's policy.

Code example

// CI: install from lockfile -> run tests -> dependency/SAST scans -> deploy

Diagram

Code -> CI security checks -> staged deployment -> monitoring

Key Points

  • Understand the purpose of how do you keep dependencies and apis secure in production?
  • Validate inputs and handle failure cases
  • Apply the pattern consistently and test it

Share this question bank

Send this page to someone preparing for an interview.