Back to results for “Performance”
Node.js › Advanced Node.js

What is monkey-patching in the context of Node.js APM (Application Performance Monitoring) tools, and what are its risks?

Advanced

Answer

APM tools like New Relic or Datadog commonly instrument an application by monkey-patching -- overriding core module methods (like http.request or a database driver's query method) at runtime to inject timing and tracing logic transparently, without requiring the application code itself to change. The risk is that patched functions can subtly change behavior (altering stack traces, breaking assumptions about function.length or this binding), and multiple APM/tracing libraries patching the same method can conflict, causing hard-to-diagnose bugs.
// Simplified monkey-patch example
const originalRequest = http.request;
http.request = function(...args) {
  const start = Date.now();
  const req = originalRequest.apply(this, args);
  req.on('response', () => console.log('Request took', Date.now() - start, 'ms'));
  return req;
};
Real-world example A team debugging an intermittent production issue eventually traces it to two separately installed tracing libraries both monkey-patching the same database driver method, each wrapping the other's wrapper and silently swallowing an error that should have propagated to the application's error handler.

Common follow-ups: How do modern instrumentation libraries use AsyncLocalStorage or diagnostics_channel instead of raw monkey-patching to reduce these conflicts?;What's a safer alternative to monkey-patching for adding cross-cutting instrumentation?