Learn / Performance / Lesson 14

CPU and the event loop

Node.js runs your code on one thread. One slow regular expression can stop every user at once, and it has taken down two of the biggest sites on the web.

Last updated: 2026-09-19

What it is

Node.js runs JavaScript on a single thread with an event loop: it picks up the next piece of work, runs it to the end, then picks up the next. Waiting on the network or the disk is free, because Node does other work meanwhile. But while your code is computing, nothing else runs. Not other requests, not timers, not health checks.

So in Node, a CPU problem for one request is a CPU problem for everyone.

Why it is a rule

Both were a single pattern, written by capable engineers, that was fast on normal input and explosive on unusual input.

How to do it

Treat regular expressions as code that can explode

Nested or overlapping repeats like (a+)+, (.) or \s+$ on untrusted text can take exponential or quadratic time.

js
/\s+$/.test(untrusted)

untrusted.trimEnd()

The first line slows down with the square of the input on a long run of spaces followed by one letter, because the engine retries the match from every space. The second is one pass.

Pick the right algorithm first

Most speed comes from doing less, not doing it faster.

Keep big work off the request path

Watch the event loop

perf_hooks.monitorEventLoopDelay() reports how late the loop is running. A rising delay means something is holding the thread.

How we do it here

Text parsers work line by line with anchored patterns and cap their input sizes. Large downloads such as ledgers and spreadsheets are streamed, not built whole in memory. Work whose inputs have not changed is done once and reused.

Benefits

Disadvantages

Checklist

Sources

Read this lesson as Markdown