samanime
samanime

Reputation: 26527

Express server takes 500ms to return a 304 response

I have a very simple express server. It has compression and uses static-serve to serve files. I have cacheControl set to false, so it only uses the ETag.

The server will return a 304 for the files (which is desired), but it takes about 500ms to do so. That's the same amount of time it takes to actually send the file.

Is there some configuration I can do (outside of things like Varnish and nginx) to speed it up?

The server only has about 6 different files to serve up, all static.

Express server code:

const path = require('path');
const express = require('express');
const compression = require('compression');
const serveStatic = require('serve-static');

const PORT = process.env.PORT || 9095;

const app = express();

app.use(compression({ threshold: 0 }));

app.use(/regex pattern here/, serveStatic(path.join(__dirname, '../dist/client/assets'), { cacheControl: false }));

app.listen(PORT, (error) => {
  console.log(error || `Listening on port ${PORT}`);
});

Upvotes: 0

Views: 438

Answers (2)

samanime
samanime

Reputation: 26527

It turns out the trick is to run the express server with NODE_ENV=production.

Apparently, this tells Express to do a number of optimizations, one of which seems to do exactly what I wanted. Went from about 500ms to about 40ms to return a 304, which is much better.

Reference: https://expressjs.com/en/advanced/best-practice-performance.html#in-environment

Upvotes: 1

ponury-kostek
ponury-kostek

Reputation: 8060

You should use nginx or something similar to serve static content because node serve-static module need to calculate hash from file content. So this is even slower than just serving file especially on local machine. Here is deep dive into serve-static mechanics https://evanhahn.com/express-dot-static-deep-dive/

Upvotes: 1

Related Questions