CodeJournal Blog Header

How to Fix Slow Express.js API Responses Caused by Blocking Operations

Fixing API Bottlenecks with Async Workers

Table of Contents

An Express.js API can become slow even when its routes, database, and hosting appear to be working correctly. One common reason is blocking operations that prevent Node.js from processing other work while the current operation runs.

Node.js uses an event loop to coordinate JavaScript execution, incoming connections, and asynchronous operations. When a route performs an expensive synchronous task—such as reading a large file synchronously, processing a large JSON payload, or executing a CPU-intensive calculation—the event loop cannot move on to other JavaScript callbacks until that work finishes. As a result, unrelated API requests may also experience delays. The official Node.js documentation explains why keeping event-loop callbacks short is essential for throughput and responsiveness.

The solution is not simply to add more Express middleware or increase the server’s timeout. First, identify what is blocking execution, measure its impact, and apply a fix suited to that operation.

Why Do Blocking Operations Make Express.js APIs Slow?

Express.js handles requests through route handlers and middleware. Although many operations can run asynchronously, ordinary JavaScript on the main thread executes sequentially until it yields control.

Consider this example:

app.get("/report", (req, res) => {
  const report = generateLargeReport();
  res.json(report);
});

If generateLargeReport() performs substantial synchronous computation, the server must finish that computation before sending the response or running other JavaScript callbacks.

During that time, another request to /health may also be delayed—even if its handler only needs to return a short status message.

This distinction matters because a slow endpoint can affect the performance of endpoints that have no direct dependency on it.

Node.js is particularly effective for I/O-heavy applications, but CPU-intensive work and long-running synchronous callbacks can undermine that advantage. See the official Node.js guide to avoiding event-loop and worker-pool blocking.

1. Find the Blocking Operation Before Changing the Code

Start by identifying which requests are slow and whether the delay comes from JavaScript execution, database activity, or another dependency.

Measure response times for individual routes. Record timestamps around expensive operations, including database calls, file access, external API requests, serialization, and report generation.

For example:

app.get("/products", async (req, res, next) => {
  const start = performance.now();

  try {
    const products = await getProducts();
    console.log(
      "getProducts duration:",
      performance.now() - start
    );
    res.json(products);
  } catch (error) {
    next(error);
  }
});

This example requires importing performance from Node.js’s node:perf_hooks module.

The measurement helps identify how long getProducts() takes, but it does not automatically tell you whether the delay is caused by a database, network, or CPU work inside the function.

For more reliable diagnosis, combine route-level timings with CPU profiling and event-loop delay measurements. Avoid logging every request synchronously in production, because logging itself can add overhead.

2. Replace Synchronous File Operations

A common source of event-loop blocking is using synchronous filesystem methods inside request handlers.

Problematic example:

const fs = require("node:fs");

app.get("/config", (req, res) => {
  const config = fs.readFileSync(
    "./config.json",
    "utf8"
  );
  res.type("json").send(config);
});

// readFileSync() prevents the current JavaScript execution from continuing until the file read completes.
// For request-time file access, use the asynchronous API:

const fs = require("node:fs/promises");

app.get("/config", async (req, res, next) => {
  try {
    const config = await fs.readFile(
      "./config.json",
      "utf8"
    );
    res.type("json").send(config);
  } catch (error) {
    next(error);
  }
});

This lets the event loop handle other work while the file operation is pending. The filesystem operation may still take time, and excessive concurrent file requests can create resource pressure, but the main JavaScript thread does not have to wait synchronously for each read.

If the configuration rarely changes, loading it during startup or caching a validated version may be more efficient than reading it on every request.

Express’s production performance guidance recommends avoiding synchronous functions in production request handling.

3. Move CPU-Intensive Work Off the Event Loop

Some tasks cannot be made faster merely by adding async and await. Examples include image transformations, complex calculations, large data transformations, and computationally expensive document processing.

Consider:

app.post("/calculate", (req, res) => {
  const result = calculateComplexResult(req.body);
  res.json(result);
});

If calculateComplexResult() performs heavy synchronous computation, the event loop remains occupied until it finishes.

For substantial CPU-bound tasks, Node.js worker threads can execute JavaScript in parallel with the main thread.

A worker can receive the required input, perform the calculation, and return the result without making the Express event loop perform the entire computation itself.

However, do not create a new worker for every request without limits. Worker startup, communication, and copying data all have costs. A managed worker pool is generally more appropriate when many requests need the same type of expensive computation.

Official guidance: Express.js performance best practices and Node.js worker threads.

NOT SURE WHAT TO DO NEXT?

Let’s Figure It Out.

Tell us what you’re working on and we’ll help you identify the right next step.

Talk to an Expert

4. Avoid Large Synchronous JSON Operations

JSON processing can also become a bottleneck when request bodies or response objects are very large.

For example:

const output = JSON.stringify(hugeObject);

res.send(output);

JSON.stringify() executes synchronously. If hugeObject contains a very large amount of data, serialization can occupy the event loop long enough to delay other requests.

The same issue can occur with JSON.parse() when processing large strings.

Practical fixes include:

  • Limit request-body size to what the endpoint actually needs.
  • Return paginated results instead of entire datasets.
  • Avoid duplicating large objects during transformations.
  • Use streaming where the data format and client support it.
  • Move expensive transformations to worker threads when appropriate.

An asynchronous route handler does not make every operation inside it non-blocking. The cost of synchronous JavaScript still matters.

5. Distinguish Blocking Code From Slow Database Queries

Not every slow Express.js API is suffering from event-loop blocking.

