Node.js knowledge reference Essential Node.js Concepts Explore all 60 knowledge cards from one complete menu. The supplied Node.js, Express, caching, production, and senior refactoring guides have been combined into distinct concepts with concise explanations, memory formulas, examples, and practical uses.
Concept 01 What is Node.js? Quick recall Concept Glance Card 30 sec
01 Easy tipJavaScript runtime outside the browser. 02 Concise explanation“Node.js is an open-source, cross-platform JavaScript runtime built on V8. It provides server-side APIs for files, networking, processes, streams, and other operating-system work.”
03 Memory formulaJavaScript + V8 + Node APIs = server-side runtime04 Real-world usesAPIs web servers CLI tools real-time services Concept 02 What is a runtime environment? Quick recall Concept Glance Card 30 sec
01 Easy tipThe engine and APIs needed to execute code. 02 Concise explanation“A runtime environment supplies the execution engine, built-in APIs, memory management, error handling, and access to its host system. Node.js provides different capabilities from a browser runtime.”
03 Memory formulaEngine + host APIs + execution services = runtime04 Real-world usesenvironment comparisons platform APIs debugging Concept 03 How is Node.js different from JavaScript? Quick recall Concept Glance Card 30 sec
01 Easy tipJavaScript is the language; Node.js is one host. 02 Concise explanation“JavaScript defines language syntax and behavior. Node.js is a runtime that executes JavaScript and adds server-side APIs such as process, Buffer, node:fs, and node:http.”
03 Memory formulaLanguage describes code; runtime executes it04 Real-world usesfull-stack development API selection environment debugging Concept 04 How does Node.js work internally? Quick recall Concept Glance Card 30 sec
01 Easy tipV8 executes; libuv and the OS coordinate I/O. 02 Concise explanation“V8 executes JavaScript on the main thread. Node APIs, libuv, the operating system, and a worker pool coordinate asynchronous work; completed work becomes eligible to continue through the event loop.”
03 Memory formulaV8 + Node APIs + libuv + OS = Node runtime04 Real-world usesperformance reasoning concurrency design runtime debugging Concept 05 Why is Node.js called single-threaded? Quick recall Concept Glance Card 30 sec
01 Easy tipJavaScript has one main thread, not the whole runtime. 02 Concise explanation“A standard Node.js process normally executes JavaScript on one main thread. The runtime can still use OS I/O, libuv workers, worker threads, child processes, and multiple application processes.”
03 Memory formulaOne JavaScript thread != one runtime thread04 Real-world usesevent-loop reasoning CPU planning scaling decisions Concept 06 When is Node.js a good choice? Quick recall Concept Glance Card 30 sec
01 Easy tipChoose it for concurrent I/O, not blindly for every workload. 02 Concise explanation“Node.js is strong for APIs, real-time systems, streaming, gateways, and I/O-heavy services. CPU-heavy work may need worker threads, background jobs, separate processes, or a specialized service.”
03 Memory formulaMany waiting connections = strong fit; heavy CPU = isolate work04 Real-world usestechnology selection API services real-time systems Concept 07 How do you create a basic Node.js HTTP server? Quick recall Concept Glance Card 30 sec
01 Easy tipCreate, respond, end, and listen. import { createServer } from 'node:http';
createServer((_request, response) => {
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end('Hello, World!');
}).listen(3000); 02 Concise explanation“Load node:http, call createServer with a request handler, complete each response with res.end(), and call listen() on a port.”
03 Memory formulacreateServer -> request handler -> end -> listen04 Real-world useshealth checks HTTP fundamentals framework debugging Concept 08 What is the difference between synchronous and asynchronous code? Quick recall Concept Glance Card 30 sec
01 Easy tipSynchronous waits; asynchronous continues and handles the result later. 02 Concise explanation“Synchronous code blocks progression until an operation completes. Asynchronous code starts work, allows other work to continue, and processes the result later through callbacks, Promises, or events.”
03 Memory formulaSync = wait now; async = continue then resume04 Real-world usesfile access database calls network requests Concept 09 How does Node.js achieve asynchronous programming? Quick recall Concept Glance Card 30 sec
01 Easy tipNon-blocking APIs hand work to the runtime and resume later. 02 Concise explanation“Node.js uses non-blocking APIs, OS facilities, libuv, callbacks, Promises, async/await, and the event loop. Not every asynchronous operation runs in a background thread.”
03 Memory formulaRegister work -> continue -> completion queued -> callback runs04 Real-world usesconcurrent servers I/O workflows latency management Concept 10 How does the Node.js event loop work? Quick recall Concept Glance Card 30 sec
01 Easy tipIt coordinates callbacks through libuv phases. 02 Concise explanation“The event loop processes timers, pending callbacks, poll, check, and close callbacks. The next-tick queue and Promise microtasks run between appropriate callbacks and phases.”
03 Memory formulaTimers -> pending -> poll -> check -> close04 Real-world usestiming bugs server responsiveness performance analysis Concept 11 How is the Node.js event loop different from the browser event loop? Quick recall Concept Glance Card 30 sec
01 Easy tipNode coordinates server I/O; browsers also coordinate rendering. 02 Concise explanation“Both environments schedule tasks and microtasks, but Node.js integrates with libuv phases, files, sockets, and processes, while browsers coordinate DOM events, rendering, layout, and Web APIs.”
03 Memory formulaNode = libuv I/O; browser = Web APIs + rendering04 Real-world usescross-runtime debugging timing behavior platform design Concept 12 How do process.nextTick(), setImmediate(), and setTimeout() differ? Quick recall Concept Glance Card 30 sec
01 Easy tipNext tick before loop progress; immediate in check; timeout after a threshold. 02 Concise explanation“process.nextTick runs after the current operation before the event loop continues, setImmediate runs in the check phase, and setTimeout runs after its minimum timer delay. Ordering between immediate and zero-delay timeout is context-dependent.”
03 Memory formulanextTick -> before loop; immediate -> check; timeout -> threshold04 Real-world usesscheduling I/O continuation timing diagnostics Concept 13 What is callback hell and how do you avoid it? Quick recall Concept Glance Card 30 sec
01 Easy tipDeep nesting hides control flow and errors. 02 Concise explanation“Callback hell is deeply nested asynchronous control flow. Avoid it with named functions, Promises, async/await, small responsibilities, and consistent error propagation.”
03 Memory formulaFlatten control flow + separate responsibilities04 Real-world useslegacy refactoring error handling workflow design Concept 14 How do Promises and async/await work in Node.js? Quick recall Concept Glance Card 30 sec
01 Easy tipAsync functions return Promises; await pauses only that function. 02 Concise explanation“A Promise represents eventual fulfillment or rejection. An async function always returns a Promise, and await suspends that function until a value settles without blocking the whole Node.js process.”
03 Memory formulaasync -> Promise; await -> suspend function, not process04 Real-world usesI/O orchestration error propagation readable workflows Concept 15 How does Node.js handle asynchronous errors? Quick recall Concept Glance Card 30 sec
01 Easy tipThe handling mechanism follows the API style. 02 Concise explanation“Callback APIs use error-first callbacks, Promise APIs reject, and event-based APIs emit error events. A synchronous try/catch cannot catch an error thrown later in an unawaited callback.”
03 Memory formulaCallback -> error first; Promise -> rejection; emitter -> error event04 Real-world usesreliable services stream handling failure boundaries Concept 16 What is package.json? Quick recall Concept Glance Card 30 sec
01 Easy tipThe project manifest for metadata, scripts, modules, and dependencies. 02 Concise explanation“package.json records project metadata, scripts, dependencies, supported Node versions, package entry points, and module type. A lockfile separately pins the resolved dependency graph.”
03 Memory formulaIdentity + scripts + dependency contract + runtime settings04 Real-world usesproject setup CI commands package publishing Concept 17 How do CommonJS and ECMAScript modules differ? Quick recall Concept Glance Card 30 sec
01 Easy tipCommonJS uses require; ESM uses import and export. 02 Concise explanation“CommonJS uses require() and module.exports with runtime loading. ECMAScript modules use import and export with static structure, live bindings, and standard JavaScript module semantics.”
03 Memory formulaCJS = require/exports; ESM = import/export04 Real-world usespackage migration module interoperability tooling Concept 18 What happens when require() loads the same module repeatedly? Quick recall Concept Glance Card 30 sec
01 Easy tipCommonJS caches by resolved filename. 02 Concise explanation“The first require normally executes a CommonJS module and caches its exports by resolved filename. Later requires of that same resolution return the cached exports object.”
03 Memory formulaResolve -> execute once -> cache -> reuse exports04 Real-world usesshared module state performance test isolation Concept 19 Which built-in Node.js modules are most useful? Quick recall Concept Glance Card 30 sec
01 Easy tipCore modules need no npm installation. 02 Concise explanation“Common built-ins include node:http, node:fs, node:path, node:os, node:events, node:stream, node:url, node:crypto, node:worker_threads, and node:test.”
03 Memory formulaHTTP + files + paths + events + streams + platform04 Real-world usesservers file tools testing cryptography Concept 20 How should environment configuration be managed? Quick recall Concept Glance Card 30 sec
01 Easy tipValidate configuration once at startup and fail fast. 02 Concise explanation“Read environment values through process.env or a secret provider, validate and convert them at startup, expose typed configuration, and never commit or log real secrets.”
03 Memory formulaLoad -> validate -> type -> fail fast -> never log secrets04 Real-world usesdeployments secret management environment parity Concept 21 What is the difference between Node.js and Express? Quick recall Concept Glance Card 30 sec
01 Easy tipNode is the runtime; Express is a web framework. 02 Concise explanation“Node.js executes JavaScript and provides low-level HTTP APIs. Express runs on Node.js and adds routing, middleware, request parsing, response helpers, and error-handling conventions.”
03 Memory formulaNode runtime + Express web layer04 Real-world usesAPI development framework selection architecture explanation Concept 22 What is middleware in Express? Quick recall Concept Glance Card 30 sec
01 Easy tipA function in the request-response pipeline. 02 Concise explanation“Middleware can inspect or modify a request, modify the response, send a response, call next() to continue, or call next(error) to enter error handling.”
03 Memory formulaRequest -> middleware stack -> route -> response04 Real-world usesauthentication validation logging security headers Concept 23 What do app.use() and next() do? Quick recall Concept Glance Card 30 sec
01 Easy tipuse registers pipeline steps; next advances the pipeline. 02 Concise explanation“app.use registers middleware or mounts a router, optionally under a path prefix. next() passes control to the next matching function, while next(error) skips normal middleware for error handlers.”
03 Memory formulause = register; next = continue; next(error) = fail04 Real-world usesmiddleware composition router mounting error flow Concept 24 How do application-level and router-level middleware differ? Quick recall Concept Glance Card 30 sec
01 Easy tipThey differ by registration boundary, not capability. 02 Concise explanation“Application middleware is registered on app; router middleware is registered on an express.Router instance. Both can be path-limited, while routers group related features and endpoints.”
03 Memory formulaapp boundary vs feature router boundary04 Real-world usesmodular APIs feature isolation middleware scoping Concept 25 How does routing work in Express? Quick recall Concept Glance Card 30 sec
01 Easy tipMatch an HTTP method and path to handlers. 02 Concise explanation“Express routes match the request method and URL path in registration order. Dynamic path segments become req.params, while query-string values become req.query.”
03 Memory formulaMethod + path + ordered handlers = route04 Real-world usesREST APIs resource endpoints modular routers Concept 26 What is the difference between req.params, req.query, and req.body? Quick recall Concept Glance Card 30 sec
01 Easy tipPath identity, query options, and submitted content. 02 Concise explanation“req.params contains named path segments, req.query contains values after ?, and req.body contains parsed request-body data. Every client-provided value must be validated.”
03 Memory formulaparams = path; query = options; body = payload04 Real-world usesresource lookup filtering form and JSON input Concept 27 Is body-parser still required in Express? Quick recall Concept Glance Card 30 sec
01 Easy tipModern Express handles common JSON and form bodies itself. 02 Concise explanation“Most applications can use express.json() and express.urlencoded(). Specialized content such as multipart uploads, raw webhook signatures, or plain text may need different middleware.”
03 Memory formulaParse content type -> validate resulting value04 Real-world usesJSON APIs forms webhooks uploads Concept 28 How should Express handle 404s and errors? Quick recall Concept Glance Card 30 sec
01 Easy tipNormal routes first, 404 next, error middleware last. 02 Concise explanation“Register a final unmatched-request handler for 404 responses, followed by four-argument error middleware. Return safe client messages and log internal details with correlation context.”
03 Memory formulaRoutes -> 404 -> error handler04 Real-world usesconsistent APIs operational diagnostics secure failures Concept 29 How should HTTP methods and status codes be used? Quick recall Concept Glance Card 30 sec
01 Easy tipModel resource semantics, not just CRUD labels. 02 Concise explanation“GET retrieves, POST submits or creates, PUT creates or fully replaces a known resource, PATCH partially updates, and DELETE removes. Status codes should describe the actual result.”
03 Memory formulaMethod = intent; status = outcome04 Real-world usesREST APIs client contracts idempotency Concept 30 What is event-driven programming? Quick recall Concept Glance Card 30 sec
01 Easy tipProducers emit facts; listeners react. 02 Concise explanation“Event-driven programs respond to emitted events such as data arrival, connection changes, timers, or domain actions. This can reduce direct coupling between producers and consumers.”
03 Memory formulaEmitter -> named event -> listeners04 Real-world usesstreams domain events real-time services Concept 31 What does EventEmitter provide? Quick recall Concept Glance Card 30 sec
01 Easy tipon, once, emit, and off manage listeners. 02 Concise explanation“node:events provides EventEmitter for registering recurring or one-time listeners, emitting named events, and removing listeners. Unhandled error events are special and can terminate the process.”
03 Memory formulaon/once -> emit -> off; always handle error04 Real-world usescore Node APIs domain notifications stream events Concept 32 What is a Buffer? Quick recall Concept Glance Card 30 sec
01 Easy tipA fixed-size sequence of bytes. 02 Concise explanation“Buffer represents binary data used by files, network packets, encoded text, and stream chunks. Prefer Buffer.alloc() or Buffer.from(); allocUnsafe requires careful initialization.”
03 Memory formulaBuffer = bytes; stream = chunk-by-chunk flow04 Real-world usesbinary protocols files networking encoding Concept 33 What types of streams does Node.js provide? Quick recall Concept Glance Card 30 sec
01 Easy tipReadable, writable, duplex, and transform. 02 Concise explanation“Readable streams produce data, writable streams consume it, duplex streams do both, and transform streams modify data while passing it through.”
03 Memory formulaRead -> write; duplex = both; transform = both + change04 Real-world useslarge files uploads compression network sockets Concept 34 What is backpressure in a stream? Quick recall Concept Glance Card 30 sec
01 Easy tipSlow consumers must regulate fast producers. 02 Concise explanation“Backpressure prevents a readable producer from overwhelming a slower writable consumer. pipe() and pipeline() coordinate flow, while manual writes must respect write() and the drain event.”
03 Memory formulaProducer speed > consumer speed -> pause until drain04 Real-world usesmemory control file pipelines network services Concept 35 How do child processes work in Node.js? Quick recall Concept Glance Card 30 sec
01 Easy tipUse spawn, exec, execFile, or fork for separate processes. 02 Concise explanation“spawn streams command I/O, exec buffers shell output, execFile runs an executable directly, and fork starts another Node.js process with IPC. Never interpolate untrusted input into shell commands.”
03 Memory formulaspawn = stream; exec = shell buffer; execFile = direct; fork = Node IPC04 Real-world usessystem commands isolated programs background processing Concept 36 What is the difference between clusters and worker threads? Quick recall Concept Glance Card 30 sec
01 Easy tipClusters scale processes; workers run JavaScript on extra threads. 02 Concise explanation“Cluster workers are separate Node.js processes with separate heaps and event loops, useful for server scaling. Worker threads run JavaScript on additional threads in one process and suit CPU-intensive computation.”
03 Memory formulaCluster = process isolation; worker = CPU thread04 Real-world usesmulti-core servers CPU work fault isolation Concept 37 How should CPU-bound work be handled? Quick recall Concept Glance Card 30 sec
01 Easy tipMove heavy computation away from the request event loop. 02 Concise explanation“Use worker threads, child processes, background queues, or specialized external services. Ordinary asynchronous I/O APIs do not make CPU-heavy JavaScript non-blocking.”
03 Memory formulaCPU-heavy request -> isolate or queue work04 Real-world usesimage processing large parsing calculations media jobs Concept 38 How should a Node.js service shut down gracefully? Quick recall Concept Glance Card 30 sec
01 Easy tipStop new work, finish bounded work, release resources, then exit. 02 Concise explanation“On SIGTERM, stop accepting connections, allow in-flight requests a deadline, close databases and queues, flush essential telemetry, and exit so the supervisor can replace the process.”
03 Memory formulaSignal -> stop intake -> drain -> close -> exit04 Real-world usesdeployments container shutdown reliable restarts Concept 39 How do you secure a Node.js application? Quick recall Concept Glance Card 30 sec
01 Easy tipSecurity is layered, not one middleware package. 02 Concise explanation“Validate input, authorize every protected action, use HTTPS and secure cookies, parameterize database queries, set security headers, rate-limit abuse, protect secrets, restrict uploads, and maintain dependencies.”
03 Memory formulaValidate + authorize + encrypt + limit + monitor04 Real-world usesAPI security authentication production hardening Concept 40 What is CORS and how should Express configure it? Quick recall Concept Glance Card 30 sec
01 Easy tipThe server declares which browser origins may read responses. 02 Concise explanation“CORS is a browser-enforced HTTP-header protocol. Configure an explicit origin policy, allowed methods and headers, and credentials only where required; it does not replace authentication.”
03 Memory formulaBrowser origin + server permission headers04 Real-world usesfrontend APIs credentialed requests cross-origin security Concept 41 How should sessions and cookies be secured? Quick recall Concept Glance Card 30 sec
01 Easy tipKeep sensitive session state server-side and harden its identifier. 02 Concise explanation“Use HttpOnly, Secure, and appropriate SameSite cookies; rotate session identifiers; store sessions in a shared production store; and enforce expiry, CSRF defenses, and server-side authorization.”
03 Memory formulaSecure cookie ID + shared store + expiry + authorization04 Real-world useslogin sessions CSRF defense multi-instance APIs Concept 42 How should authentication and authorization differ? Quick recall Concept Glance Card 30 sec
01 Easy tipAuthentication proves identity; authorization permits an action. 02 Concise explanation“Authenticate credentials at a trusted boundary, then authorize every protected operation against the current user, resource, and action. A valid login or token does not automatically grant access to every record.”
03 Memory formulaAuthenticate who -> authorize what on which resource04 Real-world usesAPI access control role checks ownership enforcement Concept 43 How do you prevent injection attacks in Node.js? Quick recall Concept Glance Card 30 sec
01 Easy tipTreat every external value as data, never executable syntax. 02 Concise explanation“Validate request data against an allowlist schema, use parameterized database queries, avoid shell command construction, encode output for its context, and restrict dynamic file paths and template execution.”
03 Memory formulaValidate shape + parameterize sinks + encode output04 Real-world usesSQL and NoSQL safety command execution server-rendered output Concept 44 How do CSRF, CORS, and security headers protect different boundaries? Quick recall Concept Glance Card 30 sec
01 Easy tipCSRF checks intent; CORS controls browser reads; headers harden responses. 02 Concise explanation“CSRF defenses protect cookie-authenticated state changes, CORS controls which browser origins may read responses, and headers such as Content-Security-Policy and HSTS reduce browser attack surface. None replaces authentication or authorization.”
03 Memory formulaCSRF = request intent; CORS = origin reads; headers = browser policy04 Real-world usescookie sessions cross-origin APIs browser hardening Concept 45 How do you optimize a Node.js service for production? Quick recall Concept Glance Card 30 sec
01 Easy tipMeasure bottlenecks before changing architecture. 02 Concise explanation“Track latency, errors, CPU, memory, event-loop delay, database performance, and external calls. Then address blocking work, slow queries, caching, compression, connection limits, and horizontal scaling.”
03 Memory formulaMeasure -> find bottleneck -> change -> verify04 Real-world usesperformance tuning capacity planning incident response Concept 46 What observability should a Node.js API include? Quick recall Concept Glance Card 30 sec
01 Easy tipLogs explain events; metrics show trends; traces connect work. 02 Concise explanation“Use structured logs with request IDs, service metrics, distributed traces, error tracking, health and readiness checks, dashboards, and actionable alerts without recording secrets.”
03 Memory formulaLogs + metrics + traces + health + alerts04 Real-world usesproduction operations debugging SLO monitoring Concept 47 What is the cache-aside pattern? Quick recall Concept Glance Card 30 sec
01 Easy tipCheck cache, load on miss, store, and return. 02 Concise explanation“With cache-aside, the application reads the cache first, fetches missing data from its source, stores it with a TTL, and invalidates or replaces it when the source changes.”
03 Memory formulaGet -> hit return; miss -> load -> set -> return04 Real-world usesdatabase load reduction external API caching latency reduction Concept 48 What are cache hits, misses, TTL, and invalidation? Quick recall Concept Glance Card 30 sec
01 Easy tipFound, absent, lifetime, and removal. 02 Concise explanation“A hit finds a usable value, a miss requires the source, TTL limits how long an entry remains valid, and invalidation removes stale data when the underlying value changes.”
03 Memory formulaHit/miss = lookup result; TTL/invalidation = freshness04 Real-world usescache monitoring freshness policy write workflows Concept 49 What is a cache stampede? Quick recall Concept Glance Card 30 sec
01 Easy tipMany simultaneous misses regenerate the same value. 02 Concise explanation“A cache stampede occurs when a popular key expires and many requests call the source together. Mitigations include request coalescing, locking, stale-while-revalidate, jittered TTLs, and prewarming.”
03 Memory formulaPopular expiry + concurrent misses = source surge04 Real-world usestraffic spikes database protection resilient caching Concept 50 When should you use Redis instead of an in-memory cache? Quick recall Concept Glance Card 30 sec
01 Easy tipUse shared storage when several processes need one cache view. 02 Concise explanation“Use a distributed cache when multiple processes or servers need shared values, atomic operations, shared rate limits or sessions, larger capacity, or persistence beyond an application restart.”
03 Memory formulaOne process -> local cache; many instances -> shared cache04 Real-world useshorizontal scaling shared sessions distributed rate limiting Concept 51 How does HTTP caching reduce work in a Node.js API? Quick recall Concept Glance Card 30 sec
01 Easy tipLet clients and intermediaries reuse responses safely. 02 Concise explanation“Set Cache-Control for freshness and sharing rules, provide ETag or Last-Modified validators, and vary responses on every request property that changes the representation. A valid conditional request can return 304 without resending the body.”
03 Memory formulaFresh response -> reuse; stale + valid -> 304; changed -> new body04 Real-world usesREST APIs CDN caching bandwidth reduction Concept 52 How do you keep cached data consistent after writes? Quick recall Concept Glance Card 30 sec
01 Easy tipEvery write needs an explicit cache update or invalidation policy. 02 Concise explanation“After the source of truth commits, invalidate affected keys or update them with the committed value. Design keys around query dependencies, accept a defined staleness window, and use versioning or events when several services own cached views.”
03 Memory formulaCommit source -> invalidate or update -> tolerate defined staleness04 Real-world useswrite workflows distributed services derived queries Concept 53 How should an application handle cache failures? Quick recall Concept Glance Card 30 sec
01 Easy tipA cache should improve service, not become an unbounded failure amplifier. 02 Concise explanation“Use short timeouts, bounded retries, connection limits, circuit breaking where appropriate, and metrics. Decide per operation whether to fall back to the source, serve stale data, reject load, or fail closed for security-sensitive state.”
03 Memory formulaBound cache wait -> fallback by policy -> observe degradation04 Real-world usesRedis outages latency control resilient APIs Concept 54 How should a maintainable Node.js API be structured? Quick recall Concept Glance Card 30 sec
01 Easy tipKeep HTTP, business logic, and data access at clear boundaries. 02 Concise explanation“Use modular features with thin routes or controllers, services for use-case orchestration, domain logic for business rules, repositories for persistence, and explicit schemas or DTOs at boundaries.”
03 Memory formulaRoute -> controller -> service/domain -> repository04 Real-world useslarge APIs team ownership testable architecture Concept 55 What are the SOLID principles in Node.js? Quick recall Concept Glance Card 30 sec
01 Easy tipDesign modules that have one purpose, extend cleanly, substitute safely, expose focused contracts, and depend on abstractions. interface PaymentGateway {
charge(request: ChargeRequest): Promise<ChargeResult>;
}
class CheckoutService {
constructor(private readonly gateway: PaymentGateway) {}
} 02 Concise explanation“SOLID means Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. In Node.js and TypeScript, these principles guide focused services, extensible strategies, compatible implementations, small interfaces, and injected dependencies.”
03 Memory formulaSRP + OCP + LSP + ISP + DIP = maintainable object design04 Real-world usesservice architecture dependency injection testable modules safe refactoring Concept 56 Why should controllers remain thin? Quick recall Concept Glance Card 30 sec
01 Easy tipControllers translate HTTP; services own application behavior. 02 Concise explanation“A controller should receive validated input, invoke a use case, select the HTTP response, and map output. Business calculations, persistence, and external-service policies belong behind focused interfaces.”
03 Memory formulaController = HTTP adapter, not business engine04 Real-world usesunit testing framework migration clear ownership Concept 57 Why is returning inside subscribe() not an outer return? Quick recall Concept Glance Card 30 sec
01 Easy tipA callback return belongs only to that callback. import { firstValueFrom } from 'rxjs';
const rate = await firstValueFrom(exchangeRateService.getRate()); 02 Concise explanation“The outer function normally finishes after registering the subscription. A return inside the subscription callback cannot become the earlier function’s return value.”
03 Memory formulaRegister callback -> outer returns -> callback runs later04 Real-world usesRxJS integration async refactoring NestJS services Concept 58 How should financial values be represented? Quick recall Concept Glance Card 30 sec
01 Easy tipDo not use display rounding as financial arithmetic. 02 Concise explanation“Represent money with integer minor units or a decimal type, define currency-specific rounding rules, persist with decimal database columns, and format only at presentation boundaries.”
03 Memory formulaExact representation + explicit rounding + separate formatting04 Real-world usespayments commissions exchange rates billing Concept 59 Why are idempotency and failure ordering important? Quick recall Concept Glance Card 30 sec
01 Easy tipRetries must not duplicate side effects. 02 Concise explanation“Distributed operations can partially succeed, and clients may retry after timeouts. Idempotency keys, transactions, outbox patterns, retries, and compensating actions keep repeated or partial workflows safe.”
03 Memory formulaRetry-safe identity + atomic local state + reliable publication04 Real-world usespayments webhooks job processing event publication Concept 60 How should a senior engineer approach an unfamiliar Node.js refactor? Quick recall Concept Glance Card 30 sec
01 Easy tipUnderstand boundaries, fix correctness first, then improve design. 02 Concise explanation“Trace the request and data flow, state assumptions, prioritize async and data-correctness bugs, make small named changes, preserve contracts, and verify each step with types and tests.”
03 Memory formulaUnderstand -> prioritize correctness -> small refactor -> verify04 Real-world useslive coding legacy modernization code review