Questions 161–180 of 200 · 0 of 20 on this page marked learned
161.nodejs-0161Easyfresher
What does helmet do in an Express app, and which security headers matter most?
helmet is Express middleware that sets a group of HTTP security headers and removes X-Powered-By. The important ones are Content-Security-Policy (limits where scripts and other content can load from, reducing XSS impact), Strict-Transport-Security (forces HTTPS), X-Content-Type-Options: nosniff, frame protection (frame-ancestors or X-Frame-Options), Referrer-Policy and Cross-Origin policies. Defaults are a good start, and the CSP needs tuning for your app.
Full answer
helmet is a collection of small middleware functions. app.use(helmet()) turns on sensible defaults.
Headers that matter
Content-Security-Policy (CSP): a list of allowed sources for scripts, styles, images, frames and connections. A strict policy (no inline scripts, nonces or hashes instead) greatly reduces the damage of an XSS bug. It is the most powerful and the hardest to configure.
Strict-Transport-Security (HSTS): tells browsers to use HTTPS only for a period (max-age). Only send it over HTTPS and test before enabling includeSubDomains and preload.
X-Content-Type-Options: nosniff stops browsers from guessing a different content type (for example executing an upload as script).
The same route is served with and without helmet, and the security headers are printed for each. Install first with npm install express helmet (run here with express 5.3.0, helmet 8.3.0). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
-- without helmet
x-powered-by Express
content-security-policy (not set)
strict-transport-security (not set)
x-content-type-options (not set)
referrer-policy (not set)
cross-origin-opener-policy (not set)
-- with helmet
x-powered-by (not set)
content-security-policy default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'none';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests
strict-transport-security max-age=31536000; includeSubDomains
x-content-type-options nosniff
referrer-policy no-referrer
cross-origin-opener-policy same-origin
Key points
helmet sets a group of security headers and removes X-Powered-By.
CSP limits script sources and reduces XSS damage.
HSTS forces HTTPS; nosniff stops content type guessing.
Headers are a second line of defence, not a fix for XSS.
Try CSP in report-only mode first.
Common mistakes
Adding helmet and believing XSS is solved.
Enabling HSTS preload without testing every subdomain.
A CSP with unsafe-inline that gives no protection.
Leaving X-Powered-By on.
Setting different header values in the proxy and in the app.
Follow-ups
How do nonces make inline scripts safe under a CSP?
What does HSTS preload mean?
Which headers matter for a JSON-only API?
Tips
Name CSP, HSTS and nosniff first.
Say that headers are defence in depth.
Mention report-only mode.
162.nodejs-0162Mediummid
How does Passport work with express-session: strategies, serializeUser and deserializeUser, and logout?
Passport is authentication middleware with pluggable strategies. A strategy (for example passport-local) checks credentials and calls done(null, user). With sessions, serializeUser stores a small identifier in the session at login and deserializeUser loads the full user from that identifier on later requests, which sets req.user. Protect routes by checking req.isAuthenticated(), and call req.logout with a callback to end the session.
Full answer
Passport separates three things
Strategies: how to verify a login (local username and password, OAuth providers such as Google, JWT, and many more).
Session support: after a successful login, remember the user for later requests.
Your routes: what to do with req.user.
Flow with passport-local
app.use(session(...)), app.use(passport.initialize()), app.use(passport.session()). Order matters: session first.
The strategy function receives (username, password, done). Look up the user, compare the password hash in constant time, then done(null, user) on success, done(null, false) on failure, and done(err) on a server error.
passport.authenticate('local') on the login route runs the strategy. On success, Passport calls req.login, which runs serializeUser(user, done). Store only the id: done(null, user.id).
On every later request, passport.session() reads the id from the session and calls deserializeUser(id, done), which loads the user and sets req.user. A failed lookup (user deleted) should clear the login.
Logout: req.logout((err) => ...) in Passport 0.6 and later (it is asynchronous because it regenerates the session).
Security notes
Passport 0.6 and later regenerates the session id at login, which prevents session fixation.
Use HttpOnly, Secure and SameSite cookies, a production session store (Redis), and CSRF protection for cookie sessions.
Do not store the whole user object in the session. It becomes stale and large.
For APIs consumed by other services prefer token strategies; for plain apps, sessions are fine.
A local strategy with a scrypt hash, a session cookie and a logout. The cookie is kept by hand because Node's fetch has no cookie jar. Install first with npm install express express-session passport passport-local (run here with express 5.3.0, express-session 1.19.0, passport 0.7.0, passport-local 1.0.0). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
/me before login : 401
login, wrong password : 401
login, right password : 200 {"user":"asha"}
/me with the cookie : 200
logout : 200
/me after logout : 401
Key points
Strategies verify credentials; sessions remember the user.
serializeUser stores an id, deserializeUser loads the user into req.user.
Session middleware must come before passport.session().
req.logout takes a callback in current Passport versions.
Passport regenerates the session at login.
Common mistakes
Putting passport.session() before the session middleware.
Storing the whole user in the session.
Comparing password hashes with ===.
Using req.logout() without a callback in new versions.
Skipping CSRF protection for cookie sessions.
Follow-ups
What does deserializeUser run on, and how often?
How would you add Google login with the same app?
How do you share sessions across several instances?
Tips
Explain strategy, serialize, deserialize.
Say that order matters.
Mention session fixation protection.
163.nodejs-0163Hardsenior
What is broken object level authorization (IDOR), and how do you design authorization checks with roles and ownership in a Node.js API?
Authentication says who you are, authorization says what you may do. IDOR (broken object level authorization) happens when a route trusts an id from the URL and returns the object without checking that it belongs to the caller, so changing /docs/2 to /docs/3 shows someone else's data. Fix it by checking permission for every object on the server, using one policy function (role plus ownership), scoping queries by owner, and not trusting client-supplied owner fields.
Full answer
The bug
GET /docs/:id loads the document by id and returns it. The user is logged in, so the route passes the authentication check, but nothing asks whether this user may see this document. Anyone can enumerate ids. It is number one on the OWASP API Security list.
Defences
Check on the server, every time, for every object and every action (read, update, delete). Do not rely on hidden ids or UI buttons.
One policy function: can(user, action, resource) that combines role rules (RBAC: admin may delete anything, teacher may read students in their class) and ownership or relationship rules (ABAC: owner may update). Call it from every route, so rules live in one tested place.
Scope queries: WHERE id = $1 AND owner_id = $2, or tenant_id = current tenant. A row that does not belong to you is simply not found.
Do not accept owner or role fields from the request body (mass assignment). Set them on the server from the session.
Return 404 instead of 403 when revealing existence is itself a leak. Use 403 when the user knows the resource exists and lacks rights.
Unpredictable ids (UUIDs) make guessing harder, but they are not an authorization control.
Test authorization: for each route, a test that user B cannot read, change or delete user A's object.
Related issues: broken function level authorization (a normal user calls an admin route), privilege escalation by changing the role in a token, and missing checks in background jobs and GraphQL resolvers.
The first request shows the IDOR bug. The policy routes allow owners and the teacher read rule, hide other people's documents, and ignore an owner field sent in the body. Install first with npm install express (run here with express 5.3.0). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
asha reads doc 2 (vulnerable route) 200 {"id":2,"ownerId":"ravi","title":"Ravi salary"}
asha reads doc 2 (policy route) 404 {"error":"not found"}
asha reads her own doc 1 200 {"id":1,"ownerId":"asha","title":"Asha notes"}
teacher reads doc 1 (role rule) 200 {"id":1,"ownerId":"asha","title":"Asha notes"}
teacher updates doc 1 (not allowed) 403 {"error":"forbidden"}
asha updates doc 1, tries to change owner 200 {"id":1,"ownerId":"asha","title":"Renamed"}
Key points
IDOR means the object was returned without an ownership check.
Authorize every object and action on the server.
Use one tested policy function and owner-scoped queries.
Never accept owner or role from the request body.
Test that user B cannot touch user A's data.
Common mistakes
Checking only that the user is logged in.
Relying on UUIDs or hidden ids as protection.
Accepting ownerId or role from the request body.
Putting the checks only in the UI.
Forgetting the same checks in GraphQL resolvers and background jobs.
Follow-ups
When do you return 403 and when 404?
How would you scope every database query to the current tenant?
How do you test authorization rules in CI?
Tips
Define IDOR with the URL example.
Say 'one policy function'.
Mention mass assignment.
164.nodejs-0164Easyfresher
What is GraphQL, how do a schema, queries, variables and resolvers work, and how does it differ from REST?
GraphQL is a query language and runtime for APIs. A typed schema describes the data, the client sends a query that names exactly the fields it wants, and the server runs a resolver function for each field. One endpoint serves many shapes of data, which avoids over-fetching and extra round trips, but moves complexity to the server (caching, N+1 queries, query cost, security).
Full answer
Core ideas
Schema (SDL): types, fields, arguments, Query (reads), Mutation (writes) and Subscription (live updates). Types are non-null or nullable (String!).
Query: the client selects fields. { student(id: 1) { name marks } } returns only name and marks, in that shape.
Variables: pass values separately from the query text (query ($id: ID!) { ... }), which is safer and cacheable.
Resolvers: functions (parent, args, context, info) that return the value of a field. If a field has no resolver, GraphQL reads the property with the same name from the parent object.
Errors: a response can contain data and errors together (partial results). A nullable field that fails becomes null and adds an error entry.
Introspection: clients can ask the schema about itself, which powers tools and code generation.
Compared with REST
One endpoint (POST /graphql) versus many resources. The client controls the shape of the response.
Fewer round trips for nested data, and no versioning by URL (fields are added and deprecated).
Harder: HTTP caching (everything is a POST by default), N+1 resolver queries (see DataLoader), unbounded query cost and file uploads. Errors return HTTP 200 in many servers.
REST is simpler for plain CRUD and public caching. GraphQL helps when many different clients need different data.
In Node: graphql-js is the reference implementation. Apollo Server, GraphQL Yoga and Mercurius add HTTP, tooling and plugins.
javascript
const { buildSchema, graphql } = require('graphql');
const schema = buildSchema(`
type Student { id: ID! name: String! marks: Int! grade: String! }
type Query {
student(id: ID!): Student
students(minMarks: Int = 0): [Student!]!
}
type Mutation { addStudent(name: String!, marks: Int!): Student! }
`);
const data = [{ id: '1', name: 'Asha', marks: 78 }, { id: '2', name: 'Ravi', marks: 64 }];
const withGrade = (s) => s && { ...s, grade: s.marks >= 75 ? 'A' : 'B' }; // a computed field
const rootValue = {
student: ({ id }) => withGrade(data.find((s) => s.id === id)),
students: ({ minMarks }) => data.filter((s) => s.marks >= minMarks).map(withGrade),
addStudent: ({ name, marks }) => { const s = { id: String(data.length + 1), name, marks }; data.push(s); return withGrade(s); },
};
const run = async (label, source, variableValues) => {
const result = await graphql({ schema, source, rootValue, variableValues });
console.log(label.padEnd(26), JSON.stringify(result));
};
(async () => {
await run('only name and grade', '{ student(id: "1") { name grade } }');
await run('variables + alias', 'query ($min: Int) { top: students(minMarks: $min) { name } }', { min: 70 });
await run('mutation', 'mutation { addStudent(name: "Meera", marks: 91) { id name grade } }');
await run('unknown id (nullable)', '{ student(id: "99") { name } }');
await run('unknown field', '{ student(id: "1") { email } }');
await run('missing required arg', '{ student { name } }');
})();
Queries, variables, an alias, a mutation, a missing record and two invalid queries run against an in-memory schema. Install first with npm install graphql (run here with graphql 16.15.0). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
only name and grade {"data":{"student":{"name":"Asha","grade":"A"}}}
variables + alias {"data":{"top":[{"name":"Asha"}]}}
mutation {"data":{"addStudent":{"id":"3","name":"Meera","grade":"A"}}}
unknown id (nullable) {"data":{"student":null}}
unknown field {"errors":[{"message":"Cannot query field \"email\" on type \"Student\".","locations":[{"line":1,"column":22}]}]}
missing required arg {"errors":[{"message":"Field \"student\" argument \"id\" of type \"ID!\" is required, but it was not provided.","locations":[{"line":1,"column":3}]}]}
Key points
The schema is typed and the client picks the fields.
A resolver runs for each field; default resolvers read properties.
Variables keep values out of the query text.
Responses can mix data and errors.
GraphQL reduces round trips but adds server-side complexity.
Common mistakes
Building queries by concatenating user input into the query string.
Treating GraphQL as always better than REST.
Returning HTTP 200 and ignoring the errors array on the client.
Exposing internal database errors in GraphQL errors.
Not thinking about N+1 resolver queries.
Follow-ups
What is the difference between a query and a mutation?
How do fragments and aliases work?
How do you cache GraphQL responses?
Tips
Describe the schema, query and resolver triple.
Compare with REST in two lines.
Mention N+1 as a known problem.
165.nodejs-0165Mediummid
How do you build an Apollo Server API in Node.js: typeDefs, resolvers, context for authentication, error codes and production settings?
Apollo Server takes typeDefs (the schema) and resolvers. The context function runs for each request and is the place to add the authenticated user and per-request helpers such as DataLoader instances. Throw GraphQLError with an extensions.code (UNAUTHENTICATED, FORBIDDEN, BAD_USER_INPUT) for expected errors, hide stack traces and internal messages in production, and turn off introspection and landing pages unless you need them.
Full answer
Pieces
new ApolloServer({ typeDefs, resolvers, ...options }). Use @apollo/server with startStandaloneServer for a quick start or expressMiddleware to mount it inside Express with cors and body parsing.
Resolvers receive (parent, args, contextValue, info). Keep them thin and call services.
Context: created per request. Typical content: the user from a verified token or session, a database handle, and new DataLoader instances (loaders must not be shared between requests, because their cache would leak data between users).
Errors
Throw new GraphQLError('message', { extensions: { code: 'UNAUTHENTICATED' } }) for errors that clients should handle. Validation failures get GRAPHQL_VALIDATION_FAILED automatically.
Unexpected errors become INTERNAL_SERVER_ERROR. Use formatError to hide internal messages and stack traces in production (includeStacktraceInErrorResponses: false), and log the original error with a request id.
Always check authorization in resolvers (or a shared wrapper). The schema alone does not protect fields.
Production settings
Introspection is disabled by default when NODE_ENV is production. Do not rely on that only. Set introspection explicitly for public APIs.
Limit query depth and cost, request size, and add persisted queries or an allowlist for private clients.
Keep the landing page and the sandbox off in production.
Plugins add logging, tracing and caching hints. executeOperation lets you test the server without HTTP.
javascript
const { ApolloServer } = require('@apollo/server');
const { GraphQLError } = require('graphql');
const typeDefs = `#graphql
type Query { me: String! secret: String! divide(a: Int!, b: Int!): Int! }
`;
const resolvers = {
Query: {
me: (parent, args, { user }) => user ?? 'anonymous',
secret: (parent, args, { user }) => {
if (!user) throw new GraphQLError('Please log in', { extensions: { code: 'UNAUTHENTICATED' } });
return 'the secret for ' + user;
},
divide: (parent, { a, b }) => {
if (b === 0) throw new GraphQLError('b must not be zero', { extensions: { code: 'BAD_USER_INPUT', argument: 'b' } });
if (a === 13) throw new Error('database password is hunter2'); // an unexpected error
return Math.floor(a / b);
},
},
};
const server = new ApolloServer({
typeDefs, resolvers,
includeStacktraceInErrorResponses: false,
introspection: false,
formatError: (formatted, error) => (formatted.extensions?.code === 'INTERNAL_SERVER_ERROR' ? { message: 'Internal error', extensions: { code: 'INTERNAL_SERVER_ERROR' } } : formatted),
});
async function run(label, query, user) {
const response = await server.executeOperation({ query }, { contextValue: { user } });
const { data, errors } = response.body.singleResult;
console.log(label.padEnd(24), JSON.stringify({ data, errors: errors?.map((e) => ({ message: e.message, code: e.extensions?.code })) }));
}
(async () => {
await run('anonymous me', '{ me }');
await run('secret, anonymous', '{ secret }');
await run('secret, logged in', '{ secret }', 'asha');
await run('expected error', '{ divide(a: 1, b: 0) }');
await run('unexpected error', '{ divide(a: 13, b: 1) }');
await run('validation error', '{ nothing }');
await run('introspection', '{ __schema { queryType { name } } }');
})();
executeOperation runs queries without HTTP. The unexpected error is hidden behind a generic message, and introspection is switched off. Install first with npm install @apollo/server graphql (run here with @apollo/server 5.5.4, graphql 16.15.0). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
anonymous me {"data":{"me":"anonymous"}}
secret, anonymous {"data":null,"errors":[{"message":"Please log in","code":"UNAUTHENTICATED"}]}
secret, logged in {"data":{"secret":"the secret for asha"}}
expected error {"data":null,"errors":[{"message":"b must not be zero","code":"BAD_USER_INPUT"}]}
unexpected error {"data":null,"errors":[{"message":"Internal error","code":"INTERNAL_SERVER_ERROR"}]}
validation error {"errors":[{"message":"Cannot query field \"nothing\" on type \"Query\".","code":"GRAPHQL_VALIDATION_FAILED"}]}
introspection {"errors":[{"message":"GraphQL introspection is not allowed by Apollo Server, but the query contained __schema or __type. To enable introspection, pass introspection: true to ApolloServer in production","code":"GRAPHQL_VALIDATION_FAILED"}]}
Key points
ApolloServer takes typeDefs and resolvers.
The context function adds the user and per-request loaders.
Throw GraphQLError with extensions.code for expected errors.
Hide stack traces and set introspection on purpose.
executeOperation tests without HTTP.
Common mistakes
Sharing a DataLoader or user object between requests.
Skipping authorization in resolvers because the route requires login.
Returning internal error messages and stack traces.
Leaving introspection and the sandbox open on a private API.
Throwing plain strings instead of errors with codes.
Follow-ups
How do you mount Apollo Server inside an Express app?
What does formatError receive?
How would you add query depth limiting?
Tips
List typeDefs, resolvers, context.
Say 'per-request context'.
Mention production settings.
166.nodejs-0166Hardsenior
What is the N+1 problem in GraphQL resolvers, and how does DataLoader fix it with batching and per-request caching?
A list field with 50 items whose author resolver runs one query each causes 1 + 50 database queries. DataLoader collects all load(key) calls made in the same tick of the event loop, calls one batch function with all keys (one query with WHERE id IN (...)), and caches results by key for the rest of the request. Create loaders per request, and make the batch function return values in the same order and number as the keys.
Full answer
The problem
Query: posts { title author { name } }. The posts resolver runs 1 query for N posts. The author resolver then runs for every post, N more queries. With 100 posts that is 101 queries, which hurts latency and the database.
Resolvers call loader.load(post.authorId). DataLoader waits until the current tick ends, gathers all keys, deduplicates them, calls the batch function once, and gives each caller its own result.
Caching: the loader remembers values per key, so the same author is loaded once per request.
Rules
Create loaders in the context function for each request. A global loader would cache data across users and across time (stale and a privacy leak).
The batch function must return an array with the same length and order as the keys. Missing rows need null or an Error at that position. Mismatched ordering is the classic bug.
Use it for any one-to-one or one-to-many relation (loaders keyed by foreign key for lists).
It batches within one tick. Work that is separated by awaits of other work may not batch.
Clear or prime the cache after mutations if the same request reads the data again.
Other fixes: joins and select-ahead in the parent query (look at info to see requested fields), and in REST the same idea is called eager loading.
Check the effect: log the number of queries per request and test it, because N+1 comes back quietly.
javascript
const { buildSchema, graphql } = require('graphql');
const DataLoader = require('dataloader');
// A fake database that counts queries.
let queries = [];
const users = [{ id: 1, name: 'Asha' }, { id: 2, name: 'Ravi' }, { id: 3, name: 'Meera' }];
const posts = Array.from({ length: 6 }, (_, i) => ({ id: i + 1, title: 'Post ' + (i + 1), authorId: (i % 3) + 1 }));
const db = {
allPosts: async () => { queries.push('SELECT * FROM posts'); return posts; },
userById: async (id) => { queries.push(`SELECT * FROM users WHERE id = ${id}`); return users.find((u) => u.id === id); },
usersByIds: async (ids) => { queries.push(`SELECT * FROM users WHERE id IN (${ids.join(', ')})`); return users.filter((u) => ids.includes(u.id)); },
};
const schema = buildSchema(`
type User { name: String! }
type Post { title: String! author: User }
type Query { posts: [Post!]! }
`);
const query = '{ posts { title author { name } } }';
const naive = { posts: () => db.allPosts().then((list) => list.map((p) => ({ ...p, author: () => db.userById(p.authorId) }))) };
const batched = { posts: (args, context) => db.allPosts().then((list) => list.map((p) => ({ ...p, author: () => context.userLoader.load(p.authorId) }))) };
const makeContext = () => ({
userLoader: new DataLoader(async (ids) => {
const rows = await db.usersByIds(ids);
return ids.map((id) => rows.find((u) => u.id === id) ?? null); // same order and length as ids
}),
});
(async () => {
queries = [];
const a = await graphql({ schema, source: query, rootValue: naive });
console.log('naive resolvers :', queries.length, 'queries for', a.data.posts.length, 'posts');
queries = [];
const b = await graphql({ schema, source: query, rootValue: batched, contextValue: makeContext() });
console.log('with DataLoader :', queries.length, 'queries:', JSON.stringify(queries));
console.log('same result :', JSON.stringify(a.data) === JSON.stringify(b.data));
// Caching inside one request, and the batch order rule
queries = [];
const loader = makeContext().userLoader;
const [x, y, z] = await Promise.all([loader.load(2), loader.load(1), loader.load(2)]);
console.log('keys 2,1,2 ->', [x, y, z].map((u) => u.name).join(','), '| batch calls:', queries.length, '|', queries[0]);
await loader.load(1);
console.log('load(1) again hits the cache, batch calls still:', queries.length);
console.log('a missing key gives null, not a shifted result:', await loader.load(99));
})();
Six posts are resolved with one query each for the author, and then with DataLoader. The last lines show deduplication, the cache and a missing key. Install first with npm install graphql dataloader (run here with graphql 16.15.0, dataloader 2.2.3). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
naive resolvers : 7 queries for 6 posts
with DataLoader : 2 queries: ["SELECT * FROM posts","SELECT * FROM users WHERE id IN (1, 2, 3)"]
same result : true
keys 2,1,2 -> Ravi,Asha,Ravi | batch calls: 1 | SELECT * FROM users WHERE id IN (2, 1)
load(1) again hits the cache, batch calls still: 1
a missing key gives null, not a shifted result: null
Key points
N+1 means one query for the list plus one per item.
DataLoader batches keys from one tick into a single call.
It caches by key within the request.
Create loaders per request, never globally.
The batch function must keep key order and length.
Common mistakes
Creating one global DataLoader.
A batch function that returns rows in database order instead of key order.
Calling await inside a loop of resolvers so keys never batch.
Forgetting that the cache lives for the whole request.
Not measuring the query count in tests.
Follow-ups
How do you batch a one-to-many relation?
What does the DataLoader cache do after a mutation?
How can the parent query use joins instead?
Tips
Show the 1 + N arithmetic.
Say 'same tick, one batch, per request'.
Mention the order rule.
167.nodejs-0167Mediummid
How do you protect a GraphQL API from abusive queries: depth limits, cost limits, disabled introspection and input checks?
GraphQL lets clients write very expensive queries, such as deeply nested relations. Defend with validation rules that run before execution: a maximum depth, a cost or complexity estimate, a limit on aliases and list sizes, and a request size limit. Turn off introspection for private APIs, authorise in every resolver, use persisted queries or an allowlist for known clients, and apply rate limits by cost rather than by request count.
Full answer
Why GraphQL needs this
One request can ask for a very large result: { users { friends { friends { friends { name } } } } } grows exponentially. Aliases let a client repeat an expensive field 100 times in one request. Rate limiting by request count does not see this.
Controls
Depth limit: reject queries deeper than N (often 6 to 10) using a validation rule. Cheap and effective for cyclic schemas.
Complexity or cost analysis: give each field a cost (more for lists, multiplied by first or limit arguments), reject queries above a budget, and use the cost for rate limits.
Pagination limits: require first or limit on lists, with a maximum (for example 100). Never return unbounded lists.
Alias and directive limits to stop batching abuse and brute force (for example 1000 login attempts in aliases of one mutation).
Size limits: maximum body size and query length. Timeouts for resolvers and for the whole operation.
Persisted queries: the server knows only a list of approved query ids (or hashes). It removes arbitrary queries from private clients and speeds up requests.
Introspection off in production for private APIs, because it maps the whole schema for an attacker. It is not security by itself.
Authorization in every resolver (and for subscriptions) and input validation for arguments.
Do not return detailed errors or stack traces. Log with request ids.
Implementation in Node
graphql-js: validate(schema, documentAST, [...specifiedRules, myRule]) runs rules before execute. Libraries: graphql-depth-limit, graphql-armor (a bundle of protections), graphql-query-complexity.
NoSchemaIntrospectionCustomRule from graphql disables introspection queries.
javascript
const { buildSchema, parse, validate, specifiedRules, NoSchemaIntrospectionCustomRule, GraphQLError, Kind } = require('graphql');
const schema = buildSchema(`
type User { name: String! friends: [User!]! }
type Query { user: User }
`);
// A validation rule that measures the deepest selection path.
function maxDepth(limit) {
return (context) => ({
Document: {
enter(document) {
const depthOf = (selectionSet, depth) => Math.max(depth, ...(selectionSet?.selections ?? []).map((s) => (s.kind === Kind.FIELD ? depthOf(s.selectionSet, depth + 1) : depth)));
for (const definition of document.definitions) {
if (definition.kind === Kind.OPERATION_DEFINITION) {
const depth = depthOf(definition.selectionSet, 0);
if (depth > limit) context.reportError(new GraphQLError(`Query depth ${depth} is above the limit of ${limit}`));
}
}
},
},
});
}
// A very simple alias counter: repeating one field many times under different names.
function maxAliases(limit) {
return (context) => {
let count = 0;
return {
Field(node) { if (node.alias && ++count === limit + 1) context.reportError(new GraphQLError(`More than ${limit} aliases`)); },
};
};
}
const rules = [...specifiedRules, maxDepth(4), maxAliases(3), NoSchemaIntrospectionCustomRule];
const check = (label, source) => {
const errors = validate(schema, parse(source), rules);
console.log(label.padEnd(18), errors.length ? 'rejected: ' + errors[0].message : 'accepted');
};
check('shallow query', '{ user { name friends { name } } }');
check('deep query', '{ user { friends { friends { friends { friends { name } } } } } }');
check('alias abuse', '{ a: user { name } b: user { name } c: user { name } d: user { name } }');
check('introspection', '{ __schema { types { name } } }');
Three validation rules reject a deep query, an alias flood and an introspection query before any resolver runs. A shallow query passes. Install first with npm install graphql (run here with graphql 16.15.0). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
shallow query accepted
deep query rejected: Query depth 6 is above the limit of 4
alias abuse rejected: More than 3 aliases
introspection rejected: GraphQL introspection has been disabled, but the requested query contained the field "__schema".
Key points
Clients control query shape, so cost must be limited.
Depth and cost limits run as validation rules before execution.
Limit list sizes, aliases and request size.
Disable introspection and use persisted queries for private APIs.
Authorise in every resolver.
Common mistakes
Rate limiting only by request count.
Returning unbounded lists.
Relying on hidden introspection as the only protection.
Checking depth only for fields and forgetting fragments.
No timeout on resolvers.
Follow-ups
How does persisted queries support security?
How do you estimate the cost of a list field?
Why do aliases matter for brute-force attacks?
Tips
Start with the exponential query example.
List depth, cost, size, introspection.
Say 'validation runs before execution'.
168.nodejs-0168Mediummid
What is gRPC, and how do you build a service in Node.js with a .proto file, a unary call and a server streaming call?
gRPC is an RPC framework that uses HTTP/2 and Protocol Buffers. You describe services and messages in a .proto file, load it in Node with @grpc/proto-loader and @grpc/grpc-js, implement handlers on the server and call generated client methods. It supports unary calls, server streaming, client streaming and bidirectional streaming, and it is compact and fast, which suits service to service traffic.
Full answer
Why gRPC
Contract first: the .proto file defines services, methods and typed messages. Clients and servers in different languages stay in sync, and code generation or dynamic loading removes manual parsing.
Protocol Buffers are a binary format, smaller and faster than JSON. Field numbers (not names) go on the wire, so you may add fields but must not reuse or change numbers.
HTTP/2 gives multiplexing and streaming over one connection.
Call types
Unary: one request, one response (like a normal function call).
Server streaming: one request, many responses (live updates, large result sets).
Client streaming: many requests, one response (uploads).
Bidirectional streaming: both sides stream independently (chat).
In Node
@grpc/proto-loader reads the .proto at run time (loadSync) and @grpc/grpc-js gives the server and client. Static code generation (grpc-tools, ts-proto, protobuf-ts) adds type safety.
Server: server.addService(definition, { Method: (call, callback) => ... }). For unary calls use callback(null, response). For server streaming use call.write(message) and call.end().
Client: new Service(address, credentials). Unary methods take (request, callback). Streams are Node Readable objects.
Use TLS credentials in production (createSsl), and a deadline on every call.
When not to use it: public browser APIs (browsers need grpc-web or a proxy), and simple CRUD where REST is enough.
The proto file is written to a temporary folder, a server and client run in one process on a free port, and both a unary and a streaming call are made. Install first with npm install @grpc/grpc-js @grpc/proto-loader (run here with @grpc/grpc-js 1.14.7, @grpc/proto-loader 0.8.1). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
unary response: {"id":7,"name":"Asha"}
streamed marks: maths=91, physics=78, english=85
Key points
The .proto file is the contract: services and typed messages.
Protocol Buffers over HTTP/2 are compact and support streaming.
Four call types: unary, server, client and bidirectional streaming.
grpc-js plus proto-loader is the usual Node setup.
Never change or reuse field numbers.
Common mistakes
Reusing or renumbering field numbers.
No deadline on client calls.
Exposing gRPC directly to browsers without grpc-web or a proxy.
Using insecure credentials outside local development.
Putting very large payloads in one message.
Follow-ups
How do deadlines and metadata work in gRPC?
What is the difference between proto2 and proto3?
How do you do load balancing with gRPC and HTTP/2?
Tips
Say 'contract first with protobuf'.
List the four call types.
Mention deadlines.
169.nodejs-0169Hardsenior
How do you handle errors, deadlines, metadata and interceptors in gRPC with Node.js?
gRPC errors are status codes (NOT_FOUND, INVALID_ARGUMENT, DEADLINE_EXCEEDED, UNAUTHENTICATED, UNAVAILABLE and others), not HTTP codes. The client sets a deadline on every call, and the server should stop work when the deadline passes or the call is cancelled. Metadata carries headers such as authorization and request ids. Interceptors on the client or server add cross-cutting behaviour like auth, logging and retries for transient codes.
Full answer
Status codes
Server handlers return errors with callback({ code: grpc.status.NOT_FOUND, message: '...' }).
Retry only idempotent calls and only transient codes such as UNAVAILABLE (and sometimes DEADLINE_EXCEEDED or ABORTED, if the operation is safe). Use exponential backoff with jitter.
Deadlines
The client passes { deadline: Date.now() + 500 } in call options. When it expires the client call fails with DEADLINE_EXCEEDED, and the server call is cancelled.
No deadline means the call may wait forever. Set one on every call, and let each hop pass a shorter deadline on to its own downstream calls.
On the server, watch call.cancelled or the 'cancelled' event and stop expensive work.
Metadata
Key-value pairs sent with a call (headers) and returned (headers and trailers). The client builds new grpc.Metadata() and calls set('authorization', 'Bearer ...'). The server reads call.metadata.get('authorization').
Use it for tokens, request ids and tracing. Binary values use keys that end in -bin.
Interceptors
Client interceptors wrap outgoing calls to add metadata, log latency or retry. Server interceptors (supported in grpc-js through a wrapper or the server interceptors option in newer versions) check authentication and log.
Keep one place for authentication so no handler forgets it.
Operations: use TLS, health checking service (grpc.health.v1), reflection for debugging tools, and keepalive settings behind load balancers.
A client interceptor adds the token. The calls return OK and four different status codes, and the slow call fails with DEADLINE_EXCEEDED only when a deadline is set. Install first with npm install @grpc/grpc-js @grpc/proto-loader (run here with @grpc/grpc-js 1.14.7, @grpc/proto-loader 0.8.1). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
normal call : OK "Hello Asha"
empty name : INVALID_ARGUMENT (name is required)
unknown person : NOT_FOUND (no such person)
wrong token : UNAUTHENTICATED (bad token)
deadline of 100 ms : DEADLINE_EXCEEDED
no deadline : OK "finally"
Key points
Errors are gRPC status codes, not HTTP codes.
Set a deadline on every call and propagate a shorter one downstream.
Metadata carries tokens and request ids.
Interceptors centralise auth, logging and retries.
Retry only idempotent calls on transient codes.
Common mistakes
Making calls with no deadline.
Returning INTERNAL for every error.
Retrying non-idempotent calls on DEADLINE_EXCEEDED.
Sending tokens without TLS.
Not stopping server work after the client cancelled.
Follow-ups
How do you pass a deadline from one service to the next?
What does the health checking protocol do?
How do you test a gRPC service?
Tips
Name five status codes.
Say 'deadline on every call'.
Mention interceptors for auth.
170.nodejs-0170Mediummid
What are the trade-offs between an ORM (Sequelize, Prisma), a query builder and raw SQL in Node.js?
An ORM maps tables to objects and generates SQL, which speeds up simple CRUD, migrations and validation, and gives type help (Prisma generates a typed client). The costs are hidden queries (N+1), awkward complex queries, and a learning curve for the abstraction. A query builder (Knex, Kysely) stays close to SQL with composition and types. Raw SQL gives full control and the best performance for hard queries. Many teams mix them.
Full answer
Options
ORM: Sequelize (model classes, associations, hooks, migrations), TypeORM, MikroORM, Prisma (schema file, generated typed client, its own migration tool). Good for CRUD, relations, validation and consistent access.
Query builder: Knex, Kysely (very strong TypeScript types), Drizzle (a thin typed layer close to SQL). You write queries as code, the library builds the SQL.
Raw SQL with pg or postgres.js: full power (window functions, CTEs, bulk operations), no abstraction, manual mapping and typing.
Trade-offs to discuss
Productivity: ORMs win for the first 80 percent of queries. Migrations, validation and relations come built in.
Control and performance: reports, analytics and bulk updates are easier in SQL. ORMs may select too many columns or run many small queries.
Hidden cost: lazy loading in loops causes N+1. Always inspect the SQL that the ORM produces (logging) and use eager loading (include in Sequelize, include or select in Prisma).
Type safety: Prisma and Kysely give strong types, Sequelize needs manual typing.
Portability: ORMs hide small dialect differences, but you rarely switch databases, and you lose database specific features unless you use raw queries.
Team skills and testing: SQL skills stay valuable, and ORMs are easiest when the team still understands SQL.
Prisma notes (not run in this item): the schema.prisma file defines models, prisma generate creates the client, and prisma migrate manages migrations. Recent versions use a driver adapter and a TypeScript query engine.
A sensible default: an ORM or typed query builder for everyday queries, raw SQL for the few complex ones, parameters always, SQL logging in development, and an index review.
javascript
const { Sequelize, DataTypes, Op, QueryTypes } = require('sequelize');
(async () => {
const sqlLog = [];
const sequelize = new Sequelize({
dialect: 'postgres', host: process.env.PGHOST, port: Number(process.env.PGPORT), username: process.env.PGUSER, database: process.env.PGDATABASE,
logging: (sql) => sqlLog.push(sql.replace(/^Executing \(default\): /, '')),
});
const Student = sequelize.define('OrmStudent', {
name: { type: DataTypes.STRING, allowNull: false },
marks: { type: DataTypes.INTEGER, validate: { min: 0, max: 100 } },
}, { tableName: 'orm_students', timestamps: false });
await Student.sync({ force: true });
await Student.bulkCreate([{ name: 'Asha', marks: 78 }, { name: 'Ravi', marks: 64 }, { name: 'Meera', marks: 91 }]);
sqlLog.length = 0;
// 1. The ORM way
const top = await Student.findAll({ where: { marks: { [Op.gte]: 75 } }, order: [['marks', 'DESC']], attributes: ['name', 'marks'] });
console.log('ORM result :', top.map((s) => `${s.name}:${s.marks}`).join(', '));
console.log('ORM SQL :', sqlLog.at(-1));
// 2. Validation happens in the ORM before SQL is sent
try { await Student.create({ name: 'Zoya', marks: 150 }); } catch (err) { console.log('validation :', err.name, '-', err.errors[0].message); }
// 3. Raw SQL for something the model API does not express well, still parameterised
const [stats] = await sequelize.query('SELECT count(*)::int AS n, round(avg(marks), 1)::float AS average FROM orm_students WHERE marks >= :min', { replacements: { min: 60 }, type: QueryTypes.SELECT });
console.log('raw SQL :', JSON.stringify(stats));
await sequelize.query('DROP TABLE orm_students');
await sequelize.close();
})();
Sequelize runs against a local PostgreSQL server. The script prints the SQL that the ORM generated, the validation error, and a raw query. Prisma is described in the text only and was not run here. Install first with npm install sequelize pg (run here with sequelize 6.37.8, pg 8.23.1). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
ORM result : Meera:91, Asha:78
ORM SQL : SELECT "name", "marks" FROM "orm_students" AS "OrmStudent" WHERE "OrmStudent"."marks" >= 75 ORDER BY "OrmStudent"."marks" DESC;
validation : SequelizeValidationError - Validation max on marks failed
raw SQL : {"n":3,"average":77.7}
Key points
ORMs speed up CRUD and migrations but can hide inefficient queries.
Query builders stay close to SQL with composition and types.
Raw SQL gives full control for complex or bulk queries.
Always log and review the generated SQL.
Mixing approaches is normal.
Common mistakes
Never looking at the SQL the ORM generates.
Using lazy loading inside loops.
Building raw SQL with string concatenation.
Avoiding SQL entirely and writing slow ORM code for reports.
Choosing a tool only because it is popular.
Follow-ups
How do you see the SQL that Prisma or Sequelize runs?
When would you pick Kysely or Drizzle?
How do migrations differ between the tools?
Tips
Name the three options and one strength of each.
Say 'N+1' as the main ORM risk.
Give a balanced recommendation.
171.nodejs-0171Hardsenior
What are the common ORM pitfalls in Node.js (N+1 queries, over-fetching, row-by-row writes, transactions), and how do you check for them?
ORMs make it easy to write code that runs many hidden queries. Loading a relation inside a loop causes N+1 queries (use eager loading with include or a join), selecting every column wastes bandwidth (select needed attributes), inserting rows one by one is slow (use bulk inserts), and a multi-step change needs a transaction so that a failure rolls everything back. Turn on SQL logging and count queries in tests.
Full answer
Pitfalls and fixes
N+1 queries
teachers.findAll() then teacher.getStudents() for each teacher runs 1 + N queries. Fix with eager loading (include in Sequelize, include in Prisma) which uses a join or one extra IN query, or with a DataLoader in GraphQL.
Over-fetching
By default models select every column, including large text or JSON fields. Select what you need (attributes in Sequelize, select in Prisma). Return DTOs, not models.
Row by row writes
A loop with create() makes N round trips. Use bulkCreate, createMany or a single INSERT with many rows. For updates, use one UPDATE with a WHERE clause instead of loading, changing and saving each row.
Missing transactions
A business operation with several writes (create order, reduce stock) must run in a transaction. Sequelize managed transactions (sequelize.transaction(async (t) => ...)) commit when the callback resolves and roll back when it throws. Pass the transaction to every query inside.
Keep transactions short. Do not call slow external services inside one.
Lost updates and races
Read, change, save can overwrite another writer. Use atomic updates (increment), optimistic locking (version column) or SELECT ... FOR UPDATE.
Pagination and counts
Offset pagination on big tables and count queries on every request are slow. Use keyset pagination where possible.
Migrations and schema drift
Do not use sync({ force: true }) or auto sync in production. Use versioned migrations.
How to check: enable query logging in development, count queries per request in tests (fail a test if a route runs more than expected), use EXPLAIN on slow queries, and add indexes for foreign keys and filter columns.
javascript
const { Sequelize, DataTypes } = require('sequelize');
(async () => {
let log = [];
const sequelize = new Sequelize({
dialect: 'postgres', host: process.env.PGHOST, port: Number(process.env.PGPORT), username: process.env.PGUSER, database: process.env.PGDATABASE,
logging: (sql) => log.push(sql.replace(/^Executing \(default\): /, '')),
});
const Teacher = sequelize.define('Teacher', { name: DataTypes.STRING }, { tableName: 'orm2_teachers', timestamps: false });
const Student = sequelize.define('Student', { name: DataTypes.STRING, notes: DataTypes.TEXT }, { tableName: 'orm2_students', timestamps: false });
Teacher.hasMany(Student);
Student.belongsTo(Teacher);
await sequelize.sync({ force: true });
const teachers = await Teacher.bulkCreate([{ name: 'T1' }, { name: 'T2' }, { name: 'T3' }]);
await Student.bulkCreate(teachers.flatMap((t, i) => [{ name: `S${i}a`, TeacherId: t.id }, { name: `S${i}b`, TeacherId: t.id }]));
const count = () => log.filter((q) => /^(SELECT|INSERT|UPDATE)/.test(q)).length;
// 1. N+1
log = [];
for (const t of await Teacher.findAll()) await t.getStudents();
console.log('1. lazy loading in a loop :', count(), 'queries for 3 teachers');
log = [];
await Teacher.findAll({ include: Student });
console.log(' eager loading with include :', count(), 'query');
// 2. Over-fetching
log = [];
await Student.findAll({ attributes: ['id', 'name'] });
console.log('2. selected columns :', log[0].match(/SELECT (.*) FROM/)[1]);
// 3. Row by row writes versus a bulk insert
log = [];
for (let i = 0; i < 5; i++) await Student.create({ name: 'loop' + i });
const loopQueries = count();
log = [];
await Student.bulkCreate(Array.from({ length: 5 }, (_, i) => ({ name: 'bulk' + i })));
console.log('3. five creates in a loop :', loopQueries, 'queries | bulkCreate:', count(), 'query');
// 4. A managed transaction rolls back everything when the callback throws
const before = await Student.count();
try {
await sequelize.transaction(async (transaction) => {
await Student.create({ name: 'in-transaction' }, { transaction });
throw new Error('stock check failed');
});
} catch (err) { console.log('4. transaction failed :', err.message); }
console.log(' rows before and after :', before, await Student.count());
await sequelize.query('DROP TABLE orm2_students; DROP TABLE orm2_teachers;');
await sequelize.close();
})();
Sequelize runs against a local PostgreSQL server, and the script counts the queries that each approach sends. Install first with npm install sequelize pg (run here with sequelize 6.37.8, pg 8.23.1). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
1. lazy loading in a loop : 4 queries for 3 teachers
eager loading with include : 1 query
2. selected columns : "id", "name"
3. five creates in a loop : 5 queries | bulkCreate: 1 query
4. transaction failed : stock check failed
rows before and after : 16 16
Key points
Eager loading replaces N+1 queries.
Select only the columns you need.
Use bulk operations for many writes.
Wrap multi-step changes in a transaction and pass it to every query.
Log and count queries in tests.
Common mistakes
Calling a relation getter inside a loop.
Looping over create() for imports.
Doing the steps of one business action without a transaction.
Using sync({ force: true }) outside tests.
Returning whole models, including private columns, from the API.
Follow-ups
How would you find N+1 queries in a running service?
What is optimistic locking?
When is SELECT FOR UPDATE the right tool?
Tips
Open with the N+1 arithmetic.
Name eager loading, bulk writes and transactions.
Say 'count the queries in tests'.
172.nodejs-0172Easyfresher
How do Mongoose schemas handle types, validation, defaults, virtuals and hooks, and what happens when you query without a connection?
Mongoose adds a schema layer to MongoDB: typed fields, casting, defaults, validators, virtual fields, middleware hooks and a model class. Validation runs on save (and with validate()) in Node before data reaches the database. Unknown fields are dropped in strict mode. Queries are buffered until a connection exists, so a missing connection looks like a hang until bufferTimeoutMS triggers an error.
Full answer
Why Mongoose
MongoDB stores flexible documents. An application still needs rules: required fields, allowed ranges, defaults and the same shape for every writer. Mongoose provides those rules in Node (an ODM, object document mapper).
Schema features
Types and casting: a String of '78' sent to a Number field is cast to 78. A value that cannot be cast (abc) fails with a CastError.
Validation: required, min, max, enum, match, minLength, custom validate functions. doc.validate() rejects with a ValidationError with details per path. Validation also runs automatically on save().
Defaults: default: Date.now or a value.
strict mode (default): fields not in the schema are not saved.
Virtuals: computed properties (fullName) that are not stored. Include them in JSON with toJSON({ virtuals: true }).
Middleware (hooks): pre and post for validate, save, find and others. Typical use: hashing a password, updating timestamps. In pre hooks call next() or return a promise.
Options: timestamps: true adds createdAt and updatedAt. Indexes are declared in the schema (autoIndex is usually off in production, build indexes in migrations).
Operational notes
Connection: await mongoose.connect(uri). Commands issued before the connection is ready are buffered. If the connection never opens, they wait (default 10 seconds) and then fail with a buffering timeout error. Handle connection errors and events.
lean() returns plain objects, which is faster and uses less memory for read-only queries.
Mongoose validation does not replace database-level rules (unique indexes are created in MongoDB, not checked by Mongoose validators).
Use populate carefully, because it runs extra queries (a form of N+1).
javascript
const mongoose = require('mongoose');
mongoose.set('bufferTimeoutMS', 100); // fail fast in this demo
const studentSchema = new mongoose.Schema({
name: { type: String, required: [true, 'name is required'], trim: true },
marks: { type: Number, min: [0, 'marks cannot be negative'], max: [100, 'marks cannot be above 100'], default: 0 },
track: { type: String, enum: ['web', 'data'], default: 'web' },
firstName: String,
lastName: String,
}, { timestamps: false });
studentSchema.virtual('fullName').get(function () { return `${this.firstName} ${this.lastName}`; });
studentSchema.pre('validate', function () { this.name = this.name && this.name.replace(/\s+/g, ' '); }); // a hook that tidies input
const Student = mongoose.model('Student', studentSchema);
(async () => {
const ok = new Student({ name: ' Asha Rao ', marks: '78', firstName: 'Asha', lastName: 'Rao', hobby: 'chess' });
await ok.validate();
console.log('cast and trim :', JSON.stringify({ name: ok.name, marks: ok.marks, type: typeof ok.marks, track: ok.track }));
console.log('unknown field :', ok.get('hobby') === undefined ? 'dropped (strict mode)' : 'kept');
console.log('virtual :', JSON.stringify(ok.toJSON({ virtuals: true }).fullName));
const bad = new Student({ marks: 150, track: 'art' });
const error = await bad.validate().catch((e) => e);
console.log('validation :', error.name, '->', Object.entries(error.errors).sort(([a], [b]) => a.localeCompare(b)).map(([path, e]) => `${path}: ${e.message}`).join(' | '));
const notANumber = new Student({ name: 'Ravi', marks: 'abc' });
console.log('cast error :', (await notANumber.validate().catch((e) => e)).errors.marks.name);
// No connection was opened, so the query waits and then fails.
await Student.findOne({ name: 'Asha' }).catch((err) => console.log('no connection :', err.name + ':', err.message));
})();
Everything here runs without a MongoDB server. The query at the end shows what happens when no connection exists, and queries that need a real server were not run. Install first with npm install mongoose (run here with mongoose 9.13.2). Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
cast and trim : {"name":"Asha Rao","marks":78,"type":"number","track":"web"}
unknown field : dropped (strict mode)
virtual : "Asha Rao"
validation : ValidationError -> marks: marks cannot be above 100 | name: name is required | track: `art` is not a valid enum value for path `track`.
cast error : CastError
no connection : MongooseError: Operation `students.findOne()` buffering timed out after 100ms
Key points
A Mongoose schema defines types, casting, defaults and validators.
Validation runs in Node before data is sent.
Strict mode drops unknown fields.
Virtuals are computed fields; hooks run around save and validate.
Without a connection, queries are buffered and then time out.
Not handling connection errors and seeing queries hang.
Using populate in loops without thinking about the extra queries.
Letting the schema grow with no versioning of old documents.
Auto-building indexes in production on startup.
Follow-ups
What does lean() change?
How do you add an index and a unique constraint?
How do pre and post hooks differ?
Tips
Say 'schema layer on top of flexible documents'.
Name casting, validation, virtuals, hooks.
Mention buffering.
173.nodejs-0173Mediummid
How do you model data in MongoDB: when do you embed documents, when do you reference them, and what are the document size limits?
Embed data that is read together with its parent, is bounded in size and has the same lifecycle (an address, order line items). Reference data that is large or unbounded, shared by many parents, or changed often on its own (comments on a popular post). A document cannot exceed 16 MiB, so never embed an array that grows without limit. Design the model around your queries, then add indexes that match them.
Full answer
MongoDB modeling starts from access patterns, not from entities.
Embed when
The child is almost always read with the parent (order and its line items).
The child set is small and bounded (a user with 3 addresses).
The child has no independent life and is updated together with the parent. One read, one atomic write for the whole document.
Reference when
The child set is large or unbounded (comments, log events). The 16 MiB document limit and the cost of rewriting a huge document make embedding unsafe.
Many parents share the child (a course shared by many students), or the child changes often by itself.
You need to query the child alone.
Referencing costs a second query or a $lookup, and consistency across documents needs care (transactions exist but are slower).
Patterns
Hybrid: embed a summary and reference the full data (the latest 3 comments inside the post, all comments in their own collection).
Bucketing: group time series data per hour or day to reduce the document count.
Denormalise on purpose: copy a name or title to avoid joins, and update copies when they change.
Computed fields: store counters (commentCount) instead of counting each time.
Indexes
Index fields used in filters and sorts. A compound index follows the ESR rule: equality fields first, then sort fields, then range fields.
Every index slows writes and uses memory. Review with explain().
Avoid unbounded arrays inside indexed fields (multikey index growth).
Mongoose note: populate() is a client-side join, which runs extra queries.
javascript
// A small simulation: how many reads does each model need, and how big does an embedded array get?
const posts = [{ id: 1, title: 'Intro to Node', author: 'Asha' }];
const comments = Array.from({ length: 1000 }, (_, i) => ({ postId: 1, user: 'user' + i, text: 'A typical comment with some words in it, number ' + i }));
let reads = 0;
const collections = {
postsEmbedded: [{ ...posts[0], comments }],
posts,
comments,
};
const find = (name, predicate) => { reads++; return collections[name].filter(predicate); };
// Model A: comments embedded in the post. One read.
reads = 0;
const [embedded] = find('postsEmbedded', (p) => p.id === 1);
console.log('embedded model : reads =', reads, '| comments loaded =', embedded.comments.length);
// Model B: comments in their own collection, with a limit as a real query would have.
reads = 0;
const [post] = find('posts', (p) => p.id === 1);
const firstTen = find('comments', (c) => c.postId === post.id).slice(0, 10);
console.log('referenced model : reads =', reads, '| comments loaded =', firstTen.length, '(paged)');
// The size of a growing embedded array, compared with the 16 MiB limit (JSON size is only an approximation of BSON size).
const LIMIT = 16 * 1024 * 1024;
const bytesPerComment = Buffer.byteLength(JSON.stringify(comments[0]));
console.log('one comment is about', bytesPerComment, 'bytes');
console.log('the 16 MiB limit is reached after about', Math.round(LIMIT / bytesPerComment / 1000) * 1000, 'comments');
console.log('rewriting a document with 1000 comments moves about', Math.round(Buffer.byteLength(JSON.stringify(embedded)) / 1024), 'KiB per update of the post');
// Hybrid: keep a bounded preview inside the post and the rest in the comments collection.
const hybrid = { ...posts[0], commentCount: comments.length, latestComments: comments.slice(-3) };
console.log('hybrid document :', Buffer.byteLength(JSON.stringify(hybrid)), 'bytes with a counter and 3 comments');
This is a teaching simulation with plain arrays, not a MongoDB test (no server was used). The sizes are JSON approximations of document size. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
embedded model : reads = 1 | comments loaded = 1000
referenced model : reads = 2 | comments loaded = 10 (paged)
one comment is about 86 bytes
the 16 MiB limit is reached after about 195000 comments
rewriting a document with 1000 comments moves about 89 KiB per update of the post
hybrid document : 360 bytes with a counter and 3 comments
Key points
Model around access patterns.
Embed bounded data that is read with its parent.
Reference large, unbounded or shared data.
A document is limited to 16 MiB, so avoid unbounded arrays.
Compound indexes follow equality, sort, range.
Common mistakes
Embedding an array that grows forever.
Normalising everything like a relational database and then needing many lookups.
Copying data everywhere and never updating the copies.
Creating indexes for every field.
Designing the model before knowing the queries.
Follow-ups
What is the ESR rule for compound indexes?
How does the bucket pattern help time series data?
When do you use a multi-document transaction in MongoDB?
Tips
Start with 'access patterns'.
Give one example of each choice.
Mention the 16 MiB limit.
174.nodejs-0174Easyfresher
How does a Node.js AWS Lambda handler work, what is a cold start, and what should run in init code versus in the handler?
A Lambda function exports a handler (event, context). The platform starts an execution environment on demand: it loads your module (the init phase, a cold start) and then calls the handler. The environment is reused for later invocations (warm), so code outside the handler runs once per environment and is the place for clients and configuration, while per-request work stays inside the handler. Cold starts grow with bundle size, heavy imports and init work.
Full answer
Handler basics
export const handler = async (event, context) => { ... return result }. The event shape depends on the trigger. For API Gateway or a function URL, event has httpMethod or requestContext, headers, body (a string, base64 encoded when isBase64Encoded is true) and the response needs statusCode, headers and body.
context gives awsRequestId, functionName and getRemainingTimeInMillis().
Async handlers return a value or throw. Throwing makes the invocation fail with errorType and errorMessage (and the platform may retry, depending on the trigger).
The older callback style exists. With callbacks, context.callbackWaitsForEmptyEventLoop decides whether Lambda waits for pending work. Prefer async functions.
Lifecycle
Init phase (cold start): download the code, start the runtime, run top-level module code. It happens once for a new execution environment.
Invoke phase: the handler runs. After it returns the environment is frozen, and may be reused for a later event (warm start) or discarded.
Concurrency: one environment handles one request at a time. A spike creates more environments, each with a cold start.
What belongs where
Outside the handler (once): SDK and database clients, config loading, compiled regular expressions, caches.
Inside the handler (each time): reading the event, per-request state, business logic. Never keep user data in module variables that could leak between requests.
Reducing cold starts
Bundle and minify (esbuild), import only what you need (modular AWS SDK v3 clients), avoid heavy init work, choose more memory (more CPU), keep functions small, and use provisioned concurrency or SnapStart where available when latency matters.
javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
// A handler file, as you would deploy it.
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'lambda-'));
const file = path.join(dir, 'handler.js');
fs.writeFileSync(file, `
let initRuns = 0;
initRuns++; // top-level code: runs once per execution environment
const client = { createdAt: 'init' }; // a database or SDK client would be created here
let invocations = 0;
exports.handler = async (event, context) => {
invocations++;
const raw = event.isBase64Encoded ? Buffer.from(event.body, 'base64').toString() : event.body;
const body = raw ? JSON.parse(raw) : {};
if (body.crash) throw new Error('something broke');
return {
statusCode: 200,
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ hello: body.name ?? 'world', invocations, initRuns, coldStart: invocations === 1, client: client.createdAt, msLeft: context.getRemainingTimeInMillis() > 0 }),
};
};
`);
// A tiny stand-in for the Lambda runtime (not AWS code): load once, then call the handler per event.
let handlerModule;
async function invoke(event, timeoutMs = 3000) {
handlerModule ??= require(file); // the first invoke pays the "init" cost
const deadline = Date.now() + timeoutMs;
const context = { awsRequestId: 'req-' + Math.random().toString(36).slice(2, 8), getRemainingTimeInMillis: () => deadline - Date.now() };
try { return await handlerModule.handler(event, context); }
catch (err) { return { errorType: err.name, errorMessage: err.message }; }
}
(async () => {
const print = (label, result) => console.log(label.padEnd(18), typeof result.body === 'string' ? `${result.statusCode} ${result.body}` : JSON.stringify(result));
print('1st invoke (cold)', await invoke({ body: JSON.stringify({ name: 'Asha' }) }));
print('2nd invoke (warm)', await invoke({ body: JSON.stringify({ name: 'Ravi' }) }));
print('base64 body', await invoke({ isBase64Encoded: true, body: Buffer.from('{"name":"Meera"}').toString('base64') }));
print('handler throws', await invoke({ body: '{"crash":true}' }));
fs.rmSync(dir, { recursive: true });
})();
A small simulated runtime (not AWS code) loads a handler file once and calls it several times, so the cold and warm behaviour can be seen. Real Lambda adds the platform, billing, limits and freezing. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
1st invoke (cold) 200 {"hello":"Asha","invocations":1,"initRuns":1,"coldStart":true,"client":"init","msLeft":true}
2nd invoke (warm) 200 {"hello":"Ravi","invocations":2,"initRuns":1,"coldStart":false,"client":"init","msLeft":true}
base64 body 200 {"hello":"Meera","invocations":3,"initRuns":1,"coldStart":false,"client":"init","msLeft":true}
handler throws {"errorType":"Error","errorMessage":"something broke"}
Key points
The handler receives (event, context) and returns or throws.
Top-level code runs once per execution environment (cold start).
Create clients outside the handler and reuse them.
Keep per-request data inside the handler.
Smaller bundles and lighter init reduce cold starts.
Common mistakes
Creating database clients inside the handler for every request.
Storing per-user data in module-level variables.
Importing the whole AWS SDK and large libraries.
Forgetting that the body can be base64 encoded.
Doing slow init work that every cold start pays for.
Follow-ups
What is the difference between provisioned concurrency and SnapStart?
How does memory size change CPU and cost?
What happens to a failed asynchronous invocation?
Tips
Explain init versus invoke.
Say 'clients outside, request data inside'.
Give two ways to reduce cold starts.
175.nodejs-0175Hardsenior
What are the common pitfalls of Node.js serverless functions: database connections, timeouts, duplicate events and work after the response?
Each concurrent execution has its own environment, so many functions can open too many database connections (reuse clients outside the handler and use a pooler or proxy). Functions are killed at the timeout, so budget time with the remaining time from the context. Events are delivered at least once, so handlers must be idempotent. After the handler returns the environment is frozen, so work that was not awaited may never finish.
Full answer
Connections
A pool of 10 connections per environment times 200 concurrent executions is 2000 connections, which can overwhelm a database. Create the client once per environment (outside the handler), use a small pool (1 to 2), and use a connection pooler or proxy (RDS Proxy, PgBouncer, an HTTP-based data API) for relational databases.
Time budget
The platform stops the function at its timeout, with no cleanup. Read context.getRemainingTimeInMillis(), give downstream calls a deadline that is shorter (with AbortSignal.timeout), and return a clean error or partial result before the kill. Also set sensible timeouts on SDK clients.
Duplicate delivery
Queues (SQS), streams, EventBridge and retries by the platform deliver at least once. The same event can arrive twice, or arrive out of order. Make the handler idempotent: record the event id with a conditional write, use natural idempotency keys for payments, and use upserts.
For SQS batches report partial failures, so one bad message does not return the whole batch.
Work after the response
When the handler returns, the environment is frozen, and timers and promises that were not awaited are paused or lost. Await everything before returning. For follow-up work use a queue or an extension that supports it.
Other points
Cold start latency on user-facing paths: lighter bundles, provisioned concurrency.
Local state: the filesystem (/tmp) and module memory survive only by chance, so treat them as a cache.
Concurrency limits and cost surprises: set reserved concurrency and budgets, and protect downstream systems with queues.
Observability: structured logs with the request id, and tracing across functions.
javascript
const { setTimeout: sleep } = require('node:timers/promises');
// A stand-in runtime (not AWS code) that keeps one environment and freezes it after each handler returns.
class FakeEnvironment {
constructor() { this.frozen = false; this.clientsCreated = 0; this.processed = new Set(); }
async invoke(handler, event, timeoutMs) {
this.frozen = false;
const deadline = Date.now() + timeoutMs;
const context = { getRemainingTimeInMillis: () => deadline - Date.now() };
const result = await handler(event, context, this);
this.frozen = true; // after the response the environment is paused
return result;
}
}
const dbClientPerInvoke = (env) => { env.clientsCreated++; return {}; };
let sharedClient;
const dbClientShared = (env) => (sharedClient ??= (env.clientsCreated++, {}));
async function main() {
// 1. Connections
const env = new FakeEnvironment();
for (let i = 0; i < 5; i++) await env.invoke(async (e, c, environment) => dbClientPerInvoke(environment), {}, 1000);
const perInvoke = env.clientsCreated;
env.clientsCreated = 0;
for (let i = 0; i < 5; i++) await env.invoke(async (e, c, environment) => dbClientShared(environment), {}, 1000);
console.log('1. clients created in 5 invocations: per invoke =', perInvoke, '| shared =', env.clientsCreated);
// 2. Time budget: stop waiting before the platform would kill us.
const slowDependency = (signal) => new Promise((resolve, reject) => {
const timer = setTimeout(() => resolve('data'), 500);
signal.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason); });
});
const result = await env.invoke(async (event, context) => {
const budget = context.getRemainingTimeInMillis() - 100; // keep 100 ms to answer
try { return await slowDependency(AbortSignal.timeout(budget)); }
catch (err) { return { statusCode: 504, error: err.name }; }
}, {}, 250);
console.log('2. dependency slower than the budget ->', JSON.stringify(result));
// 3. Duplicate delivery
const handler = async (event, context, environment) => {
if (environment.processed.has(event.id)) return 'duplicate skipped';
environment.processed.add(event.id); // a conditional write in a real table
return 'processed ' + event.id;
};
console.log('3. same event twice ->', await env.invoke(handler, { id: 'evt-1' }, 1000), '|', await env.invoke(handler, { id: 'evt-1' }, 1000));
// 4. Work that is not awaited
const steps = [];
await env.invoke(async (event, context, environment) => {
(async () => { for (let i = 1; i <= 3; i++) { await sleep(20); if (environment.frozen) { steps.push('frozen at step ' + i); return; } steps.push('step ' + i); } })();
return 'response sent'; // returns without awaiting the background work
}, {}, 1000);
await sleep(100);
console.log('4. background work after the response ->', steps.join(', '));
}
main();
A simulated environment is frozen after each response. It shows shared clients, a time budget, a duplicate event, and background work that stops after the handler returns. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
1. clients created in 5 invocations: per invoke = 5 | shared = 1
2. dependency slower than the budget -> {"statusCode":504,"error":"TimeoutError"}
3. same event twice -> processed evt-1 | duplicate skipped
4. background work after the response -> frozen at step 1
Key points
Reuse clients per environment and limit total database connections.
Use the remaining time to set deadlines before the platform kills the function.
Use queues to smooth load and protect downstream systems.
Common mistakes
A big pool per function with hundreds of concurrent executions.
No deadline on downstream calls, so the platform kills the function.
Assuming a message is delivered exactly once.
Starting a promise and returning without awaiting it.
Keeping state in module variables and relying on it.
Follow-ups
How does RDS Proxy help?
How do you report partial batch failures for SQS?
How do you limit the concurrency that hits a database?
Tips
Give the four pitfalls as a list.
Say 'at least once, so idempotent'.
Mention the frozen environment.
176.nodejs-0176Easyfresher
What is an edge runtime (Cloudflare Workers, Vercel Edge), and how does it differ from Node.js?
Edge runtimes run small functions in many locations close to users, usually in V8 isolates with Web-standard APIs (fetch, Request, Response, URL, crypto.subtle) and strict limits on CPU time, memory and bundle size. They start in milliseconds and have no file system, child processes or most Node core modules (some compatibility exists). Node gives the full platform and long-running processes. Edge is good for routing, auth checks, redirects and personalisation, and Node for heavy or stateful work.
Full answer
How edge runtimes work
Code runs in V8 isolates (lightweight sandboxes) instead of full processes or containers. Many isolates share one process. Start-up takes milliseconds, so cold starts are nearly invisible.
The programming model is the Web platform: export default { fetch(request, env, ctx) { return new Response('ok') } } (Workers style), or a (Request) => Response function. APIs available: fetch, Request, Response, Headers, URL, URLSearchParams, crypto.subtle, TextEncoder, streams, and often KV or object storage bindings.
Limits: CPU time per request (often 10 to 50 ms of CPU), memory around 128 MB, bundle size limits, no long-lived background tasks, and limited or no TCP connections (some now support them).
Compared with Node.js
Node: full standard library (fs, net, child_process, worker_threads), native addons, any npm package, long-running servers, and stateful processes.
Edge: no fs, no child processes, no native addons, only packages that use Web APIs. Many Node APIs exist through compatibility flags (nodejs_compat) but not all.
Data access: databases are usually far from the edge, so a round trip from the edge to a central database can cost more than it saves. Use edge-friendly data (KV, replicated databases, HTTP data APIs) or cache.
When to use which
Edge: redirects, A/B tests, authentication checks, header rewriting, geolocation, caching and simple APIs where latency matters.
Node: CPU-heavy tasks, long connections, large dependencies, anything that needs the file system or native libraries.
Portable style: write handlers with Web-standard Request and Response, so they run on Node, Deno, Bun and edge platforms.
javascript
// A handler written only with Web-standard APIs. The same function body would run on an edge runtime.
async function handle(request) {
const url = new URL(request.url);
if (url.pathname === '/hello') {
const name = url.searchParams.get('name') ?? 'world';
return Response.json({ message: `Hello ${name}`, country: request.headers.get('x-country') ?? 'unknown' });
}
if (url.pathname === '/old') return Response.redirect(new URL('/hello', url).href, 301);
if (url.pathname === '/hash') {
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(url.searchParams.get('text') ?? ''));
return new Response(Buffer.from(digest).toString('hex').slice(0, 16), { headers: { 'content-type': 'text/plain', 'cache-control': 'public, max-age=60' } });
}
return new Response('not found', { status: 404 });
}
(async () => {
const show = async (label, req) => {
const res = await handle(req);
const body = res.status === 301 ? res.headers.get('location') : await res.text();
console.log(label.padEnd(10), res.status, body, res.headers.get('cache-control') ?? '');
};
await show('hello', new Request('https://example.com/hello?name=Asha', { headers: { 'x-country': 'IN' } }));
await show('redirect', new Request('https://example.com/old'));
await show('hash', new Request('https://example.com/hash?text=edge'));
await show('missing', new Request('https://example.com/nothing'));
// Web APIs that exist in Node 24 as globals, so the handler above runs here unchanged.
const globals = ['fetch', 'Request', 'Response', 'Headers', 'URL', 'crypto', 'ReadableStream', 'TextEncoder'];
console.log('available as globals in Node:', globals.every((name) => name in globalThis));
})();
The handler uses only Web-standard APIs and is called with constructed Request objects. This shows the portable style, not the edge platform: an edge runtime was not available here, so the limits are described in the text only. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
hello 200 {"message":"Hello Asha","country":"IN"}
redirect 301 https://example.com/hello
hash 200 a1cb100f57e971ca public, max-age=60
missing 404 not found
available as globals in Node: true
Key points
Edge runtimes use isolates and Web-standard APIs.
They start fast but have strict CPU, memory and size limits.
No file system, child processes or native addons.
Data far from the edge can erase the latency gain.
Write portable handlers with Request and Response.
Common mistakes
Assuming every npm package works at the edge.
Calling a distant central database from many edge locations.
Doing CPU-heavy work in an edge function.
Using Node-only APIs such as fs in code meant for the edge.
Choosing edge for everything because it is fast to start.
Follow-ups
What is a V8 isolate, and how does it differ from a container?
How do you share code between Node and edge handlers?
What does nodejs_compat do on Workers?
Tips
Contrast isolates with processes.
List what is missing at the edge.
Name use cases for each.
177.nodejs-0177Easyfresher
How do Node.js, Deno and Bun differ, and how would you choose between them for a new project?
All three run JavaScript and TypeScript on the server. Node.js is the mature default with the biggest ecosystem and the longest support record. Deno focuses on secure defaults (permissions), built-in tooling, TypeScript and Web APIs. Bun focuses on speed, with a fast package manager, bundler and test runner built in. Node now covers many of their ideas (type stripping, fetch, test runner, permission model), so the differences are smaller than before.
Full answer
Node.js
V8 engine, libuv event loop, the largest npm ecosystem, the most production experience, LTS releases with long support, and the widest hosting and tooling support. Recent versions added built-in fetch, node:test, watch mode, TypeScript type stripping, an experimental permission model, require of ES modules and a single executable option.
Deno
V8, written in Rust. Secure by default (file, network and environment access need --allow flags), TypeScript without setup, Web-standard APIs first, a formatter, linter, test runner and package tooling in one binary, and URL, JSR and npm imports. Good compatibility with npm packages, but some native addons and edge cases differ. Deno Deploy is its hosting platform.
Bun
JavaScriptCore engine (from Safari), written in Zig. Very fast start-up and package installs, a built-in bundler, test runner, SQLite and shell helpers, and many Node APIs reimplemented. Compatibility is high but not complete, so subtle differences can appear in streams, native modules and less common APIs.
How to choose
Production services with many dependencies, compliance needs or a team that must hire: Node.js LTS.
Scripts, tools and edge-style apps where TypeScript and permissions help: Deno is a good fit.
Fast tooling, test speed and developer experience, with a plan to test compatibility: Bun, at least as a package manager or test runner.
Measure with your own workload. Micro benchmarks mislead, because real services spend time on I/O, databases and framework code.
Write portable code using Web APIs and the node: prefix for built-in modules, and check support in CI.
Always check the current version notes, because all three change quickly.
javascript
// Runtime detection and a function that only uses APIs that all three runtimes provide.
function detectRuntime() {
if (typeof globalThis.Deno !== 'undefined') return 'deno';
if (typeof globalThis.Bun !== 'undefined') return 'bun';
if (typeof process !== 'undefined' && process.release?.name === 'node') return 'node';
return 'unknown';
}
async function portableSummary(text) {
const bytes = new TextEncoder().encode(text);
const digest = await crypto.subtle.digest('SHA-256', bytes);
const id = Array.from(new Uint8Array(digest).slice(0, 4), (b) => b.toString(16).padStart(2, '0')).join('');
return { id, length: bytes.length, url: new URL('/items/' + id, 'https://example.com').href };
}
(async () => {
console.log('runtime:', detectRuntime());
console.log('user agent starts with Node.js:', navigator.userAgent.startsWith('Node.js'));
console.log('Deno global present:', typeof globalThis.Deno !== 'undefined', '| Bun global present:', typeof globalThis.Bun !== 'undefined');
console.log('built-in test runner:', typeof require('node:test').test === 'function', '| built-in fetch:', typeof fetch === 'function');
console.log('portable function result:', JSON.stringify(await portableSummary('hello runtimes')));
})();
The script was run on Node.js only. It detects the runtime and runs a function that uses only Web-standard APIs, which is the style that moves between Node, Deno and Bun. Nothing here was measured on Deno or Bun. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
runtime: node
user agent starts with Node.js: true
Deno global present: false | Bun global present: false
built-in test runner: true | built-in fetch: true
portable function result: {"id":"e80bacf5","length":14,"url":"https://example.com/items/e80bacf5"}
Key points
Node is the mature default with the largest ecosystem.
Deno stresses permissions, TypeScript and Web APIs.
Bun stresses speed and built-in tooling, with high but not full Node compatibility.
Node has absorbed many ideas from both.
Choose with your workload, dependencies and team in mind.
Common mistakes
Choosing a runtime from a micro benchmark.
Assuming full npm compatibility everywhere without testing.
Using runtime-specific APIs everywhere and getting locked in.
Running a non-LTS Node version in production.
Ignoring the team's experience and hosting support.
Follow-ups
How does the Deno permission model differ from the Node one?
Why is Bun fast at installing packages?
How do you test that your code runs on more than one runtime?
Tips
Give one sentence per runtime.
Say that Node has absorbed many features.
Answer 'choose by workload and team'.
178.nodejs-0178Easyfresher
How does the Node.js release schedule work, what do Current, Active LTS, Maintenance and End-of-Life mean, and which version should production use?
Each major version starts as Current, then moves to Active LTS for about a year of fixes and features that are safe, then to Maintenance LTS for critical fixes and security patches, and finally reaches End-of-Life, when it gets no more patches. Production should run an LTS line that is still supported, and plan the move to the next LTS before the end of support. Check the official schedule for exact dates, because the policy has changed in the past.
Full answer
Stages of a version
Current: new features, released in April and October historically, for about six months before a possible LTS promotion.
Active LTS: a long term support release (codename, for example Krypton for 24). Gets bug fixes, security fixes and carefully chosen backports for about 12 months. This is the version most teams should start new production work on.
Maintenance LTS: critical bug fixes and security updates only, for roughly another 18 months.
End-of-Life (EOL): no patches at all. Running an EOL version means unfixed security problems, and libraries and cloud services stop supporting it.
Practical rules
Run an LTS version in production. Even-numbered versions have been the LTS lines, and odd-numbered Current versions were short lived. The schedule can change, so read nodejs.org/en/about/previous-releases and the nodejs/Release repository.
Plan upgrades twice a year at most, and always before EOL. Upgrading one LTS at a time is easier than jumping several.
Pin the version: .nvmrc or .node-version, the engines field in package.json, and the same version in Docker images (node:24-slim), CI and local machines.
Subscribe to security announcements. Security releases can arrive at any time for supported versions.
Cloud platforms follow their own lists of supported runtimes (for example Lambda). Check them as well.
The script below uses a copy of the dates from the nodejs/Release schedule file (checked on 2026-12-04) and computes the status of each line on a chosen date. The dates were copied from the official file, so verify them again before you rely on them.
javascript
// Dates copied from the nodejs/Release schedule.json file on 2026-12-04. Verify them against the official source.
const schedule = {
v20: { start: '2023-04-18', lts: '2023-10-24', maintenance: '2024-10-22', end: '2026-04-30', codename: 'Iron' },
v22: { start: '2024-04-24', lts: '2024-10-29', maintenance: '2025-10-21', end: '2027-04-30', codename: 'Jod' },
v24: { start: '2025-05-06', lts: '2025-10-28', maintenance: '2026-10-20', end: '2028-04-30', codename: 'Krypton' },
v25: { start: '2025-10-15', maintenance: '2026-04-01', end: '2026-06-01' },
v26: { start: '2026-05-05', lts: '2026-10-28', maintenance: '2027-10-20', end: '2029-04-30', codename: 'Lithium' },
v27: { start: '2027-04-22', lts: '2027-10-20', end: '2030-04-30' },
};
function status(version, today) {
const v = schedule[version];
const at = (date) => date && today >= date; // ISO dates compare correctly as strings
if (!at(v.start)) return 'not released yet';
if (at(v.end)) return 'End-of-Life';
if (at(v.maintenance)) return 'Maintenance' + (v.lts ? ' LTS' : '');
if (at(v.lts)) return 'Active LTS';
return 'Current';
}
const daysUntil = (date, today) => Math.round((Date.parse(date) - Date.parse(today)) / 86400000);
const today = '2026-12-04';
console.log('status on', today);
for (const version of Object.keys(schedule)) console.log(' ', version, (schedule[version].codename || '').padEnd(8), status(version, today));
console.log('days until v22 reaches End-of-Life:', daysUntil(schedule.v22.end, today));
console.log('days until v24 reaches End-of-Life:', daysUntil(schedule.v24.end, today));
console.log('this process runs', process.version, '=', status('v' + process.versions.node.split('.')[0], today));
console.log('same version on the day v20 ended:', status('v20', '2026-04-29'), '->', status('v20', '2026-04-30'));
The dates in the script were copied from the official schedule file. The status is computed for a fixed date so the output does not change, and it must be checked against the official page when you rely on it. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
status on 2026-12-04
v20 Iron End-of-Life
v22 Jod Maintenance LTS
v24 Krypton Maintenance LTS
v25 End-of-Life
v26 Lithium Active LTS
v27 not released yet
days until v22 reaches End-of-Life: 147
days until v24 reaches End-of-Life: 513
this process runs v24.22.1 = Maintenance LTS
same version on the day v20 ended: Maintenance LTS -> End-of-Life
Key points
Current, Active LTS, Maintenance and End-of-Life are the four stages.
Production should use a supported LTS line.
EOL versions get no security patches.
Pin versions in .nvmrc, engines, Docker and CI.
Check the official schedule for exact dates.
Common mistakes
Running an End-of-Life version in production.
Starting new work on an odd-numbered or non-LTS release.
Waiting until the last week before EOL to upgrade.
Different Node versions on laptops, CI and servers.
Remembering dates from an old article instead of checking the schedule.
Follow-ups
What changes between Active LTS and Maintenance LTS?
How do you pin a Node version in a Docker image and in CI?
How do you test a new Node version before upgrading?
Tips
Name the four stages in order.
State the production rule.
Admit that you check the official dates.
179.nodejs-0179Mediummid
How do you upgrade Node.js to a new major version safely: reading release notes, deprecation warnings, engines, dependencies and rollout?
Read the release notes and the list of breaking changes, run your tests and CI on the new version first, turn deprecation warnings into visible failures (--throw-deprecation in CI, --trace-deprecation to find the source), update dependencies (native addons often need new builds), pin the version in engines and the Docker image, and roll out gradually with monitoring and an easy rollback.
Full answer
Preparation
Read the release announcement and the changelog for each major between your version and the target (the breaking changes section). Check the deprecation list (DEPxxxx codes).
Check your dependencies: do they support the new version? Native addons (bcrypt, sharp, argon2) need prebuilt binaries or a compiler for the new ABI. Update the lockfile and run npm audit.
Check the platform: Docker base image, CI images, serverless runtimes, and operating system libraries (musl or glibc).
Find problems early
Run the full test suite on the new version in CI, next to the old one (a matrix: 22 and 24).
Run with --throw-deprecation in CI so deprecated API use fails the tests. Use --trace-deprecation (or NODE_OPTIONS) to print the stack that triggered a warning. A deprecation in Node can become a removal in the next major version.
Watch for behavioural changes: default values (for example stream highWaterMark changes), stricter validation, changed error messages, and removed APIs.
Test performance and memory with a realistic load. The V8 version changes with every major.
Roll out
Update .nvmrc, the engines field, Dockerfile and CI together. engines with engine-strict makes npm enforce it.
Deploy to staging, then a small share of production (canary), compare error rates, latency and memory, and keep the old image ready for rollback.
Upgrade one LTS at a time, and schedule it regularly, so changes stay small.
Afterwards: remove workarounds for the old version, and use new built-in features carefully instead of adding dependencies.
javascript
const { spawnSync } = require('node:child_process');
const run = (flags, code) => {
const r = spawnSync(process.execPath, [...flags, '-e', code], { encoding: 'utf8' });
return { exit: r.status, stderr: r.stderr };
};
// 1. A deprecated API normally prints a warning and keeps working.
const plain = run([], "require('node:url').parse('http://example.com/a'); console.log('still works')");
console.log('1. default : exit', plain.exit, '| warning code:', (plain.stderr.match(/DEP\d+/) || ['none'])[0]);
// 2. In CI, turn the deprecation into an error.
const strict = run(['--throw-deprecation'], "require('node:url').parse('http://example.com/a'); console.log('still works')");
console.log('2. in CI : exit', strict.exit, '| error mentions:', (strict.stderr.match(/DEP\d+/) || ['none'])[0]);
// 3. Find where the warning comes from.
const traced = run(['--trace-deprecation'], "function oldWay() { require('node:url').parse('http://example.com'); } oldWay();");
console.log('3. with trace : stack names the calling function:', /oldWay/.test(traced.stderr));
// 4. A tiny engines check, like the one npm does with engine-strict.
const engines = { node: '>=22' };
const major = (v) => Number(String(v).replace(/^[^\d]*/, '').split('.')[0]);
const ok = major(process.versions.node) >= major(engines.node);
console.log('4. engines check:', engines.node, 'is satisfied by', process.version + ':', ok);
console.log(' a project that needs >=26 on this version:', major(process.versions.node) >= 26);
Child processes run the same deprecated call with different flags. It also shows a simplified engines check. Real checks use the semver package or npm itself. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
1. default : exit 0 | warning code: DEP0169
2. in CI : exit 1 | error mentions: DEP0169
3. with trace : stack names the calling function: true
4. engines check: >=22 is satisfied by v24.22.1: true
a project that needs >=26 on this version: false
Key points
Read the breaking changes for every major you cross.
Test on the new version in a CI matrix.
Use --throw-deprecation and --trace-deprecation to find deprecated API use.
Native addons need new builds.
Canary rollout with monitoring and a quick rollback.
Common mistakes
Upgrading production first and testing later.
Ignoring deprecation warnings until the API is removed.
Forgetting native addons and the Docker base image.
Skipping several major versions at once.
Different Node versions in local, CI and production.
Follow-ups
How do you list which dependencies break on a new Node version?
What does engine-strict do?
How would you do a canary deploy of a new runtime version?
Tips
Describe prepare, find, roll out.
Name --throw-deprecation.
Say 'one LTS at a time'.
180.nodejs-0180Hardsenior
A Node.js service in production is slow or restarting. How do you triage it in the first fifteen minutes, and what diagnostics can you collect safely?
First stabilise, then diagnose. Check what changed (deploy, traffic, dependency), look at the four signals (error rate, latency, CPU, memory) and the event loop, restart or roll back if users are hurt, and collect evidence before you destroy it: logs, a diagnostic report, a heap snapshot, a CPU profile. Classify the failure (CPU, memory, blocked event loop, resource exhaustion, a slow dependency) and then fix and prevent.
Full answer
Minutes 0 to 5: stabilise and orient
Who is affected, since when, and what changed? Check deploys, config, traffic, dependency status pages and recent alerts.
If a recent release correlates, roll back first. Diagnose afterwards.
Look at dashboards: request rate, error rate, latency (p50 and p99), CPU, memory, event loop delay or utilization, open handles and file descriptors, database and downstream latency, restarts.
Minutes 5 to 15: classify
High CPU, normal I/O: a hot loop, a regex, large JSON work, a crypto call. Capture a CPU profile (node --cpu-prof or the inspector).
Memory grows then OOM kill (exit code 137 in containers, or a V8 heap error): a leak or a huge payload. Take heap snapshots over time.
Event loop blocked (latency for everything, CPU one core at 100 percent, health checks time out): synchronous work. Check event loop delay and profile.
Errors such as ECONNRESET, ETIMEDOUT, EMFILE: a dependency or a limit. Check connection pools, file descriptor limits and downstream health.
Low CPU and slow requests: waiting on a database, lock or external API. Look at traces and timeouts.
Collecting evidence safely
Keep one instance out of rotation, then inspect it. Do not attach the debugger to a customer-facing instance.
process.report.getReport() (or --report-on-signal and kill -USR2) writes a JSON diagnostic report with JavaScript and native stacks, heap statistics, libuv handles and resource usage.
v8.writeHeapSnapshot() blocks the process and needs memory about equal to the heap, so use it on an isolated instance.
--heapsnapshot-near-heap-limit and --report-on-fatalerror capture data right before a crash.
Always save logs, metrics and traces with timestamps for the post-incident review.
After: write a blameless post-incident review, add the missing alert, add a regression test or a load test, and add limits (timeouts, concurrency, memory) that would have contained it.
javascript
const v8 = require('node:v8');
const { performance, monitorEventLoopDelay } = require('node:perf_hooks');
// A small "snapshot" function: the quick facts to look at during an incident.
function snapshot() {
const report = process.report.getReport();
const heap = v8.getHeapStatistics();
const memory = process.memoryUsage();
const elu = performance.eventLoopUtilization();
return {
reportSections: Object.keys(report),
nodeVersion: report.header.nodejsVersion,
heapUsedMB: Math.round(memory.heapUsed / 1048576),
heapLimitMB: Math.round(heap.heap_size_limit / 1048576),
heapUsedPercent: Math.round((heap.used_heap_size / heap.heap_size_limit) * 100),
openFileDescriptorLimit: report.userLimits.open_files.soft,
libuvHandles: report.libuv.length,
activeResources: process.getActiveResourcesInfo().sort(),
eventLoopUtilizationAvailable: typeof elu.utilization === 'number',
uptimeSeconds: Math.round(process.uptime()),
};
}
const delay = monitorEventLoopDelay({ resolution: 10 });
delay.enable();
const server = require('node:http').createServer((req, res) => res.end('ok')).listen(0, '127.0.0.1', () => {
const s = snapshot();
console.log('report sections :', s.reportSections.join(', '));
console.log('node version known :', s.nodeVersion === process.version);
console.log('heap used under limit :', s.heapUsedMB < s.heapLimitMB);
console.log('fd limit is a number :', typeof s.openFileDescriptorLimit === 'number' || s.openFileDescriptorLimit === 'unlimited');
console.log('active resources :', s.activeResources.join(', '));
console.log('ELU available :', s.eventLoopUtilizationAvailable);
// The event loop delay histogram is the quickest check for a blocked loop.
setTimeout(() => { // let the histogram run for a moment first
const end = Date.now() + 120;
while (Date.now() < end) {} // block the loop on purpose for 120 ms
setTimeout(() => {
delay.disable();
console.log('max loop delay above 100 ms after the blocking loop:', delay.max / 1e6 > 100);
server.close();
}, 100);
}, 50);
});
The script collects facts that matter in an incident from a running process and shows that the event loop delay histogram notices a 120 ms block. It is a starting point, not a monitoring system. Save it as app.js and run it with node app.js.
Output (Node.js v24.22.1, run once):
report sections : header, javascriptStack, javascriptHeap, nativeStack, resourceUsage, uvthreadResourceUsage, libuv, workers, environmentVariables, userLimits, sharedObjects
node version known : true
heap used under limit : true
fd limit is a number : true
active resources : TCPServerWrap
ELU available : true
max loop delay above 100 ms after the blocking loop: true
Key points
Stabilise first, roll back if a release correlates.
Classify the failure: CPU, memory, event loop, resource limits or a dependency.
Collect reports, profiles and snapshots from an isolated instance.
process.report gives a quick JSON diagnostic snapshot.
Finish with a review, alerts and limits.
Common mistakes
Restarting everything before saving any evidence.
Taking a heap snapshot on a busy production instance.
Changing several things at once and losing the cause.
Debugging before rolling back an obvious bad release.
No alert on event loop delay, memory growth or restarts.
Follow-ups
What does exit code 137 mean for a container?
How do you enable a diagnostic report on a signal?