Ractors
suggest changeCRuby has a Global VM Lock (GVL): only one thread runs Ruby code at a time, so threads don't speed up CPU-bound work. Ractors (Ruby actors, added in Ruby 3.0) get around that. Each ractor has its own lock, so several ractors run Ruby code in parallel on different CPU cores.
The price is isolation. Ractors don't share mutable objects. They talk by sending messages, and only immutable (shareable) objects can be seen by more than one ractor. This rules out data races by design, but it also means a lot of ordinary Ruby code and many gems don't work inside a ractor.
This article covers:
- creating ractors and getting their result with
#valueand#join - sending messages with
send/<<andRactor.receive - shareable vs. unshareable objects, copying and moving
Ractor.make_shareableandRactor.shareable_procRactor::PortandRactor.selectfor communication- error handling
- a worker pool for CPU-bound jobs
- what doesn't work inside a ractor
The examples were run with Ruby 4.0. The API changed in Ruby 4.0 (it was in development as 3.5): Ractor.yield and Ractor#take were removed and replaced by Ractor::Port, Ractor#join and Ractor#value. See Migrating from the Ruby 3.x API at the end if you maintain older code.
Creating a ractor
Ractor.new takes a block and runs it in a new ractor. #value waits for the block to finish and returns its result:
r = Ractor.new do
21 * 2
end
p r.value
p Ractor.main?
p Ractor.new { Ractor.main? }.value
a1.rb:1: warning: Ractor API is experimental and may change in future versions of Ruby.
42
true
false
The program starts in the main ractor (Ractor.main? is true there). Each ractor runs in its own native thread.
The first Ractor.new prints a warning, because ractors are still experimental. Turn it off with Warning[:experimental] = false or by running ruby -W:no-experimental. The remaining examples set Warning[:experimental] = false so the output stays readable.
If you only need to wait for a ractor to finish and don't care about its result, use #join:
Warning[:experimental] = false
r = Ractor.new { sleep 0.1; puts "worker finished" }
r.join
puts "main continues"
worker finished
main continues
Passing arguments
The block of a ractor is isolated: it can't use local variables from the outer scope. Pass values as arguments to Ractor.new instead. They become the block's parameters. You can also give the ractor a name:
Warning[:experimental] = false
r = Ractor.new(10, 20, name: "adder") do |a, b|
a + b
end
p r.name
p r.value
"adder"
30
Using an outer variable inside the block raises an error right away, when the ractor is created:
name = "Ruby"
begin
Ractor.new { puts name }
rescue ArgumentError => e
puts "#{e.class}: #{e.message}"
end
r = Ractor.new(name) { |n| "hello #{n}" }
p r.value
ArgumentError: can not isolate a Proc because it accesses outer variables (name).
"hello Ruby"
The same check rejects yield inside a ractor block, since that would call a block owned by another ractor.
Sending and receiving messages
Every ractor has an inbox. Other ractors put messages in it with send (or its alias <<), and the ractor takes them out with Ractor.receive, which waits until a message arrives:
Warning[:experimental] = false
r = Ractor.new do
total = 0
while (msg = Ractor.receive) != :done
total += msg
end
total
end
r.send(1)
r << 2
r.send(3)
r << :done
p r.value
6
send doesn't wait for the message to be received. Messages from one sender arrive in the order they were sent. Using a symbol like :done (or :stop) as a "no more work" marker is a common pattern.
Shareable and unshareable objects
An object is shareable if several ractors can safely use it at the same time. Ractor.shareable? tells you whether an object is:
p Ractor.shareable?(1)
p Ractor.shareable?(:sym)
p Ractor.shareable?(nil)
p Ractor.shareable?("text")
p Ractor.shareable?("text".freeze)
p Ractor.shareable?([1, 2].freeze)
p Ractor.shareable?(["a", "b"].freeze)
p Ractor.shareable?(String)
p Ractor.shareable?(1..10)
Point = Data.define(:x, :y)
p Ractor.shareable?(Point.new(1, 2))
p Ractor.shareable?(Point.new("a", 2))
true
true
true
false
true
true
false
true
true
true
false
The rules:
- immutable values are shareable: integers, floats, symbols,
nil,true,false - frozen objects are shareable only if everything they refer to is shareable too.
["a", "b"].freezeisn't, because the strings inside are still mutable. The same goes for theDatainstance holding"a". - classes and modules are shareable (but see the limits on their instance variables below)
Ractorobjects andRactor::Portobjects are shareable
Unshareable objects are copied
When you send an unshareable object, the receiver gets a deep copy. Changes made by the receiver don't affect the original:
Warning[:experimental] = false
r = Ractor.new do
arr = Ractor.receive
arr << "added inside"
arr
end
list = ["original"]
r.send(list)
copy = r.value
p list
p copy
p list.equal?(copy)
["original"]
["original", "added inside"]
false
Shareable objects aren't copied. The receiver gets a reference to the very same object:
Warning[:experimental] = false
shared = Ractor.make_shareable(["a", "b"])
unshared = ["a", "b"]
r = Ractor.new { 2.times.map { Ractor.receive.object_id } }
r << shared << unshared
ids = r.value
p ids[0] == shared.object_id
p ids[1] == unshared.object_id
true
false
Copying a large structure takes time and memory, so it pays to send shareable data, or small messages, when you can.
Moving instead of copying
send(obj, move: true) hands the object over without copying it. The sender loses access: any method call on the old reference raises Ractor::MovedError:
Warning[:experimental] = false
r = Ractor.new do
buf = Ractor.receive
buf << " world"
buf
end
big = +"hello"
r.send(big, move: true)
p r.value
begin
big.size
rescue Ractor::MovedError => e
puts "#{e.class}: #{e.message}"
end
"hello world"
Ractor::MovedError: can not send any methods to a moved object
Use move: true for large buffers you're done with, for example a big string you've read from a file and want to hand to a worker.
Ractor.make_shareable
Ractor.make_shareable(obj) deep-freezes an object and everything reachable from it, then returns it. The object is changed in place:
config = { host: "localhost", ports: [80, 443], tags: ["web"] }
frozen = Ractor.make_shareable(config)
p frozen.equal?(config)
p Ractor.shareable?(config)
p config.frozen?, config[:ports].frozen?, config[:tags][0].frozen?
begin
config[:tags] << "db"
rescue FrozenError => e
puts e.message
end
copy = Ractor.make_shareable({ list: [+"x"] }, copy: true)
p Ractor.shareable?(copy)
true
true
true
true
true
can't modify frozen Array: ["web"]
true
With copy: true it freezes a deep copy and leaves the original alone. This is also useful outside of ractors, as a deep freeze. See Values and references and Immutability.
Constants, globals and class state
Code inside a non-main ractor can't reach mutable state that other ractors could also reach. These accesses raise Ractor::IsolationError:
Warning[:experimental] = false
LIMIT = 10 # Integer: shareable
NAMES = %w[ann bob].freeze # frozen array of unfrozen strings: not shareable
COLORS = Ractor.make_shareable(%w[red green])
$counter = 0
def show(label, r)
puts "#{label}: #{r.value.inspect}"
rescue Ractor::RemoteError => e
puts "#{label}: #{e.cause.class}: #{e.cause.message}"
end
show("LIMIT", Ractor.new { LIMIT })
show("COLORS", Ractor.new { COLORS })
show("NAMES", Ractor.new { NAMES })
show("$counter", Ractor.new { $counter })
show("$stdout", Ractor.new { $stdout.puts("hi from a ractor"); :ok })
show("define", Ractor.new { Object.const_set(:NEW_ONE, [1]); :ok })
hi from a ractor
LIMIT: 10
COLORS: ["red", "green"]
NAMES: Ractor::IsolationError: can not access non-shareable objects in constant Object::NAMES by non-main Ractor.
$counter: Ractor::IsolationError: can not access global variable $counter from non-main Ractor
$stdout: :ok
define: Ractor::IsolationError: can not set constants with non-shareable objects by non-main Ractors
(Each failing ractor also prints a "terminated with exception" report to stderr, not shown here.)
So inside a ractor:
- constants are fine if they hold shareable values. Freeze constants with
Ractor.make_shareable, or put# shareable_constant_value: literalat the top of the file to make Ruby do it for literal constants. - most global variables are off limits.
$stdout,$stderrand$stdinare special: each ractor has its own, soputsworks. - instance variables of classes and modules can be read only if they hold shareable values
Class-level instance variables are a common way to store configuration and caches, so they're often the first thing that breaks:
Warning[:experimental] = false
class Config
@settings = { debug: true } # unshareable class-level ivar
@limit = 5 # shareable value
class << self
attr_reader :settings, :limit
end
end
def show(label, r)
puts "#{label}: #{r.value.inspect}"
rescue Ractor::RemoteError => e
puts "#{label}: #{e.cause.class}: #{e.cause.message}"
end
show("limit", Ractor.new { Config.limit })
show("settings", Ractor.new { Config.settings })
show("require", Ractor.new { require "json"; JSON.generate({ ok: true }) })
show("local", Ractor.new { Ractor[:cache] = []; Ractor[:cache] << 1; Ractor[:cache] })
show("memo", Ractor.new { Ractor.store_if_absent(:conn) { "connection" } })
limit: 5
settings: Ractor::IsolationError: can not get unshareable values from instance variables of classes/modules from non-main Ractors (@settings from Config)
require: "{\"ok\":true}"
local: [1]
memo: "connection"
The last three lines show what you can do instead:
requireworks inside a ractor in Ruby 3.4 and later (the main ractor does the actual loading)Ractor[:key]is ractor-local storage, a per-ractor replacement for a globalRactor.store_if_absent(:key) { ... }sets ractor-local storage once, which is handy for a per-ractor cache or connection
Shareable procs
A normal Proc can't be shared, because it can see the local variables of the scope where it was created. Ruby 4.0 adds Ractor.shareable_proc and Ractor.shareable_lambda, which create a proc that's isolated and shareable, so you can pass it to a ractor:
Warning[:experimental] = false
factor = 3
times = Ractor.shareable_proc { |x| x * factor }
p Ractor.shareable?(times)
p Ractor.new(times) { |f| [1, 2, 3].map(&f) }.value
doubler = Ractor.shareable_lambda { |x| x * 2 }
p doubler.lambda?
p doubler.(21)
true
[3, 6, 9]
true
42
The proc may read outer variables, but only if they hold shareable values and aren't reassigned anywhere:
Warning[:experimental] = false
name = +"mutable"
begin
Ractor.shareable_proc { name.upcase }
rescue => e
puts "#{e.class}: #{e.message}"
end
count = 0
begin
Ractor.shareable_proc { count + 1 }
rescue => e
puts "#{e.class}: #{e.message}"
end
count += 1
Ractor::IsolationError: cannot make a shareable Proc because it can refer unshareable object "mutable" from variable 'name'
Ractor::IsolationError: cannot make a shareable Proc because the outer variable 'count' may be reassigned.
Note that count is reassigned on the last line, after the proc was created. Ruby checks the whole scope.
Shareable procs also fix methods created with define_method. A method defined with an ordinary block can't be called from another ractor:
Warning[:experimental] = false
class Greeter
define_method(:hello) { "hello" }
define_method(:hi, &Ractor.shareable_proc { "hi" })
end
r = Ractor.new { Greeter.new.hi }
p r.value
r = Ractor.new { Greeter.new.hello }
begin
r.value
rescue Ractor::RemoteError => e
puts e.cause.message
end
"hi"
defined with an un-shareable Proc in a different Ractor
This matters for metaprogramming-heavy libraries, which often use define_method.
Ports
Ractor.receive reads from a ractor's own inbox (its default port). A Ractor::Port is an additional channel. Anyone can send to a port, but only the ractor that created it can receive from it. Ports are shareable, so you can pass one to another ractor so it can reply:
Warning[:experimental] = false
port = Ractor::Port.new
r = Ractor.new(port) do |out|
3.times { |i| out << "step #{i}" }
out << :finished
end
4.times { p port.receive }
r.join
"step 0"
"step 1"
"step 2"
:finished
This gives you request/reply: send the request together with the port the answer should go to:
Warning[:experimental] = false
# A ractor that answers requests; each request carries a reply port
squarer = Ractor.new do
loop do
n, reply = Ractor.receive
break if n == :stop
reply << n * n
end
:stopped
end
reply = Ractor::Port.new
[3, 4, 5].each do |n|
squarer << [n, reply]
puts "#{n}^2 = #{reply.receive}"
end
squarer << [:stop, nil]
p squarer.value
3^2 = 9
4^2 = 16
5^2 = 25
:stopped
Ractor.select
Ractor.select waits on several ports or ractors and returns the first one that's ready, along with the value. Given ractors, it waits for one of them to finish:
Warning[:experimental] = false
rs = [0.3, 0.1, 0.2].map do |delay|
Ractor.new(delay) do |d|
sleep d
"slept #{d}"
end
end
until rs.empty?
r, value = Ractor.select(*rs)
puts "#{r.inspect[/#\d+/]} -> #{value}"
rs.delete(r)
end
#3 -> slept 0.1
#4 -> slept 0.2
#2 -> slept 0.3
Given ports, it waits for a message on any of them:
Warning[:experimental] = false
fast = Ractor::Port.new
slow = Ractor::Port.new
Ractor.new(fast) { |p| sleep 0.1; p << "fast done" }
Ractor.new(slow) { |p| sleep 0.3; p << "slow done" }
2.times do
port, msg = Ractor.select(fast, slow)
puts "#{port == fast ? 'fast' : 'slow'} port: #{msg}"
end
fast port: fast done
slow port: slow done
Closing a port
close closes a port. Messages already in it can still be received. After that, both receive and send raise Ractor::ClosedError:
port = Ractor::Port.new
port << 1
port.close
p port.closed?
p port.receive
begin
port.receive
rescue Ractor::ClosedError => e
puts "#{e.class}: #{e.message}"
end
begin
port << 2
rescue Ractor::ClosedError => e
puts "#{e.class}: #{e.message}"
end
true
1
Ractor::ClosedError: The port was already closed
Ractor::ClosedError: The port was already closed
Only the ractor that created a port can close it.
Errors
An exception that ends a ractor shows up in whoever calls #value (or #join), wrapped in Ractor::RemoteError. The original exception is in cause:
Warning[:experimental] = false
r = Ractor.new { raise ArgumentError, "bad input" }
begin
r.value
rescue Ractor::RemoteError => e
puts "#{e.class}: #{e.message}"
puts "cause: #{e.cause.class}: #{e.cause.message}"
end
Ractor::RemoteError: thrown by remote Ractor.
cause: ArgumentError: bad input
To be notified when a ractor ends without blocking on it, use #monitor with a port. The port receives :exited when the ractor finishes normally and :aborted when it dies with an exception:
Warning[:experimental] = false
r = Ractor.new do
Ractor.receive
raise "boom"
end
events = Ractor::Port.new
r.monitor(events)
r << :go
p events.receive
:aborted
A supervisor can monitor many workers with one port and restart those that crash.
A worker pool
Starting a ractor isn't free, and you normally don't want more ractors than CPU cores. For many small jobs, start a fixed number of workers and feed them work. This pool hands the next job to whichever worker finishes first, so a slow job doesn't hold up the others:
Warning[:experimental] = false
require "digest"
class RactorPool
def initialize(size, &work)
work = Ractor.shareable_proc(&work)
@results = Ractor::Port.new
@workers = size.times.map do |i|
Ractor.new(@results, work, name: "worker-#{i}") do |results, fn|
while (job = Ractor.receive) != :stop
item, index = job
results << [Ractor.current, index, fn.call(item)]
end
end
end
@idle = @workers.dup
end
# Gives each job to whichever worker is free; returns results in input order
def map(items)
jobs = items.each_with_index.to_a
out = Array.new(items.size)
@idle.shift << jobs.shift until @idle.empty? || jobs.empty?
items.size.times do
worker, index, value = @results.receive
out[index] = value
jobs.empty? ? @idle << worker : worker << jobs.shift
end
out
end
def shutdown
@workers.each { |w| w << :stop }
@workers.each(&:join)
end
end
pool = RactorPool.new(4) do |word|
# deliberately slow: hash the word 20,000 times
20_000.times.reduce(word) { |acc, _| Digest::SHA256.hexdigest(acc) }[0, 12]
end
words = %w[apple banana cherry date elderberry fig grape]
pool.map(words).zip(words).each { |digest, word| puts "#{word.ljust(10)} #{digest}" }
p pool.map(%w[kiwi lime]).size
pool.shutdown
apple 4b831d343101
banana 797f33560b55
cherry 57f61d341d46
date 8341c807c472
elderberry 029a526131fc
fig babfcba397e9
grape 210d7a5c853a
2
How it works:
- the work block becomes a shareable proc, so each worker gets the same proc without copying
- each worker reads jobs from its own inbox and sends
[worker, index, result]to one shared results port, which only the main ractor reads - the main ractor gives the first jobs to idle workers, then sends one more job to each worker that reports back, until no jobs are left
- the index puts results back in input order, because workers finish in any order
shutdownsends:stopto every worker and waits for all of them
Digest is a C extension marked as ractor-safe, so it works inside the workers. Use Etc.nprocessors to pick a pool size that matches the machine.
Do ractors make code faster?
For CPU-bound pure Ruby code, yes. Here the same work is done serially, in 4 threads and in 4 ractors:
Warning[:experimental] = false
def prime?(n)
return false if n < 2
(2..Integer.sqrt(n)).none? { |d| (n % d).zero? }
end
def count_primes(range) = range.count { |n| prime?(n) }
def measure(label)
t = Process.clock_gettime(Process::CLOCK_MONOTONIC)
result = yield
ms = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - t) * 1000
puts format("%-8s %6d primes %7.1f ms", label, result, ms)
end
ranges = [1...250_000, 250_000...500_000, 500_000...750_000, 750_000...1_000_000]
measure("serial") { ranges.sum { |r| count_primes(r) } }
measure("threads") { ranges.map { |r| Thread.new { count_primes(r) } }.sum(&:value) }
measure("ractors") { ranges.map { |r| Ractor.new(r) { |rr| count_primes(rr) } }.sum(&:value) }
serial 78498 primes 5578.9 ms
threads 78498 primes 5362.8 ms
ractors 78498 primes 1630.5 ms
Threads give no speedup because of the GVL. Ractors finish in less than a third of the time. Exact numbers depend on the machine and its load.
Methods defined at the top level, such as count_primes, can be called from a ractor, because methods belong to classes, not to a ractor. What matters is the state those methods touch.
For I/O-bound work (HTTP calls, database queries) you don't need ractors: threads or Fibers and Async already overlap the waiting, with far fewer restrictions. See also Performance.
Limitations
Ractors are still marked experimental in Ruby 4.0. Before you use them, know the limits:
- Gems. Code that keeps state in globals, class variables (
@@x), class-level instance variables or mutable constants fails withRactor::IsolationErrorinside a ractor. Many popular gems do at least one of these. C extensions must explicitly mark themselves as ractor-safe, or calling them from a non-main ractor raises an error. - Copying cost. Every unshareable message is deep-copied. A ractor that does a little work on a big message can be slower than doing it in the main ractor.
- No shared caches. Each ractor needs its own copy of a cache or connection (use
Ractor.store_if_absent), or one ractor owns it and others ask it through messages. - Debugging. Error messages point at the access that broke isolation, but finding why a library touches a global can take a while.
- Stability. The API changed between 3.4 and 4.0, and may change again.
The mature alternative for CPU-bound work is multiple processes: Process.fork on Unix-like systems, or a process-based server such as Puma in cluster mode. Processes cost more memory but run any Ruby code. Ractors are a good fit for self-contained, CPU-heavy computation (parsing, hashing, number crunching, image processing in pure Ruby) where you control all the code that runs inside them.
For other approaches to shared state see Race conditions and Locks and synchronization.
Migrating from the Ruby 3.x API
Ruby 3.0 to 3.4 used a different way to get values out of a ractor: the ractor called Ractor.yield(obj) and others called r.take. Both are gone in Ruby 4.0:
| Ruby 3.0 to 3.4 | Ruby 4.0 |
|---|---|
r.take to get the block's result |
r.value |
r.take only to wait for the end |
r.join |
Ractor.yield(obj) inside the ractor |
port << obj, with a Ractor::Port passed in |
Ractor.select(*ractors) for yielded values |
Ractor.select(*ports) |
r.close_incoming / r.close_outgoing |
port.close |
| no equivalent | r.monitor(port), Ractor.shareable_proc |
Ractor.new, send/<<, Ractor.receive, Ractor.make_shareable and Ractor.shareable? work the same in both. Code that has to run on both can check Ractor.method_defined?(:value).