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.
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.
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