How bcrypt Can Block the Node.js Event Loop

A synchronous hash or crypto call blocks the Node.js event loop, and even the async version shares a small thread pool. What I saw and how to deal with it.

· 2 min read · Erik Kubica

Node.js is usually described as non-blocking: a single OS thread, driven by libuv's event loop, can handle a lot of concurrent connections because it does not wait for network or disk operations.

That works well, until someone on the team adds password hashing to the login route.

// routes/auth.js - The line that froze our production API
const express = require('express');
const bcrypt = require('bcryptjs');
const router = express.Router();

router.post('/login', (req, res) => {
  const { password, hash } = req.body;
  // An innocent-looking synchronous call:
  const isValid = bcrypt.compareSync(password, hash);
  if (!isValid) return res.status(401).json({ error: 'Unauthorized' });
  return res.json({ token: 'jwt-payload' });
});

On the setup I tested, that single bcrypt.compareSync() call took approximately 85 milliseconds on a 3.2 GHz CPU core with cost factor 12.

For those 85 milliseconds, the V8 JavaScript thread is fully busy. It cannot accept new TCP sockets, parse incoming HTTP headers, or answer a lightweight /health check ping.

How the Latency Adds Up

Here is roughly what happens when twenty users try to log in at the same instant while hundreds of others are browsing ordinary product endpoints:

$ autocannon -c 100 -d 10 http://127.0.0.1:3000/health
Running 10s test @ http://127.0.0.1:3000/health
  100 connections

Stat         Avg       Stdev     Max
Latency (ms) 942.34    412.18    2150.80
Req/Sec      105.20    45.10     210.00
Bytes/Sec    24.2 kB   10.2 kB   48.2 kB

1k requests in 10.05s, 242 kB read

The max latency was 2.15 seconds for a simple JSON response that does nothing more than return {"status": "ok"}.

In our case the health check failed, the load balancer assumed the container was dead, and it started a rolling restart that took the cluster offline. All because a few people entered incorrect passwords at the same time.

The libuv Thread Pool

The usual suggestion is to use the asynchronous bcrypt.compare() instead, and that is a good first step.

Asynchronous bcrypt pushes the computation to libuv's worker threads. The catch is the default thread pool size in Node.js:

// Default libuv thread pool
process.env.UV_THREADPOOL_SIZE = 4;

Four threads by default.

If five login requests arrive concurrently, the fifth request queues in memory waiting for one of the four worker threads to finish its CPU-heavy hash rounds. Those four threads are also shared across:

  • crypto.pbkdf2 and hashing routines
  • DNS lookups via dns.lookup()
  • File system reads and writes via fs
  • Zlib compression streams

What I took from this: CPU-heavy work in a Node service needs a plan, because the thread pool is small and shared.

How Go Handles It

In Go, there is no single event loop that you have to avoid blocking. Every incoming HTTP request executes inside its own goroutine, scheduled across the available OS threads:

func handleLogin(w http.ResponseWriter, r *http.Request) {
    // Runs on an independent goroutine
    // Preemptively scheduled across all CPU cores
    err := bcrypt.CompareHashAndPassword(storedHash, []byte(password))
    if err != nil {
        http.Error(w, "Unauthorized", http.StatusUnauthorized)
        return
    }
    json.NewEncoder(w).Encode(map[string]string{"token": "token"})
}

If one goroutine spends 80ms running bcrypt on Core 1, the Go runtime scheduler can keep executing health checks and database queries on the other cores.

That does not make Node a bad choice. It works well for I/O-heavy services, and for CPU-heavy parts you can raise UV_THREADPOOL_SIZE, use worker threads, or move that work into a separate service. If your application does a lot of JSON transformation, cryptography or image processing, it is worth planning for this early, before it shows up as a slow Friday afternoon.

Tell me what you need built

Usually a reply within a day, by email or WhatsApp.