A Node.js API responds slowly. How do you find the cause before you fix anything?
Suggested answer
The interviewer wants to know whether you work from measurements instead of guesses, and whether you understand why code that is fast on small data can be slow on large data.
The first step is to know where it is slow at the request level. If the server has logs that record the processing time of each request, you filter out which route is slow. If it doesn't, measure with performance.now() or add that log first.
The second step is to test your hypothesis by measuring each suspected part separately (formatting data, converting to JSON, a database query): if one part takes a few milliseconds out of several seconds in total, don't optimize it.
The third step is to use a profiler. For example, the --cpu-prof flag of Node.js writes a .cpuprofile file, so you can see which function spends the most time of its own.
One common cause is quadratic complexity: using find or includes on an array inside a loop. With a few hundred items you won't notice, but with tens of thousands it gets clearly slow. The fix is usually to use a Map or a Set and look things up by key.
After the fix, verify two things: whether the result is still correct (keep the old version to compare, or write a test) and how much faster it is (measure several times, take the median, at several data sizes to see the shape of the growth curve).
Bonus points: mention that not every piece of code is worth optimizing, that the more readable version is a reasonable decision at small scale, and that a measurement is only valid for the machine and the data you measured on.