cs.oldnet

All sheets / Languages

Node.js

Runtime internals, async patterns and production concerns for backend interviews.

Architecture

  • Single JS thread + libuv event loop + thread pool (default 4, UV_THREADPOOL_SIZE).
  • Thread pool handles fs, dns.lookup, crypto, zlib. Network I/O uses OS async (epoll/kqueue).
  • Great for I/O-bound work; CPU-bound work blocks the loop → use worker_threads or a separate service.

Event loop phases

  1. timers: setTimeout / setInterval callbacks
  2. pending callbacks: some system errors
  3. poll: wait for and run I/O callbacks
  4. check: setImmediate
  5. close: socket.on('close')

Between every callback: process.nextTick queue first, then Promise microtasks.

Async patterns

import { readFile } from 'node:fs/promises';
import { promisify } from 'node:util';
const sleep = promisify(setTimeout);

// limit concurrency
async function mapLimit(items, limit, fn) {
  const out = []; let i = 0;
  const workers = Array.from({ length: limit }, async () => {
    while (i < items.length) { const idx = i++; out[idx] = await fn(items[idx]); }
  });
  await Promise.all(workers);
  return out;
}

const ac = new AbortController();
setTimeout(() => ac.abort(), 2000);
await fetch(url, { signal: ac.signal }); // cancellable

Streams

Four types: Readable, Writable, Duplex, Transform. Use them for large data so memory stays flat.

import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { createGzip } from 'node:zlib';

await pipeline(createReadStream('big.log'), createGzip(), createWriteStream('big.log.gz'));

for await (const chunk of readable) { /* ... */ }

Backpressure: write() returns false when the buffer is full; wait for 'drain'. pipeline handles it and cleans up on error.

Errors

process.on('unhandledRejection', (e) => { log(e); process.exit(1); });
process.on('uncaughtException', (e) => { log(e); process.exit(1); });

// graceful shutdown (ECS/K8s send SIGTERM)
process.on('SIGTERM', async () => {
  server.close();          // stop accepting new connections
  await db.end();
  process.exit(0);
});

Express skeleton

import express from 'express';
const app = express();
app.use(express.json());
app.get('/health', (req, res) => res.json({ ok: true }));
app.get('/users/:id', async (req, res, next) => {
  try { res.json(await svc.get(req.params.id)); } catch (e) { next(e); }
});
app.use((err, req, res, next) => res.status(err.status ?? 500).json({ error: err.message }));
app.listen(process.env.PORT ?? 3000);

Scaling & performance

  • cluster / multiple containers to use all cores; put a load balancer in front.
  • worker_threads for CPU tasks (hashing, image work).
  • Keep-alive agents for outbound HTTP; reuse DB pools.
  • Profile: node --inspect, --cpu-prof, clinic.js, --heap-snapshot-signal.
  • Memory leaks: growing caches/maps, listeners never removed, closures holding big objects.

npm & packaging

npm ci                  # clean, lockfile-exact install (use in CI)
npm i -D pkg            # devDependency
npm outdated; npm audit fix
npm version patch|minor|major
npx pkg                 # run without installing

SemVer: ^1.2.3 allows minor+patch, ~1.2.3 allows patch only.

Handy built-ins

import { randomUUID, createHash } from 'node:crypto';
createHash('sha256').update(s).digest('hex');
import { EventEmitter, once } from 'node:events';
import { setTimeout as sleep } from 'node:timers/promises';
import test from 'node:test';     // built-in test runner
structuredClone, fetch, AbortController // global in Node 18+