// Consider:
app.get("/orders", async (req, res, next) => {
  try {
    const orders = await db.query(
      "SELECT * FROM orders"
    );
    res.json(orders.rows);
  } catch (error) {
    next(error);
  }
});

If the database takes several seconds to execute the query, the endpoint will remain slow even though the JavaScript thread can process other work while waiting.

Measure the database operation separately. Check query plans, indexes, returned row counts, connection-pool saturation, and whether the query retrieves more data than the endpoint requires.

Avoid solving a database bottleneck by moving the query into a worker thread. That will not make the database execute the query faster.

If the endpoint is slow because of repeated queries, inefficient data retrieval, or an overloaded database, address those causes directly.

6. Handle External API Calls Without Blocking Other Requests

External service calls can also increase response times.

Use an asynchronous HTTP client and set reasonable timeouts. Where possible, avoid unnecessary sequential dependencies.

For example, if two independent services must provide data, running their requests concurrently may reduce total waiting time:

const [profile, preferences] = await Promise.all([
  fetchProfile(userId),
  fetchPreferences(userId)
]);

This only helps when both operations are genuinely independent and the underlying functions are asynchronous. It does not make synchronous CPU work non-blocking.

Also consider failure handling: Promise.all() rejects if one of its promises rejects. Use appropriate error handling and decide whether the endpoint requires both results or can return partial data.

7. Measure Event-Loop Delay and CPU Usage

If multiple endpoints become slow simultaneously, investigate whether the main thread is being blocked.

// Node.js provides monitorEventLoopDelay() through node:perf_hooks:

const {
  monitorEventLoopDelay
} = require("node:perf_hooks");

const histogram = monitorEventLoopDelay({
  resolution: 20
});

histogram.enable();

setInterval(() => {
  console.log({
    meanMs: histogram.mean / 1e6,
    maxMs: histogram.max / 1e6
  });
  histogram.reset();
}, 10000);

This is a diagnostic example, not a complete production monitoring setup. The interval should be managed appropriately, and the output should be exported to a monitoring system rather than relying on console logs alone.

Elevated event-loop delay can indicate that the event loop is not getting timely opportunities to process callbacks. It is not proof of one particular cause, so correlate it with CPU profiles, request timings, and application logs.

Use the Node.js Performance Hooks documentation for the available measurements.

8. Avoid Increasing Timeouts as the First Fix

Increasing an API timeout may prevent a client from giving up too early, but it does not reduce the time required to complete the work.

If blocking operations are consuming the event loop, longer timeouts can allow requests to remain pending while other users continue to experience delays.

Instead, establish a baseline, identify the slow operation, make one targeted change, and repeat the same measurement. Test under representative concurrency, because an endpoint that looks fast with one request may behave differently when multiple clients request expensive work simultaneously.

If a single expensive request affects unrelated routes, investigate event-loop blocking. If only one endpoint is slow while other routes remain responsive, investigate its database queries, downstream dependencies, and response size as well.

Conclusion

To fix slow Express.js API responses caused by blocking operations, determine whether the bottleneck is synchronous JavaScript, CPU-heavy processing, filesystem access, database latency, or an external service.

Replace synchronous request-time I/O with asynchronous APIs, move substantial CPU-intensive tasks to worker threads or a managed worker pool, and reduce unnecessarily large JSON operations. Measure event-loop delay and individual operation timings so that optimizations address the real cause.

The objective is not to make every route asynchronous in appearance. It is to keep event-loop callbacks short, avoid unnecessary waiting, and prevent one expensive request from degrading the responsiveness of the entire application.

FAQs

Why are all my Express.js API endpoints slow when only one route is doing heavy work?

A route may be executing synchronous CPU-intensive code on the main event loop. While that code runs, other JavaScript callbacks—including handlers for unrelated routes—cannot execute. Profile the application and look for long-running synchronous functions. If the work is CPU-heavy, consider a worker thread or a managed worker pool.

Does using async/await prevent blocking in Express.js?

No. async and await help structure asynchronous operations, but they do not automatically make synchronous code non-blocking. A CPU-intensive function called inside an async handler can still block the event loop. Use asynchronous APIs for I/O and offload substantial CPU-bound work when appropriate.

Should I use worker threads to fix every slow Express.js API?

No. Worker threads are most useful for CPU-intensive JavaScript, such as expensive calculations or transformations. They are not a general fix for slow database queries, network latency, or an overloaded external service. Measure the bottleneck first and choose the solution that addresses it.

Can synchronous file operations slow down an Express.js server?

Yes. Methods such as fs.readFileSync() prevent the current JavaScript execution from continuing until the file operation completes. In request handlers, prefer asynchronous filesystem APIs or load infrequently changing files during startup when appropriate. This reduces unnecessary blocking of the main event loop.

How do I measure Express.js API response-time improvements reliably?

Record baseline latency for individual routes, measure major operations separately, and monitor event-loop delay and CPU usage. Repeat tests under comparable request volume and payload sizes after each change. Look at percentile latency as well as averages, because a low average can hide slow responses experienced by a portion of users.

NEED HELP WITH THIS?

Let’s Talk About Your Business

Not sure which approach is right for your business? Get a free consultation with our team.

Get Free Consultation

One Response

Leave a Reply

Your email address will not be published. Required fields are marked *

NOT SURE WHAT TO DO NEXT?

Let's Figure It Out.

Tell us what you’re working on and we’ll help you identify the right next step.

NEED HELP WITH THIS?

Let's Talk About Your Business

Not sure which approach is right for your business? Get a free consultation with our team.