Rack (Per-Request) Memory Usage

Author: Samuel Williams When: Wednesday, 24 August 2011

I was recently converting some code from Ruby 1.8.7 to Ruby 1.9.2 and I wanted to check memory usage. I also wanted to check for memory leaks, which can be a problem in garbage collected languages.

The following code can be used to check memory usage after each request. It is designed to be used in conjunction with other rack middleware:

class MemoryUsage
	def initialize(app)
		print_memory_usage!
		
		@app = app
	end
	
	def print_memory_usage!
		$stderr.puts "Memory Usage: " + `ps -o rss= -p #{Process.pid}`
	end
	
	def call(env)
		result = @app.call(env)
		
		GC.start
		
		print_memory_usage!
		
		return result
	end
end

use MemoryUsage

Once you've got this up and running, you can use ab to stress test the website. If memory usage keeps on increasing over time for the same load level, you probably have a memory leak.

Comments

Leave a comment

Please note, comments must be formatted using Markdown. Links can be enclosed in angle brackets, e.g. <www.codeotaku.com>.