Skip to content

Instantly share code, notes, and snippets.

@marianposaceanu
Last active December 19, 2015 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save marianposaceanu/5892298 to your computer and use it in GitHub Desktop.
Save marianposaceanu/5892298 to your computer and use it in GitHub Desktop.
Using out of band GC via OobGC.

Unicorn tweaks

Using out of band GC via OobGC.

Credits

Example config.ru

require_dependency 'unicorn/oob_gc'
GC.disable # Don't run GC during requests
use(Unicorn::OobGC, 40) # Only GC once every n requests

# UnicornSlayer kills overgrown workers
require_dependency 'unicorn/unicorn_slayer.rb'
use(UnicornSlayer::MaxRequests, 1000)
use(UnicornSlayer::Oom, 400 * 1024, 1)

# GC ever two requests that hit /expensive/foo or /more_expensive/foo
# in your app.  By default, this will GC once every 5 requests
# for all endpoints in your app
# from http://unicorn.bogomips.org/Unicorn/OobGC.html
use(Unicorn::OobGC, 2, %r{\A/(?:expensive/foo|more_expensive/foo)})
# # your config.ru
# require 'unicorn_slayer'
# use UnicornSlayer::MaxRequests, 1000
# use UnicornSlayer::Oom, 400 * 1024
module UnicornSlayer
module Kill
def quit
sec = (Time.now - @process_start).to_i
warn "#{self.class} send SIGQUIT (pid: #{Process.pid})\talive: #{sec} sec"
Process.kill :QUIT, Process.pid
end
end
class Oom
include Kill
def initialize(app, memory_size= 512 * 1024, check_cycle = 10)
@app = app
@memory_size = memory_size
@check_cycle = check_cycle
@check_count = 0
end
def rss
`ps -o rss= -p #{Process.pid}`.to_i
end
def call(env)
@process_start ||= Time.now
if (@check_count += 1) % @check_cycle == 0
@check_count = 0
quit if rss > @memory_size
end
@app.call env
end
end
class MaxRequests
include Kill
def initialize(app, max_requests = 1000)
@app = app
@max_requests = max_requests
end
def call(env)
@process_start ||= Time.now
quit if (@max_requests -= 1) == 0
@app.call env
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment