Save 36% for Black Friday! Learn more

Limit Webpacker RAM on compile for production

Chris Oliver

December 12, 2019

If you're deploying Rails to production with Webpacker, you might run into a Compilation failed error from Webpacker.

Often this happens because Webpacker runs out of RAM and the operating system kills the command for using too many resources. Modern VPS servers run on SSDs and don't enable a swap file by default because it can cause additional wear on the SSD and significantly reduce the lifetime of the drive. A side effect of this is the operating system is more aggressive with killing processes when it runs out of RAM.

To confirm this is your problem, you'll want to make sure that compiling assets doesn't throw any errors because of broken code. Update config/webpacker.yml to have webpack_compile_output: true and redeploy. If you are getting an error now, then you probably just need to fix that and you aren't running out of RAM.

Getting the "Compilation failed" error from Webpacker?

Try setting NODE_OPTIONS="--max-old-space-size=350" in your environment variables.

What this will do is tell Node.js that it can only use up to 350MB of RAM. This applies to your yarn install and webpack compile steps and will force it to run within those limits.

If you set this number too low, you'll get an error that Node.js was unable to allocate memory. You can try raising the max-old-space-size number until your compiles are working again.

This is really helpful if you're compiling webpack assets on a 1GB of RAM server and already have Rails, Sidekiq, Postgres, Redis, etc running. The free RAM will only be a portion of the 1GB left, so in our case, we could set it to 350MB of RAM to keep the OS from killing our webpack precompile.

P.S. You might enjoy following me on Twitter.


Comments