Issue
I’m using NestJS (with Express Server) for a project and trying to optimize the performance on some of the endpoints, using New Relic I noticed that a big chunk of the response time of all endpoints is spent in an anonymous middleware, reaching 89% at some points.
Is there a way to find out which middleware is this?
Solution
I’ve made an answer to this in another question, but I figured I should go into a bit more depth here about what’s going on under the hood of Nest.
A route handler in Nest is technically a middleware in express. I.e.
@Controller('test')
export class TestController {
@Get()
testGet() {
return 'do the thing';
}
}
Get’s transformed under the hood (through some really awesome code) to
app.get('test', (req, res, next) => {
res.send('do the thing');
})
Now when we add on a filter
@Controller('test')
export class TestController {
@Get()
@UseFilter(SomeExceptionFilter)
testGet() {
return 'do the thing';
}
}
More magic happens and we get this
app.get('test', (req, res, next) => {
let returnVal = '';
try {
returnVal = controller.testGet();
} catch (err) {
returnVal = someExceptionFilterInstnace.catch(err, customArgumentHostThatNestMaintains);
}
res.send(returnVal);
})
(Disclaimer: this isn’t a perfect 1:1 representation of what actually happens, as there’s a lot going on, but this should get the idea across that it’s all middleware in the end)
This follows too as you add in services, they’re just method calls inside of the express/fastify middleware, and so they don’t get broken out in a nice way in newrelic.
Unfortunately, I don’t know of a good way to help with this in newrelic or how to add better annotations. Looking at the timing of the middleware, you’ve got 218 ms, which isn’t too bad. Most likely a database operation somewhere, so I’d check your pipes, guards, and interceptors, along with your service, and see if you have any possibly large queries. If nothing else, you can do some profiling locally and get a bit more raw information about the time being taken
Answered By – Jay McDoniel
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0