How to Use JRuby and MRI in One Project
In 2013, I worked on a project that needed quick web responses and substantial computation in the background. I was considering MRI Ruby for its familiar ecosystem and JRuby for its performance on long-running processes.
I tried using both interpreters in the same project. It worked well for our application, though managing two Ruby environments brought extra work.
The Problem: Different Needs, Different Strengths
The application had two components with different performance requirements:
The User-Interactive Section: This handled typical web requests - user authentication, displaying data, form submissions. Users expected fast response times, and we needed something that could start up quickly and handle requests efficiently.
Background Jobs: These were computationally intensive tasks - mathematical optimization problems, essentially NP-hard problems we solved using heuristics. These jobs were CPU and memory heavy, often running for minutes or hours.
MRI Ruby (we were using 2.0 and later 2.1) suited our web application: it started quickly, handled short-lived processes well, and worked with the gems we knew. Its Global Interpreter Lock meant true parallel processing was impossible, though, and memory management on long-running processes wasn't ideal.
JRuby 1.7.x offered true threading without GIL constraints. For our long-running processes, the JVM garbage collector also gave us much better memory management.
The Architecture: Best Tool for Each Job
Here's how we structured the application:
Web Frontend: MRI Ruby + Unicorn + Nginx
For the user-facing parts, we kept MRI Ruby 2.0 (and later 2.1):
# Gemfile (MRI-specific gems)
source 'https://rubygems.org'
gem 'rails', '~> 4.0'
gem 'pg'
gem 'unicorn'
# MRI-specific gems that wouldn't work on JRuby
gem 'nokogiri'
gem 'sqlite3', groups: [:development, :test]
We used Unicorn behind Nginx, the standard Rails deployment stack in 2013-2014. It handled our web requests well. Unicorn's process-based architecture suited MRI: we avoided threading problems, and if one process crashed, the others kept serving requests.
Our Unicorn configuration was typical for the time:
# config/unicorn.rb
worker_processes 4
timeout 30
preload_app true
listen "/tmp/unicorn_myapp.sock", :backlog => 64
if GC.respond_to?(:copy_on_write_friendly=)
GC.copy_on_write_friendly = true
end
before_fork do |server, worker|
ActiveRecord::Base.connection.disconnect!
end
after_fork do |server, worker|
ActiveRecord::Base.establish_connection
end
This gave us fast response times and easy deployment. When we needed to push fixes or small changes, we could restart the web frontend quickly without affecting the background jobs.
Background Processing: JRuby + Sidekiq
For the computational work, we used JRuby 1.7 with Sidekiq.
Mike Perham had released Sidekiq in early 2012, and by 2013 it was becoming a popular choice for background jobs. Its threading model suited our JRuby setup: Sidekiq used threads rather than processes.
# Gemfile for JRuby workers
source 'https://rubygems.org'
gem 'sidekiq'
gem 'activerecord'
gem 'activerecord-jdbc-adapter'
gem 'jdbc-postgres'
# Our computational gems that worked well on JRuby
gem 'matrix'
gem 'concurrent-ruby'
The difference showed up during long computations. MRI could accumulate memory fragmentation over several hours, while JRuby's threading and JVM garbage collector handled these workloads more efficiently.
Here's what a typical background job looked like:
class OptimizationWorker
include Sidekiq::Worker
def perform(problem_data)
# This might run for 30+ minutes
optimizer = HeuristicOptimizer.new(problem_data)
# JRuby's true threading allows us to parallelize
# parts of the computation
result = optimizer.solve_with_parallel_processing
# Save results back to shared database
OptimizationResult.create!(
problem_id: problem_data['id'],
solution: result.to_json,
completed_at: Time.current
)
end
endThe Shared Foundation: ActiveRecord Models
We kept the business logic in shared ActiveRecord models. The MRI web frontend and JRuby workers could then use the same data structures without duplicating them.
# app/models/optimization_problem.rb
# This model was used by both MRI and JRuby
class OptimizationProblem < ActiveRecord::Base
validates :parameters, presence: true
def enqueue_for_processing
# Called from MRI web frontend
OptimizationWorker.perform_async(self.attributes)
end
def processing_complete?
OptimizationResult.exists?(problem_id: self.id)
end
end
With both interpreters connected to the same PostgreSQL database, we didn't run into data consistency issues. The MRI frontend created optimization problems and enqueued jobs; the JRuby workers picked them up and saved the results.
Database Configuration: One Database, Two Interpreters
We used the same database for both sides but with different connection adapters:
# MRI side: database.yml
production:
adapter: postgresql
database: myapp_production
username: myapp
password: <%= ENV['DATABASE_PASSWORD'] %>
host: localhost
# JRuby side: database.yml
production:
adapter: jdbcpostgresql
database: myapp_production
username: myapp
password: <%= ENV['DATABASE_PASSWORD'] %>
host: localhost
The JDBC adapter for JRuby gave us better performance for long-running database connections. The standard PostgreSQL adapter worked well for MRI's shorter request cycles.
Deployment and Process Management
We managed the two Ruby interpreters with separate service scripts:
# /etc/init.d/myapp_web (MRI)
#!/bin/bash
USER="deploy"
DAEMON="unicorn"
ROOT_DIR="/var/www/myapp"
DAEMON_OPTS="-c $ROOT_DIR/config/unicorn.rb -D"
case "$1" in
start)
su - $USER -c "$DAEMON $DAEMON_OPTS"
;;
stop)
su - $USER -c "kill `cat /tmp/unicorn_myapp.pid`"
;;
restart)
su - $USER -c "kill -USR2 `cat /tmp/unicorn_myapp.pid`"
;;
esac# /etc/init.d/myapp_workers (JRuby)
#!/bin/bash
USER="deploy"
ROOT_DIR="/var/www/myapp"
JRUBY_OPTS="-J-Xmx2g -J-Xms1g"
case "$1" in
start)
su - $USER -c "cd $ROOT_DIR && jruby $JRUBY_OPTS -S bundle exec sidekiq -d"
;;
stop)
su - $USER -c "kill `cat /var/www/myapp/tmp/pids/sidekiq.pid`"
;;
esacPerformance Results
Our web frontend maintained sub-100ms response times for typical requests, as we'd expected from the MRI/Unicorn setup. The larger improvements were in the JRuby background jobs.
Memory usage changed the most. MRI workers processing hour-long optimization jobs could reach 800MB+ and show memory fragmentation. JRuby workers stayed around 400-500MB, with stable performance throughout each job.
CPU utilization was better too. JRuby's ability to truly parallelize computation within a single process meant we could solve optimization problems 2-3x faster than equivalent MRI implementations.
Challenges We Encountered
There were costs to running both interpreters:
Gem Compatibility: Not every gem worked on both interpreters. We had to maintain separate Gemfiles and occasionally find JRuby-specific alternatives for certain dependencies.
Development Environment: New developers needed to set up both MRI and JRuby locally. We used RVM to manage both versions:
rvm install 2.1.0
rvm install jruby-1.7.14
# Create separate gemsets
rvm use 2.1.0@myapp_web --create
rvm use jruby-1.7.14@myapp_workers --create
Debugging: Troubleshooting issues that crossed the interpreter boundary was tricky. We had to be very careful about our Redis job serialization and database connection handling.
Deployment Complexity: We had to plan deployments around which changes affected each interpreter, rather than deploying everything at once.
Why This Worked in 2013-2014
The versions available in 2013-2014 suited this arrangement. MRI 2.0 and 2.1 worked well for web applications but struggled with intensive background processing. JRuby 1.7 had good MRI compatibility and performed better on the workloads we gave it.
Sidekiq was relatively new, and its threaded job processing worked well with JRuby for our computations.
The Rails ecosystem had also stabilized around certain deployment patterns. Unicorn + Nginx was the standard, and most gems we needed had mature versions that worked reliably across interpreters.
Lessons Learned
Using both interpreters helped because the web requests and background jobs had such different requirements. We could choose an interpreter for each part of the application.
I'd consider this approach when:
- You have genuinely different performance requirements (fast web responses vs. long-running processes)
- Your team is comfortable managing the additional complexity
- Your deployment infrastructure can handle multiple Ruby environments
- The performance gains justify the operational overhead
For most applications, I'd still use one interpreter. Our workload justified the extra complexity, and combining MRI and JRuby gave us performance we couldn't get from either alone. It also made me more willing to consider a combination of tools when a single choice didn't fit the whole application.