This page is for developers preparing for Node.js backend roles, from freshers who have built a few Express projects to engineers with several years of running APIs in production. Indian product companies and funded startups in 2026 rarely stop at "what is the event loop". They ask you to explain why a specific piece of code blocks it, how you would handle backpressure in a file upload, how you shut a service down without dropping requests, and how you found the last memory leak you fixed. Service companies still test fundamentals, but increasingly expect working knowledge of TypeScript, Redis, queues and containers.
The questions were compiled by VidhaiX trainers who run mock backend interviews. They are grouped into fresher, intermediate, experienced (3+ years) and scenario-based sections. Each answer describes what a strong response covers and where candidates usually slip, with short code samples where they make the point clearer.
How to Prepare for a Node.js Interview
- Draw the event loop phases from memory and predict the output order of a snippet mixing setTimeout, setImmediate, process.nextTick and resolved promises, then run it to check yourself.
- Build a small REST API with Fastify or Express that has validation, JWT auth, rate limiting, structured logging with pino, and a graceful shutdown handler you can demonstrate.
- Write a stream pipeline that reads a large CSV, transforms rows and writes to a file or database using stream/promises pipeline, and observe memory usage stays flat.
- Take a heap snapshot of a deliberately leaking service in Chrome DevTools, compare two snapshots, and practise explaining the retainer chain that keeps objects alive.
- Learn the Node 22/24 LTS toolbox: node --test, --watch, --env-file, native fetch, type stripping for TypeScript files, and the permission model flags.
- Add Redis caching and a BullMQ job queue to your project, including retries with backoff and an idempotency key, so you can discuss failure modes from experience.
- Profile a CPU-heavy endpoint with --cpu-prof or clinic flame, fix the hotspot, and record the before and after latency numbers to quote in interviews.
Node.js Interview Questions for Freshers
12 questions
Q1.What is Node.js, and why is it described as single-threaded yet able to handle many concurrent connections?
Node.js is a JavaScript runtime built on V8 and libuv. Your JavaScript runs on one main thread, but I/O such as sockets, files and DNS is handed to the operating system or to libuv, which notifies Node when results are ready. While one request waits on the database, the thread serves others.
A strong answer adds the limit: this model suits I/O-bound work. CPU-heavy code like image resizing or large JSON parsing runs on that single thread and stalls every other request.
Q2.Walk me through the phases of the Node.js event loop.
Each iteration runs phases in order: timers (expired setTimeout and setInterval callbacks), pending callbacks (some deferred system errors), idle/prepare (internal), poll (retrieve new I/O events and run their callbacks, blocking here if nothing else is scheduled), check (setImmediate callbacks) and close callbacks (such as a socket close event).
Between each callback, Node drains the process.nextTick queue and then the promise microtask queue. Candidates who forget the microtask draining usually get output-order questions wrong.
Q3.What is the difference between process.nextTick, setImmediate and a resolved promise callback?
process.nextTick callbacks run immediately after the current operation, before promise microtasks. Promise then callbacks run next, in the microtask queue. setImmediate runs in the check phase of the next loop iteration, after I/O polling.
The trap is recursion: a function that keeps scheduling itself with nextTick starves the event loop because that queue is drained fully before I/O. Use setImmediate when you want to yield to I/O.
setTimeout(() => console.log('timeout'), 0)
setImmediate(() => console.log('immediate'))
Promise.resolve().then(() => console.log('promise'))
process.nextTick(() => console.log('nextTick'))
console.log('sync')
// sync, nextTick, promise, then timeout/immediate
// (order of the last two is not guaranteed in the main module)Q4.What is the libuv thread pool, and which operations use it?
libuv keeps a pool of worker threads, four by default, configurable with UV_THREADPOOL_SIZE. It handles work the OS cannot do asynchronously in a portable way: most fs operations, dns.lookup, crypto functions like pbkdf2 and scrypt, and zlib compression.
Network sockets do not use it; they use epoll, kqueue or IOCP. A good candidate knows that heavy bcrypt hashing or many concurrent file reads can saturate the four threads and queue unrelated work like DNS lookups.
Q5.How does CommonJS differ from ES modules in Node.js?
CommonJS uses require and module.exports, loads synchronously and resolves exports at runtime. ES modules use import and export, are statically analysable, load asynchronously, support top-level await and run in strict mode. Node treats .mjs files, or .js files under "type": "module" in package.json, as ESM.
Interviewers like hearing about interop: ESM can import CommonJS, and recent Node versions (22 and 24) allow require() of synchronous ES modules, which removed much of the old dual-package pain. __dirname is replaced by import.meta.dirname in ESM.
// CommonJS
const { readFile } = require('node:fs/promises')
module.exports = { loadConfig }
// ES module
import { readFile } from 'node:fs/promises'
const config = JSON.parse(await readFile(import.meta.dirname + '/config.json', 'utf8'))
export { config }Q6.What does it mean to block the event loop, and how would you spot it?
Blocking means synchronous work holds the main thread long enough that timers, I/O callbacks and new requests wait. Common culprits are fs.readFileSync in a request path, JSON.parse on huge payloads, catastrophic regex backtracking and tight loops over large arrays.
You spot it through rising p99 latency across all endpoints at once, and you measure it with perf_hooks.monitorEventLoopDelay() or APM event loop lag metrics. A weak answer says "use async" without naming how to measure the delay.
Q7.What is a Buffer, and when do you use one instead of a string?
A Buffer is a fixed-length sequence of bytes, a subclass of Uint8Array, allocated outside the V8 heap. You use it for binary data: file contents, network packets, images, hashes and encodings such as base64 or hex.
Good candidates mention Buffer.alloc versus Buffer.allocUnsafe (the latter may contain old memory and must be fully overwritten), and that converting large buffers to strings repeatedly is wasteful. Strings assume an encoding; buffers do not.
Q8.What are streams in Node.js, and what are the four stream types?
Streams process data in chunks instead of loading it all into memory. The four types are Readable (a file read stream, an HTTP request), Writable (a file write stream, an HTTP response), Duplex (a TCP socket, readable and writable independently) and Transform (a Duplex whose output is computed from input, such as gzip).
The point interviewers want is memory: streaming a 2 GB file keeps memory roughly flat, while readFile loads all of it. Mention pipeline from node:stream/promises for composing them safely.
Q9.How do you handle errors in asynchronous Node.js code?
With async/await, wrap awaited calls in try/catch or let errors propagate to a central handler. With callbacks, check the error-first argument. Event emitters and streams need an error listener, otherwise the error is thrown and crashes the process.
Separate operational errors (timeout, invalid input, a downstream 503) from programmer errors (undefined property access). Operational errors are handled and returned to the client; programmer errors usually mean the process should log and restart cleanly rather than continue in an unknown state.
Q10.What is middleware in Express, and how does the order of middleware matter?
Middleware is a function with (req, res, next) that can read or modify the request, end the response, or call next() to pass control on. Express runs middleware in the order it is registered, so body parsing must come before routes that read req.body, and authentication before protected routes.
Error-handling middleware has four arguments, (err, req, res, next), and must be registered last. A common bug is forgetting to call next() or to send a response, which leaves the request hanging until the client times out.
Q11.What is package-lock.json for, and what is the difference between npm install and npm ci?
The lockfile records the exact resolved version and integrity hash of every dependency in the tree, so every machine installs the same code. npm install may update the lockfile when package.json ranges allow newer versions. npm ci deletes node_modules, installs exactly what the lockfile says and fails if the two files disagree.
Use npm ci in CI and Docker builds for reproducibility. Committing the lockfile is expected; candidates who add it to .gitignore raise a flag.
Q12.How do you read environment variables in Node.js, and what changed with --env-file?
Configuration comes from process.env, which always holds strings, so you parse numbers and booleans yourself and validate them at startup. Historically teams used the dotenv package to load a .env file.
Since Node 20.6, node --env-file=.env app.js loads the file natively, and process.loadEnvFile() does the same programmatically. A strong answer adds that secrets in production should come from a secrets manager or the orchestrator, never from a committed .env file, and that config should fail fast when a required variable is missing.
Node.js Intermediate Interview Questions
12 questions
Q13.What is backpressure in streams, and how does Node handle it?
Backpressure happens when a writable cannot consume data as fast as a readable produces it. writable.write() returns false once its internal buffer passes highWaterMark; the producer should pause until the drain event. Ignoring that return value lets memory grow without bound.
pipe() and pipeline() handle this for you, and pipeline also destroys every stream and reports an error if any stage fails. Hand-rolled on("data") loops that write without checking are a classic interview code-review catch.
import { pipeline } from 'node:stream/promises'
import { createReadStream, createWriteStream } from 'node:fs'
import { createGzip } from 'node:zlib'
await pipeline(
createReadStream('access.log'),
createGzip(),
createWriteStream('access.log.gz'),
)Q14.When would you use worker_threads, cluster or child_process?
worker_threads run JavaScript in parallel threads inside one process, can share memory via SharedArrayBuffer and transfer buffers cheaply. Use them for CPU-bound tasks such as image processing or parsing. cluster forks multiple Node processes sharing a server port, to use all cores for HTTP traffic. child_process runs separate programs, such as ffmpeg or a Python script.
In containers, many teams skip cluster and run one process per container, letting Kubernetes scale replicas. Mentioning a worker pool library like Piscina shows practical experience.
import { Worker } from 'node:worker_threads'
function resizeInWorker(imagePath) {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL('./resize-worker.js', import.meta.url), {
workerData: { imagePath },
})
worker.once('message', resolve)
worker.once('error', reject)
})
}Q15.What happens on an unhandled promise rejection in current Node.js versions?
Since Node 15 the default --unhandled-rejections mode is throw: an unhandled rejection is raised as an uncaught exception and, without a handler, the process exits with a non-zero code. Older code that relied on a warning breaks.
A good answer covers process.on("unhandledRejection") and process.on("uncaughtException") as last-resort loggers that flush logs and exit, not as a way to keep running. The real fix is awaiting or catching every promise, and lint rules like no-floating-promises catch the misses.
Q16.How would you design a clean REST API for a resource such as orders?
Use nouns and HTTP methods: GET /orders, GET /orders/:id, POST /orders, PATCH /orders/:id. Return correct status codes (201 with a Location header on create, 404, 409 on conflict, 422 for validation), a consistent error body, and cursor-based pagination for large lists.
Strong candidates mention versioning strategy, filtering and sorting conventions, idempotency keys for POSTs that create payments, and an OpenAPI spec as the contract. A weak answer returns 200 with an error message in the body.
Q17.Compare JWT-based authentication with server-side sessions.
Sessions store state on the server (often Redis) and give the client an opaque cookie; revocation is instant by deleting the session. JWTs are signed tokens holding claims, verified without a lookup, which suits multiple services, but they cannot be revoked before expiry without a denylist.
In practice: short-lived access tokens (minutes) plus rotating refresh tokens, stored in HttpOnly, Secure, SameSite cookies rather than localStorage. Mention pinning the algorithm when verifying, and never putting sensitive data in the payload, since it is only encoded, not encrypted.
Q18.How do you validate request input in a Node.js API?
Validate at the boundary with a schema: Zod, Valibot or JSON Schema via Ajv. Fastify compiles JSON Schema for both validation and fast serialization. The schema should reject unknown fields, enforce types, lengths and formats, and the validated output, not raw req.body, should flow into business logic.
With TypeScript, inferring types from the schema keeps runtime checks and compile-time types in sync. Interviewers watch for candidates who think TypeScript types alone validate input; they disappear at runtime.
import { z } from 'zod'
const CreateOrder = z.object({
productId: z.string().uuid(),
quantity: z.number().int().min(1).max(100),
}).strict()
app.post('/orders', (req, res) => {
const parsed = CreateOrder.safeParse(req.body)
if (!parsed.success) return res.status(422).json(parsed.error.flatten())
// use parsed.data from here on
})Q19.How would you implement rate limiting for an API that runs on several instances?
In-memory counters fail once you have multiple instances, because each holds its own count. Use a shared store such as Redis with a fixed window, sliding window or token bucket algorithm, usually implemented atomically with a Lua script or a library like rate-limiter-flexible or @fastify/rate-limit with a Redis store.
Key by user ID or API key rather than only IP, return 429 with Retry-After, and apply stricter limits to login and OTP endpoints. Mention that edge or gateway limits complement, not replace, application limits.
Q20.How do you add Redis caching to a Node.js service without serving stale or inconsistent data?
The common pattern is cache-aside: read from Redis, on a miss load from the database, then set the value with a TTL. On writes, update the database and delete the cache key rather than updating it, to avoid race conditions between concurrent writers.
A strong answer covers TTL jitter to avoid synchronized expiry, protecting against cache stampede with a lock or request coalescing, versioned keys, and deciding which data can tolerate staleness. Caching without an invalidation plan is the usual weak spot.
async function getProduct(id) {
const key = 'product:v2:' + id
const hit = await redis.get(key)
if (hit) return JSON.parse(hit)
const row = await db.product.findUnique({ where: { id } })
if (row) await redis.set(key, JSON.stringify(row), 'EX', 300 + Math.floor(Math.random() * 60))
return row
}Q21.Why do you need database connection pooling, and how do you size the pool?
Opening a database connection costs a TCP and TLS handshake plus authentication, and PostgreSQL spawns a process per connection. A pool such as pg.Pool reuses a fixed set of connections across requests. Each instance should create one pool at startup, not per request.
Size it from the database side: total connections across all replicas must stay under max_connections. Ten pods with a pool of 20 is 200 connections. With serverless or many pods, put PgBouncer in front. Always release clients in a finally block.
Q22.How does Fastify differ from Express, and when would you choose it?
Fastify uses JSON Schema for validation and response serialization, an encapsulated plugin system, hooks such as onRequest and preHandler, and native async handlers. It ships with pino logging and is typically faster than Express under JSON-heavy load.
Express 5 is now stable and handles rejected promises in handlers, but its ecosystem is older and middleware-based. Choose Fastify for new performance-sensitive APIs with schemas; Express when the team and middleware ecosystem matter more. The honest answer is that the database is usually the bottleneck, not the framework.
Q23.What does structured logging mean, and why use pino over console.log?
Structured logging writes JSON lines with consistent fields (level, time, message, request ID, user ID) that log platforms can index and query. pino is fast because it serializes cheaply and moves formatting and transport to separate threads or processes.
console.log is synchronous for terminals and files, unstructured and has no levels. Good candidates mention child loggers carrying a request ID, redacting secrets with pino redact paths, and never logging full request bodies with passwords or tokens.
Q24.How do you write tests with the built-in Node.js test runner?
Import test or describe/it from node:test and assertions from node:assert/strict, then run node --test. It supports subtests, before/after hooks, mocking via the mock object including timers, and watch mode with --watch. Coverage is available with --experimental-test-coverage.
Many teams still use Vitest or Jest for richer features, but the built-in runner removes dependencies for libraries and small services. Interviewers want to hear how you test an HTTP route, for example with fetch against a server on an ephemeral port.
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { calculateTotal } from './cart.js'
test('applies 10 percent discount above 1000', () => {
assert.equal(calculateTotal([{ price: 1200, qty: 1 }]), 1080)
})Node.js Interview Questions for Experienced (3+ Years)
11 questions
Q25.How do you implement graceful shutdown for a Node.js HTTP service running in Kubernetes?
On SIGTERM, fail the readiness probe so traffic stops arriving, call server.close() to stop accepting connections, let in-flight requests finish, then close queue workers, the database pool and Redis, and exit. Add a hard timeout below terminationGracePeriodSeconds in case something hangs.
Experienced candidates mention keep-alive connections that keep close() waiting (server.closeIdleConnections() helps), and that the container must run Node as PID 1 correctly or use tini so signals actually arrive. npm start as the entrypoint often swallows signals.
process.on('SIGTERM', async () => {
ready = false
server.close()
server.closeIdleConnections()
const force = setTimeout(() => process.exit(1), 25_000)
await worker.close()
await pool.end()
clearTimeout(force)
process.exit(0)
})Q26.How do you find and fix a memory leak in a production Node.js service?
Confirm it first: heap used climbs across GC cycles and never returns to baseline. Then take heap snapshots with --heapsnapshot-signal, v8.writeHeapSnapshot() or the inspector, ideally two or three over time under load, and compare them in Chrome DevTools to see which constructors grow and what retains them.
Typical causes are unbounded in-memory caches or Maps, event listeners added per request, closures capturing large objects, and timers never cleared. Mention that a snapshot pauses the process and roughly doubles memory, so take it on one instance pulled from rotation.
Q27.How do you profile CPU performance in Node.js?
Start with metrics to find which endpoint is slow and whether the cause is CPU or waiting on I/O. For CPU, run with --cpu-prof to write a .cpuprofile, attach Chrome DevTools via --inspect, or generate flame graphs with 0x or Clinic.js. Look for wide frames: synchronous parsing, regex, serialization, crypto on the main thread.
Strong candidates load-test with autocannon or k6 to reproduce, change one thing at a time and compare latency percentiles, not averages. They also know that slow I/O shows up in traces, not CPU profiles.
Q28.How would you add observability to a Node.js microservice using OpenTelemetry?
Initialise the OpenTelemetry Node SDK before any other module loads (via --import of a setup file), with auto-instrumentations for HTTP, Express or Fastify, pg, Redis and messaging clients. Export traces and metrics over OTLP to a collector, then to Tempo, Jaeger, Honeycomb or a vendor.
Propagate W3C trace context across services and queues, inject the trace ID into pino logs so logs and traces correlate, and add custom spans around business-critical steps. Watch sampling rates and attribute cardinality, which drive cost.
Q29.How do you process background jobs reliably with BullMQ or Kafka?
BullMQ uses Redis for job queues with retries, exponential backoff, delayed jobs, rate limits and concurrency per worker. It suits task queues: emails, PDF generation, webhooks. Kafka is a durable, partitioned log for event streaming, with ordering per partition and consumer groups, suited to high-volume events that multiple services consume.
Either way, delivery is at least once, so handlers must be idempotent. Mention dead-letter handling for jobs that exhaust retries, and graceful worker shutdown so in-progress jobs are not left stalled.
Q30.What is idempotency, and how do you make a payment-creating endpoint idempotent?
An operation is idempotent if repeating it has the same effect as doing it once. Networks retry, users double-click and queues redeliver, so endpoints that create payments or orders need protection. The client sends an Idempotency-Key header; the server stores the key with the request hash and the resulting response.
On a repeat key, return the stored response. Enforce uniqueness with a database constraint, not just a check-then-insert, to survive concurrent duplicates, and reject a reused key with a different payload. Keys expire after a sensible window, such as 24 hours.
INSERT INTO idempotency_keys (key, request_hash, status)
VALUES ($1, $2, 'processing')
ON CONFLICT (key) DO NOTHING
RETURNING key;
-- no row returned: a duplicate, so load and return the stored responseQ31.How do you approach security for a Node.js API in line with the OWASP Top 10?
Cover the categories concretely: broken access control (check object ownership on every request, not just authentication), injection (parameterised queries, no eval, no shell string building with exec), security misconfiguration (helmet headers, no stack traces in responses), SSRF on endpoints that fetch user-supplied URLs, and prototype pollution from unsafe object merging.
For the supply chain, run npm audit or a tool like Snyk or Socket in CI, pin versions with the lockfile, review install scripts, and use npm ci --ignore-scripts where possible. Interviewers want IDOR examples, not a recited list.
Q32.What is the Node.js permission model, and where is it useful?
Started with --permission, Node restricts access to the file system, child processes, worker threads and native addons unless explicitly granted with flags such as --allow-fs-read, --allow-fs-write, --allow-child-process and --allow-worker. Code can check access at runtime with process.permission.has().
It was promoted to stable in recent releases and is useful for CLI tools, build scripts and running less trusted code. A careful candidate says it is defence in depth, not a sandbox for hostile code, and that network restrictions are not equivalent to a container or OS-level isolation.
Q33.How does running TypeScript directly in Node.js work now, and what are its limits?
Node 22.18+ and Node 24 strip TypeScript type annotations by default, so node app.ts runs without a build step. It replaces types with whitespace rather than compiling, which keeps source maps unnecessary.
The limits matter: it does not type-check, so tsc --noEmit still belongs in CI. Syntax that needs code generation, such as enum and parameter properties, requires --experimental-transform-types, and imports must use real file extensions with import type for type-only imports. Settings like erasableSyntaxOnly in tsconfig keep code compatible.
Q34.How do you scale a Node.js API horizontally, and what has to change in the code?
Run multiple stateless instances behind a load balancer or as Kubernetes replicas, scaling on CPU, latency or queue depth. The code must not keep per-user state in memory: sessions, rate limit counters, caches that need consistency and WebSocket presence move to Redis or the database.
Experienced candidates mention sticky sessions or a Redis adapter for Socket.IO, scheduled jobs that must run once (a distributed lock or a queue scheduler, not setInterval in every replica), and database connection limits growing with replica count.
Q35.How do you keep Node.js services current with LTS releases, and what does an upgrade involve?
Even-numbered releases become LTS; production should run Active or Maintenance LTS and move before end-of-life. Today that means Node 22 or 24. An upgrade involves reading the changelog for breaking changes, updating the Docker base image and engines field, rebuilding native addons, and running the full test suite plus a canary deployment.
Good answers mention dependencies that pin old Node versions, OpenSSL changes affecting legacy ciphers, and removing polyfills such as node-fetch once native fetch, --watch and --env-file cover them.
Node.js Scenario-Based Interview Questions
8 questions
Q36.All endpoints of your API suddenly have 3-second p99 latency, but database metrics look normal. How do you investigate?
Latency rising across every endpoint at once points to a blocked event loop or saturated thread pool rather than one slow query. I would check event loop delay metrics, CPU per instance and recent deploys. If CPU is pinned, capture a CPU profile from one instance and look for synchronous hot paths: a new regex, a large JSON.stringify, synchronous crypto.
If CPU is low, suspect the libuv pool (bcrypt or fs calls queueing) or a connection pool exhausted by a leak. Roll back first if a deploy correlates.
Q37.Memory on your Node pods grows steadily until they are OOM-killed every few hours. What do you do?
Short term, keep the service up: raise limits or schedule restarts while investigating, and check whether --max-old-space-size is aligned with the container limit. Then confirm whether heap or external memory grows using process.memoryUsage() metrics.
For heap growth, take snapshots on one pod at intervals and compare retainers. If external or RSS grows instead, look at buffers, native modules or allocator fragmentation. I would review recent changes for module-level Maps used as caches and listeners registered per request.
Q38.A user uploads 2 GB CSV files and your import endpoint crashes the server. How do you redesign it?
The crash almost certainly comes from buffering the whole file, for example with a body parser or readFile. I would stream the upload straight to object storage with presigned URLs, then enqueue a job. A worker streams the file, parses rows with a streaming CSV parser and inserts in batches inside a pipeline, so backpressure keeps memory flat.
Add progress tracking, validation errors per row written to a report, idempotency so retried jobs do not duplicate rows, and size limits on the endpoint.
Q39.During every deploy, clients see a burst of 502 errors for a few seconds. How do you fix it?
Pods are being killed while still receiving traffic or holding requests. I would add a SIGTERM handler that marks readiness as failing, waits a few seconds for the load balancer to deregister the pod (a preStop sleep also works), then closes the server and drains in-flight requests before exiting.
Also check that the entrypoint is node directly or via tini, not npm start, so the signal reaches Node. Align keep-alive timeouts with the load balancer so it never reuses a connection Node has closed.
Q40.Your payment webhook handler occasionally credits a customer twice. What is happening and how do you fix it?
Payment providers deliver webhooks at least once and retry on timeouts, so a slow handler that eventually succeeds still receives the retry. Two deliveries processed concurrently both pass a check-then-insert.
I would verify the signature, then record the provider event ID in a table with a unique constraint inside the same transaction as the credit. A duplicate hits the constraint and returns 200 without side effects. Respond quickly and move heavy processing to a queue so the provider does not time out and retry.
Q41.npm audit reports a critical vulnerability in a transitive dependency with no patched version from the direct dependency. What do you do?
First assess exploitability: is the vulnerable function reachable in our code path, and is it a runtime or dev-only dependency? Many critical reports affect build tooling only. If it is reachable, I would use the overrides field in package.json to force a patched version of the transitive package, run the test suite, and open an issue or PR upstream.
If no fix exists, mitigate at the boundary, for example input limits, or replace the library. Document the decision so the next audit does not repeat the investigation.
{
"overrides": {
"vulnerable-lib": "^2.4.3"
}
}Q42.A report generation endpoint takes 8 seconds of CPU and makes the rest of the API unresponsive. How do you handle it?
The work is CPU-bound on the main thread, so every other request waits. Short term I would move it off the request path: return 202 with a job ID, process it in a BullMQ worker running as a separate deployment, and let the client poll or receive a notification.
If it must stay synchronous, run it in a worker_threads pool such as Piscina sized to available cores. Then profile it, because 8 seconds often hides an N+1 query or an inefficient loop that can be fixed outright.
Q43.After moving to Kubernetes with 12 replicas, PostgreSQL starts rejecting connections with "too many clients". How do you fix it?
Each replica creates its own pool, so 12 replicas with a pool of 20 open 240 connections, plus migrations, cron jobs and admin tools, exceeding max_connections. Autoscaling makes it worse at peak.
I would reduce per-pod pool size based on measured concurrency, add PgBouncer in transaction pooling mode in front of the database, and check for leaked clients not released in finally. Raising max_connections is a last resort, because each PostgreSQL connection is a process consuming memory.