DigitalPaani’s backend is an Express monolith of roughly 300 routes. Three or four of them, the dashboard and access-control endpoints, carried around 75% of all requests and CPU time. For super users those routes were slow, and their long queries timed out.
Problem
The service functions behind those routes had grown long and general. One function handled many kinds of request through branch after branch of if/else, and built its response by adding and deleting properties as it went. They were hard to debug and hard to optimise.
I took this on myself after the access-control rollout. Adding servers or bigger instances was off the table, because the team did not want to spend more on infrastructure, so the fix had to be in the code.
Decisions
Read the flat profile as the clue
node --prof showed no single hot function. Time was spread thinly across DTO mappers, middleware wrappers and validation helpers, and a large share sat inside V8 itself: LoadIC_Megamorphic, KeyedLoadIC_Megamorphic and Scavenge.
Those names explain the flatness. While a function runs in Ignition, V8’s interpreter, its inline caches collect type feedback: the hidden classes (shapes) of the objects seen at each property access. TurboFan, the optimising compiler, then speculates on that feedback. If a site has only ever seen one shape, it is monomorphic, and TurboFan compiles row.id into a shape check plus a single load at a fixed offset, then inlines the code around it. If an object with a new shape arrives later, the check fails and the function is deoptimised back to the interpreter, to be optimised again later with weaker assumptions. A site that has seen more than four shapes goes megamorphic: there is nothing left to speculate on, so every access becomes a lookup in a global stub cache. Nothing was slow on its own; every helper paid a small tax on every property read. Scavenge pointed at a second problem: the young generation was filling up fast.
To find the exact sites, I ran the routes in staging with --trace-ic, --trace-opt and --trace-deopt. Together they log every inline-cache transition, every function TurboFan optimised, and the exact lines where its speculation failed and it deoptimised.
One shape per object
The examples below are generic illustrations, not production code, but the patterns are the ones I found and fixed.
// Before: one function for every kind of record
function toRow(record: any) {
const row: any = { id: record.id };
if (record.customer) row.customer = record.customer.name;
if (record.kind === 'order') {
row.total = record.total;
} else {
row.amount = record.amount;
row.reason = record.reason;
}
if (row.amount == null) delete row.amount;
return row;
}
Each path through that function produces a differently shaped object: with or without customer, with total or with amount and reason. The delete is worse. Removing a property that was not the last one added can drop the object into dictionary mode, where every access is a hash lookup. Any code that later reads these rows sees five or more shapes and goes megamorphic.
I split the general functions into small helpers, one per kind of input, so each helper only ever sees one shape. Responses became DTOs with every field set at construction, null where unused, always in the same order, so they all share one hidden class. delete went entirely. With one shape at each site, the type feedback stays monomorphic, TurboFan’s assumptions hold, and the functions stay optimised instead of being thrown back to the interpreter.
// After: one helper per kind, one shape for every row
class Row {
constructor(
readonly id: string,
readonly customer: string | null,
readonly total: number | null,
readonly amount: number | null,
readonly reason: string | null,
) {}
}
const orderRow = (o: Order) =>
new Row(o.id, o.customer?.name ?? null, o.total, null, null);
const refundRow = (r: Refund) =>
new Row(r.id, r.customer?.name ?? null, null, r.amount, r.reason);
const toRow = (rec: Order | Refund) =>
rec.kind === 'order' ? orderRow(rec) : refundRow(rec);
One pass instead of a chain
The busiest routes transformed arrays of 500 or more items per request with chained .filter().map().reduce() and object spreads inside the loop.
// Before: three passes, a copy per item, a new accumulator per item
const totals = items
.filter((i) => i.active)
.map((i) => ({ ...i, value: i.price * i.qty }))
.reduce(
(acc, i) => ({ ...acc, [i.group]: (acc[i.group] ?? 0) + i.value }),
{},
);
Every step allocates: an intermediate array per stage, a copied object per item, and a spread inside reduce that copies the whole accumulator on every iteration. All of it is garbage within milliseconds, and it kept the scavenger running and pausing the event loop.
On the hot paths I replaced these chains with single for loops writing into a Map or into arrays sized up front, so a request allocates its result and little else.
// After: one pass, one Map, no throwaway objects
const totals = new Map<string, number>();
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (!item.active) continue;
const value = item.price * item.qty;
totals.set(item.group, (totals.get(item.group) ?? 0) + value);
}
I also raised V8’s young-generation semi-space to 64 MB. With more room, scavenges run less often, and objects that only live for one request die young instead of being promoted to the old generation, where collecting them costs more.
node --max-semi-space-size=64 dist/server.js
Measure Node alone, then roll out gradually
To see the effect of each change, I load-tested an isolated staging environment with autocannon (100 connections for 60 seconds) and k6. Database latency was mocked, so the numbers measured Node and V8 rather than MongoDB. The changes then went to production gradually.
Result
- p95 latency on the busiest routes fell from about 420 ms to about 150 ms in the staging load test.
- In production, the timeouts on long queries stopped, and super users stopped complaining about slowness.
- No new servers or bigger instances were needed.