Building a Simple HTTP Server

Learn how to benchmark a simple HTTP server that uses the cluster module and provides auto restarting of failed workers.

Creating an HTTP server using the cluster module

Let’s now start working on an example. Let’s build a small HTTP server, cloned and load balanced using the cluster module. First of all, we need an application to scale, and for this example, we don’t need too much, just a very basic HTTP server.

So, let’s create a file called app.js containing the following code:

Press + to interact
import { createServer } from 'http'
const { pid } = process
const server = createServer((req, res) => {
// simulates CPU intensive work
let i = 1e7; while (i > 0) { i-- }
console.log(`Handling request from ${pid}`)
res.end(`Hello from ${pid}\n`)
})
server.listen(8080, () => console.log(`Started at ${pid}`))

The HTTP server we just built responds to any request by sending back a message containing its process identifier (PID); this is useful for identifying which instance of the application is handling the request. In this version of the application, we have only one process, so the PID that we see in the responses and the logs will always be the same.

Also, to simulate some actual CPU work, we perform an empty loop 10 million times: without this, the server load would be almost insignificant and it’ll be quite hard to draw conclusions from the benchmarks we’re going to run.

Note: The app.js module we create here is just a simple abstraction for a generic web server. We’re not using a web framework like Express or Fastify for simplicity, but we can rewrite these examples using a web framework of our choice.

Try it yourself

We can now check if everything works as expected by executing the following command.

Press + to interact
node app.js

We can also try to measure the requests per second that the server is able to handle in one process. For this purpose, we can use a network benchmarking tool such as the autocannon package. Open a new terminal and execute the following command:

Press + to interact
cd app && npx autocannon -c 200 -d 10 http://localhost:8080

The preceding command will load the server with 200 concurrent connections for 10 seconds. As a reference, the result we got on our machine (a 2.5 GHz quad-core Intel Core i7 ...

Get hands-on with 1400+ tech skills courses.