Skip to content

Instantly share code, notes, and snippets.

@8bitDesigner
Last active December 11, 2015 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 8bitDesigner/4550838 to your computer and use it in GitHub Desktop.
Save 8bitDesigner/4550838 to your computer and use it in GitHub Desktop.
Bare bones cluster/domain implementation.

What does this do?

  • Spawns as many workers with your web server as you have CPUS
  • The domain around the worker will catch any errors the worker allows to escape, and escaped errors are punishable by death.
  • If a worker crashes, it's rebooted
  • If a worker exits cleanly (suicides), it's not replaced
  • Sending "SIGINT" to the master process will gracefully shutdown the child instances and then exit the master process
cluster = require 'cluster'
os = require 'os'
if cluster.isMaster
timeout = []
# Emitted when a worker is removed from the load balancer
cluster.on 'disconnect', (worker) ->
# If we don't see an exit event in the next 5 seconds we have a
# stuck process. Kill it with fire.
timeout[worker.id] = setTimeout worker.process.exit, 5000
# Emitted when a worker process exits
cluster.on 'exit', (worker) ->
# worker.suicide will be false for crashes, true for requested exits
if not worker.suicide then cluster.fork() # Reboot crashed children
else clearTimeout timeout[worker.id] # Clear force quit timer
# Trap sigint and use it to disconnect workers from the load balancer
# Node will shutdown when it empties out the event loop afterwards
process.on "SIGINT", cluster.disconnect
# spawn an instance for each CPU
cluster.fork() for cpu in os.cpus()
else
worker = cluster.worker
domain = require('domain').create()
# Wrap our spawned server so we can manage errors it doesn't catch
domain.on "error", worker.process.exit
domain.run -> require('./your/http/server')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment