O'Reilly logo

Ruby Performance Optimization by Alexander Dymo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Fork to Run Heavy Jobs

Cycling long-running Ruby instances helps to deal with sudden increases in memory consumption. But often we know beforehand that the code we’re going to execute will need memory. For example, our database query returned 100,000 rows, and we need to compute complex statistics based on that data.

We can let that memory-heavy operation run and then let our infrastructure restart the Ruby process. But there’s a better solution. We can fork our process and execute the memory-heavy code in the child process. This way, only the child process will grow in memory, and when it exits, the parent process remains unaffected.

The simplest possible implementation looks like this:

 
pid = fork ​do
 
heavy_function
 
end
 
Process::waitpid(pid) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required