Skip to content

Event Loop Additional Metrics to make event-loop stalls more visible #67649

Open

Description

@mateusz-nalepa

What is the problem this feature will solve?

Hey!
This feature will help with more precise detection of long-running tasks in Node.js event loop.
When calculating p99, it will help make long event-loop stalls more visible

What is the feature you are proposing to solve the problem?

My proposal is to add additional metrics like:

  • exceededIntervalCounter / okIntervalCounter
    • to calculate ratio between both of them
  • exceededIntervalDelay

Thanks to them, it would be easier to detect event-loop stalls.
Cause ok samples and exceeded samples are treated separately.

Before going further let me first explain current metrics, to be sure, that my understanding is correct.
Cause maybe there is something, I still don't understand well and this issue doesn't make sense.

Note: During issue I'm writing typically about task duration. But I'm aware that more precise interpretation is event loop probe delay.

Event Loop Utilisation

My understanding of Event Loop Utilization (ELU) is:

  • ELU isn't aware about task duration
  • ELU is similar to CPU utilization, but it's not CPU utilization
  • ELU like 85% may mean:
    • there is a problem with event loop
    • there is no problem with event loop, all tasks are short and event loop is healthy
  • ELU is great to detect skew in node.js cluster mode
    • worker1: ELU 20%
    • worker2: ELU 15%
    • worker3: ELU 85% - probably something wrong with this worker
utilization

Event Loop Delay

My understanding of Event Loop Delay (ELD) is:

  • when calculating p99
    • it can be low, because a lot of short tasks can hide long tasks
  • max is always helpful
  • it's rather like: catastrophe detector

Code looks like this:

function monitorSample(diffNanos) {
  delay.observe(diffNanos / 1e9);
  // delay.observe((diffNanos - intervalNanos ) / 1e9); i'm not sure
}
event_loop_delay

About those metrics:

  • exceededIntervalCounter
  • exceededIntervalDelay

My understanding of those Event Loop those metrics is:

  • exceededIntervalCounter ( together with okIntervalCounter )
    • how often event loop was doing tasks longer than interval?
      • to be more precise: how often probe wasn't able to execute?
      • okIntervalCounter is needed to calculate ratio
      • exceededRatio = exceededIntervalCounter / (okIntervalCounter + exceededIntervalCounter)
  • exceededIntervalDelay
    • if probe wasn't able to execute, how long it was delayed?

Let's assume interval 10ms to describe event loop status:

  • event loop idle or tasks below 10ms
    • always healthy sample
  • task between 10ms and 20ms - healthy or unhealthy sample
    • cause we don't know when task started
  • task higher than 20ms
    • always unhealthy sample

Code could look like this:

function monitorSample(diffNanos) {
  const lagNanos = Math.max(0, diffNanos - intervalNanos - intervalNanos);

  if (lagNanos > 0) {
    const missedSamples = Math.floor(diffNanos / intervalNanos);
    exceededCounter.inc(missedSamples);
    exceededHistogram.observe(lagNanos / 1e9);
  } else {
    okCounter.inc();
  }
}
exceeded

The best part in all of that

  • all of those metrics still do not directly measure end-user latency
    • splitting one big task into smaller tasks may cause tasks overlap
    • from logical point of view, there is a lot of concurrent cpu tasks
  • so higher response times during day, faster during night, may suggest, that tasks are overlapping
    • healthy event loop metric won't tell anything about that
yield_and_semaphore

What alternatives have you considered?

Just use current Event Loop Utilization and Event Loop Delay metrics.

I'm open to your feedback!

