Crystal Cluster class plus SO_REUSEPORT to serve millions of HTTP requests per second

Crystal lang is a fast language that generate LLVM IR. With this Cluster class and SO_REUSEPORT socket option, Crystal can serve millions of HTTP requests per second. To do this, we need to compile Crystal with SO_REUSEPORT. On Linux, this socket option allows multiple sockets on the same host to bind to the same port : it improves the performance of a multithreaded network app on a multicore system. This is available on Linux > 3.9 .

Compile Crystal with SO_REUSEPORT

To compile Crystal with SO_REUSEPORT, you can follow our tutorial

Create the Cluster class

Now, create a file named and add this :

class Cluster

    def self.fork (env : Hash)
        env["FORKED"] = "1"
        Process.fork {, nil, env, true, false, true, true, true, nil ) }

    def self.master?
     (ENV["FORKED"]? || "0") == "0"
    def self.worker?
     (ENV["FORKED"]? || "0") == "1"


Use the Cluster class with the Http server

Create a file and add in it :

require "http/server"
require "./"

if Cluster.master?
        # IN MASTER
        # Init service
        nbr = 4 # Cluster number
        while(nbr > 0)
                Cluster.fork ({"id" => nbr.to_s})
                nbr -= 1
        # IN WORKER
        # start http server
        server = do |context|
                context.response.content_type = "text/plain"
                context.response.print "Hello world! The time is #{}"
        puts "Listening on"

To adjust the number of thread, just change the value of nbr


To benchmark you clustered Http server, you can use the Apache tool ab or wrk. You can install ab on Debian/Ubuntu with this command :

apt-get install apache2-utils

Now, you can benchmark your clustered server :

ab -n 1000 -c 5

Command line detailled :

  • -n 1000: ab will send 1000 requests to server
  • -c 5 : 5 is the concurrency number, ab will send 5 number of multiple requests to perform at a time

Problem with the Cluster class

If you have problems or difficulties with the Cluster class, don't hesitate to say it in comments, I'll try to help you.