Activity

  1. added
    feature request
    on Nov 20, 2026
  2. mateusz-nalepa commented on Nov 23, 2026

    @mateusz-nalepa
    Author

    Hey,
    I was able to write minimal code which can show benefits of those metrics.

    1. Package.json
    {
      "name": "event-loop-demo",
      "version": "1.0.0",
      "type": "module",
      "scripts": {
        "start": "node event_loop.js"
      },
      "dependencies": {
        "@prometheus-io/client": "^0.16.1"
      }
    }
    1. Code - 124 lines of javascript
    Here's the code
    import {setTimeout as sleep} from 'node:timers/promises';
    import client from '@prometheus-io/client';
    
    const register = new client.Registry();
    client.collectDefaultMetrics({register});
    
    const intervalMs = 10;
    const intervalNanos = intervalMs * 1e6;
    const okCounter = new client.Counter({
        name: 'custom_eventloop_sample_ok',
        help: 'Number of event loop OK samples without a threshold violation.',
        registers: [register],
    });
    const exceededCounter = new client.Counter({
        name: 'custom_eventloop_sample_exceeded',
        help: 'Number of event loop exceeded samples after a threshold violation.',
        registers: [register],
    });
    const exceededHistogram = new client.Histogram({
        name: 'custom_eventloop_exceeded_lag_seconds',
        help: 'Event loop lag beyond two monitoring intervals, for delayed samples only.',
        registers: [register],
    });
    const exceededSummary = new client.Summary({
        name: 'custom_eventloop_exceeded_lag_summary_seconds',
        help: 'Quantiles of event loop lag for delayed samples only.',
        percentiles: [0.50, 0.90, 0.99],
        registers: [register],
    });
    
    export function logMessage(message) {
        const d = new Date();
        console.log(`${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}.${d.getMilliseconds()}   ` + message);
    }
    
    function monitorSample(diffNanos) {
        const lagNanos = Math.max(0, diffNanos - intervalNanos - intervalNanos);
    
        if (lagNanos > 0) {
            const missedSamples = Math.floor(diffNanos / intervalNanos);
            exceededCounter.inc(missedSamples);
            exceededHistogram.observe(lagNanos / 1e9);
            exceededSummary.observe(lagNanos / 1e9);
        } else {
            okCounter.inc();
        }
    }
    
    const busyCpuForMs = (ms) => {
        const end = Date.now() + ms;
        while (Date.now() < end) {
        } // busy wait
    };
    
    export async function bigProcessing(taskNumber, {numberOfSteps, stepDurationMs, yieldBetweenStep}) {
        logMessage("### Start big function for task number: " + taskNumber)
        const results = [];
        const startProcessingTime = Date.now();
    
        for (let step = 1; step <= numberOfSteps; step++) {
            busyCpuForMs(stepDurationMs);
            if (yieldBetweenStep) {
                await sleep(0);
            }
        }
    
        const elapsed = Date.now() - startProcessingTime;
    
        logMessage("### Ended big function for task number: " + taskNumber + " after: " + elapsed + " ms")
        return results;
    }
    
    
    function startEventLoopCustomMonitor() {
        let previousSampleNanos = process.hrtime.bigint();
    
        return setInterval(() => {
            const nowNanos = process.hrtime.bigint();
            const diffNanos = Number(nowNanos - previousSampleNanos);
            previousSampleNanos = nowNanos;
            monitorSample(diffNanos);
        }, intervalMs).unref();
    }
    
    async function printMetrics() {
        const metrics = (await register.metrics())
            .split('\n')
            .filter(line => line.startsWith('nodejs_eventloop') || line.startsWith('custom_eventloop'));
    
        console.log(metrics.join('\n'));
    }
    
    async function runExample() {
        console.log("############### RUNNING EXAMPLE");
    
        const eventLoopCustomMonitor = startEventLoopCustomMonitor();
    
        await sleep(5000);
        await bigProcessing(1, {
            numberOfSteps: 5,
            stepDurationMs: 1000,
            yieldBetweenStep: false,
        });
        await sleep(5000);
        await bigProcessing(2, {
            numberOfSteps: 5,
            stepDurationMs: 1000,
            yieldBetweenStep: true,
        });
        await sleep(5000);
        await bigProcessing(3, {
            numberOfSteps: 1000,
            stepDurationMs: 5,
            yieldBetweenStep: true,
        });
    
        await sleep(100);
        clearInterval(eventLoopCustomMonitor);
        await printMetrics();
    
    }
    
    runExample();

    Result default event loop delay metric:

    nodejs_eventloop_lag_p99_seconds 0.012230655 -> 12ms

    Result suggested metric:

    • custom_eventloop_sample_ok 1884
    • custom_eventloop_sample_exceeded 1001
    • custom_eventloop_exceeded_lag_summary_seconds{quantile="0.99"} 4.999811 -> 4.9s

    Ratio: (1001 / (1001 + 1884)) * 100 = 34.69% number of samples were unhealthy
    P99 for unhealthy samples is: 4.9s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature request

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions