Ruby Ractors: isolation, message cost and where they scale

Ruby/RailsConcurrency

Ruby threads take turns under one lock, the GVL, so a CPU-bound Ruby program uses one core however many threads it starts. Ractors (Ruby 3.0+) are the way to run Ruby code on several cores inside one process: each Ractor has its own lock, and in exchange Ractors share almost nothing. This article covers what may cross between them, the Ruby 4.0 API, and six workloads measured on 1, 2, 4 and 8 pinned cores against threads and fork. In short, integer and float work scale. Code that allocates objects at a high rate does not: 8 Ractors building Strings finish fewer tasks per second than 1.

At a glance

ThreadsRactorsfork (Puma cluster, Sidekiq swarm)
Ruby code on several coresno: one GVL per processyes: one GVL per Ractoryes: one process per worker
Shared memoryeverythingonly shareable (deep-frozen) objectscopy-on-write after the fork; nothing shared after a write
Passing dataa referencedeep copy, move: true or a shareable objectpipes, sockets, Redis: serialised
8 workers, integer work (fib)1.0×4.8×7.8×
8 workers, String allocation0.9×0.9×7.9×
8 workers, JSON.parse0.9×1.2×7.6×
Start one, run an empty block, wait33 µs21 µs832 µs
Gems that workallonly Ractor-safe onesall
Status in Ruby 4.0stableexperimental (prints a warning)stable

Speed-ups are tasks per second against one thread of the same workload, 8 Cortex-A725 cores, Ruby 4.0.9 with YJIT; median of 9 trials (see Method). 28 whole programs measured the same way: Ractors vs threads vs fork: 28 Ruby benchmarks.

What a Ractor is

A Ractor is an actor with its own heap of objects and its own GVL. Threads inside one Ractor still take turns; two Ractors run Ruby code at the same time on two cores. The price is isolation: a Ractor may not touch another Ractor’s mutable objects, so most of what a Ruby program shares by accident (constants holding a Hash, $globals, class-level caches) is off limits outside the main Ractor.

An object is shareable when every Ractor may read it at the same time:

ShareableNot shareable
nil, true, false, Integer, Float, Symbola String, Array or Hash that is not frozen
a frozen String, or a frozen Array/Hash whose elements are all shareablea frozen Array holding an unfrozen String ([+"x"].freeze)
classes and modules, Ractor objects, Ractor::Porta Proc that refers to outer local variables
anything passed through Ractor.make_shareable (deep-freezes in place)an object with unshareable instance variables

Everything else crosses between Ractors in one of three ways:

send / <<What happensCost (measured below)
r.send(obj)deep copy: the receiver gets new objectsgrows with the object graph
r.send(obj, move: true)the receiver takes the objects; any call on the sender’s reference, even .class, raises Ractor::MovedErrorgrows with the object graph; 41–54 % of a copy from 100 KB up
r.send(shareable)the same object, no copyflat; make_shareable itself walks the graph once

What a non-main Ractor gets when it reaches for shared state, in Ruby 4.0.9:

Code inside Ractor.new { … }Result
CONFIG["retries"] with CONFIG = { "retries" => 3 }Ractor::IsolationError: can not access non-shareable objects in constant Object::CONFIG by non-main Ractor.
the same with CONFIG = Ractor.make_shareable({ … })works
$counterRactor::IsolationError: can not access global variable $counter from non-main Ractor
Cache.store returning a class-level @store = {}Ractor::IsolationError: can not get unshareable values from instance variables of classes/modules from non-main Ractors (@store from Cache)
x where x is a local of the creating methodArgumentError at Ractor.new: can not isolate a Proc because it accesses outer variables (x).
obj.size after r.send(obj, move: true)Ractor::MovedError: can not send any methods to a moved object
require "json"works: the require runs on the main Ractor
calling a method made with define_method { … } in the main RactorRuntimeError: defined with an un-shareable Proc in a different Ractor

The error inside the Ractor reaches the caller of #value or #join as Ractor::RemoteError, with the original exception in #cause.

For constants there is a file-level shortcut: the magic comment # shareable_constant_value: literal runs Ractor.make_shareable on every constant in that file that is assigned a literal, and raises at assignment when any other constant value is not shareable; experimental_everything wraps every constant in Ractor.make_shareable.

Ruby 4.0: ports instead of take and yield

Ruby 3.0–3.4 moved values with Ractor.yield and Ractor#take. Ruby 4.0 removed both, together with close_incoming/close_outgoing, and added Ractor::Port: a mailbox that any Ractor may send to and only the Ractor that created it may receive from. Each Ractor still has a default port, which is what Ractor#send and Ractor.receive use.

TaskRuby 3.4Ruby 4.0
wait for the block’s resultr.taker.value
wait for it to finishr.taker.join
a Ractor reports back to its creatorRactor.yield x / r.takeport << x / port.receive
be told when a Ractor dies—r.monitor(port); the port receives :exited or :aborted
a reply channel per requesta new Ractor as a pipeRactor::Port.new sent along with the request
receive on a port from another Ractor—Ractor::Error: only allowed from the creator Ractor of this port
# Ruby 4.0: N workers, one result port owned by the main Ractor
results = Ractor::Port.new
workers = 4.times.map do |i|
  Ractor.new(results, i) do |out, i|
    while (job = Ractor.receive)      # jobs arrive on the worker's default port
      out << [i, job, job * job]      # the main Ractor is the only one that may receive from `out`
    end
  end
end
10.times { |j| workers[j % 4].send(j) }
p 10.times.map { results.receive }
workers.each { _1.send(nil) }.each(&:join)

Ruby 4.0 still prints warning: Ractor API is experimental and may change in future versions of Ruby. the first time a program calls Ractor.new.

Measured: six workloads on 1–8 cores

Each workload is a fixed number of identical tasks, split across W workers on exactly W cores: W threads fed by a Queue, W Ractors fed by send and answering on one Ractor::Port, or W forked children fed over pipes (the shape of a Puma cluster). Ruby 4.0.9 with YJIT, Cortex-A725 cores at 2.8 GHz. Checksums are identical across all models and worker counts.

WorkloadOne task
Integer (fib)fib(22): method calls and Integer arithmetic, no allocation
Float loop20,000 Float multiply-adds (Floats are immediates on 64-bit, no allocation)
String alloc2,000 interpolated Strings in an Array, then their byte sizes summed
Hash alloc500 Hashes { id:, name:, tags: [..] }, then summed
JSON.parseparse a 15 KB JSON document (200 records) and sum fields
String#to_sym2,000 lookups of Symbols that already exist
Speed-up over one thread for six workloads at 1, 2, 4 and 8 workers: threads stay at 1×, fork scales almost perfectly, Ractors scale on integer and float work and much less on allocation-heavy work threads Ractors fork perfect split Integer (fib) 1× 2× 4× 8× 1 2 4 8 4.8× 7.8× Float loop 1× 2× 4× 8× 1 2 4 8 5.8× 7.9× String alloc 1× 2× 4× 8× 1 2 4 8 0.9× 7.9× Hash alloc 1× 2× 4× 8× 1 2 4 8 1.0× 7.7× JSON.parse 1× 2× 4× 8× 1 2 4 8 1.2× 7.6× String#to_sym 1× 2× 4× 8× 1 2 4 8 6.4× 7.8× workers (cores) — speed-up over 1 thread of the same workload
Speed-up over one thread of the same workload at 1, 2, 4 and 8 workers on as many Cortex-A725 cores; Ruby 4.0.9 + YJIT, median of 9 trials (3 passes × 3). The dotted grey line is a perfect split.
Speed-up over one thread for six workloads at 1, 2, 4 and 8 workers: threads stay at 1×, fork scales almost perfectly, Ractors scale on integer and float work and much less on allocation-heavy work threads Ractors fork perfect split Integer (fib) 1× 2× 4× 8× 1 2 4 8 4.8× 7.8× Float loop 1× 2× 4× 8× 1 2 4 8 5.8× 7.9× String alloc 1× 2× 4× 8× 1 2 4 8 0.9× 7.9× Hash alloc 1× 2× 4× 8× 1 2 4 8 1.0× 7.7× JSON.parse 1× 2× 4× 8× 1 2 4 8 1.2× 7.6× String#to_sym 1× 2× 4× 8× 1 2 4 8 6.4× 7.8× workers (cores) · speed-up over 1 thread
Speed-up over one thread of the same workload at 1, 2, 4 and 8 workers on as many Cortex-A725 cores; Ruby 4.0.9 + YJIT, median of 9 trials (3 passes × 3). The dotted grey line is a perfect split.
Workload1 thread8 threads1 Ractor2 Ractors4 Ractors8 Ractors8 × fork
Integer (fib)2,3401.0×0.9×1.8×3.6×4.8×7.8×
Float loop1,2701.0×1.0×1.9×3.9×5.8×7.9×
String alloc1,5410.9×1.0×1.4×1.4×0.9×7.9×
Hash alloc4,9951.0×1.0×1.5×1.6×1.0×7.7×
JSON.parse6,5500.9×1.0×1.5×1.9×1.2×7.6×
String#to_sym5,2891.1×1.2×2.2×4.1×6.4×7.8×

The 1-thread column is tasks per second; the rest are speed-ups over it. Median of 9 trials: 3 passes of 3 interleaved trials, each cell re-run whenever anything else on the machine was busy. Within a trial, 8 Ractors over 1 thread ranged 4.82–4.97× on fib, 0.79–0.95× on Strings, 0.98–1.05× on Hashes, 1.12–1.20× on JSON.parse and 5.63–6.85× on Symbols. The first version of this table (26 November) ran next to other jobs on the same machine and put Strings at 0.7×; it is replaced.

Why allocation stops Ractors

The heap and the garbage collector are shared by all Ractors. Two places in Ruby 4.0.9’s collector (gc/default/default.c) make Ractors wait for each other:

Reading GC.stat around the timed reps shows the cost (same cells, a control run in each pass, 9 trials):

Per rep (512 tasks)String alloc, 1 RactorString alloc, 8 RactorsJSON.parse, 1 RactorJSON.parse, 8 Ractors
GC runs274935716
time in GC55.0 ms114.0 ms16.4 ms22.3 ms
time per GC0.20 ms1.22 ms0.29 ms1.36 ms
share of wall time in GC16 %30 %21 %33 %
wall time outside GC278 ms264 ms61 ms46 ms

With 8 Ractors the collector runs a third to a quarter as often, but each run takes 6.1× longer (String) and 4.7× longer (JSON), because it marks and sweeps the objects of all eight and stops all eight. The time outside GC barely shrinks either: 278 ms of String building with 1 Ractor takes 264 ms with 8 (a perfect split would be 35 ms), so the time that 8 cores should have saved is lost waiting, at the GC barrier and on the VM lock that refills each Ractor’s slot cache (GC.stat[:time] counts neither wait, so this measurement cannot split the two). fork avoids both because nothing is shared.

A bigger starting heap removes most of it. With RUBY_GC_HEAP_0_INIT_SLOTS to RUBY_GC_HEAP_4_INIT_SLOTS set to 1,000,000, 8 Ractors ran 3.0× one thread on Strings, 2.8× on Hashes and 2.6× on JSON.parse (0.9–1.1× by default), with 0.6–3.2 collections per rep instead of 17–93 and 59–129 MB peak memory instead of 19 MB. Switching the collector off was no better: 3.1× on Strings, 1.9× on Hashes and JSON.parse. With no collections, every slot-cache refill has to grow the heap, inside the same cross-Ractor lock. Details in the benchmark article.

YJIT and non-allocating work

The same fib and Float cells without YJIT:

1 Ractor8 Ractors1 × fork8 × fork
fib, interpreter5743,902 (6.8×)5754,579 (8.0×)
fib, YJIT2,17711,303 (5.2×)2,34118,235 (7.8×)
Float loop, interpreter5243,588 (6.8×)5254,175 (8.0×)
Float loop, YJIT1,2717,350 (5.8×)1,27010,047 (7.9×)

YJIT makes each Ractor 3.8× faster on fib but the 8-Ractor speed-up drops from 6.8× to 5.2×, and one Ractor runs YJIT code 7 % slower than a thread or a forked child (2,177 against 2,340 and 2,341 tasks per second; without YJIT a Ractor and a forked child are equal, 574 and 575). fork keeps 7.8–8.0× either way. With YJIT, the best Ractor cases reach 62–83 % of what fork does on 8 cores (85 % for fib in the interpreter).

Measured: 28 whole programs

The six workloads above are fragments. The same three models also ran the 28 programs from Spinel vs JRuby vs CRuby, each split into 8 identical tasks:

Speed-up at 8 workers over one thread for 28 Ruby programs: fork reaches 6.5 to 8 times on every program, Ractors 5.3 to 7.9 times on the 14 programs that allocate under 0.11 million objects per second and 0.3 to 2 times on the 13 that allocate 2.4 million or more 8 Ractors 8 forked processes 1× 2× 4× 6× 8× partial_sums 7.91 7.99 matmul 7.69 7.95 life 7.56 8.00 sieve 7.44 7.63 so_mandelbrot 7.41 8.00 so_lists 7.07 7.90 nqueens 7.04 8.04 sudoku 7.01 7.95 fib 6.40 7.99 tak 6.33 7.98 ackermann 6.30 7.99 tarai 6.29 7.98 str_concat 5.77 6.47 fannkuch 5.29 7.82 rbtree * 4.28 7.95 linked_list * 2.00 7.88 ao_render_rs * 1.99 7.96 gcbench * 1.92 7.77 bigint_fib * 1.62 7.75 fasta_rs * 1.62 7.83 csv_process * 1.35 7.70 pidigits 1.33 7.86 io_wordcount_rs 1.28 7.95 huffman 1.17 7.80 template 0.80 7.98 binary_trees * 0.77 7.79 json_parse 0.77 7.88 splay * 0.26 6.62 * range across trials wider than ±5 % (thin line: min–max)
Speed-up at 8 workers over one thread of the same program, 8 Cortex-A725 cores, Ruby 4.0.9 + YJIT; median of 9 within-trial ratios (18 for fib, gcbench and json_parse, which ran on both machines). * marks a program whose trials ranged wider than ±5 %.
Speed-up at 8 workers over one thread for 28 Ruby programs: fork reaches 6.5 to 8 times on every program, Ractors 5.3 to 7.9 times on the 14 programs that allocate under 0.11 million objects per second and 0.3 to 2 times on the 13 that allocate 2.4 million or more 8 Ractors 8 forked processes 1× 2× 4× 6× 8× partial_sums 7.91 7.99 matmul 7.69 7.95 life 7.56 8.00 sieve 7.44 7.63 so_mandelbrot 7.41 8.00 so_lists 7.07 7.90 nqueens 7.04 8.04 sudoku 7.01 7.95 fib 6.40 7.99 tak 6.33 7.98 ackermann 6.30 7.99 tarai 6.29 7.98 str_concat 5.77 6.47 fannkuch 5.29 7.82 rbtree * 4.28 7.95 linked_list * 2.00 7.88 ao_render_rs * 1.99 7.96 gcbench * 1.92 7.77 bigint_fib * 1.62 7.75 fasta_rs * 1.62 7.83 csv_process * 1.35 7.70 pidigits 1.33 7.86 io_wordcount_rs 1.28 7.95 huffman 1.17 7.80 template 0.80 7.98 binary_trees * 0.77 7.79 json_parse 0.77 7.88 splay * 0.26 6.62 * range across trials wider than ±5 % (thin line: min–max)
Speed-up at 8 workers over one thread of the same program, 8 Cortex-A725 cores, Ruby 4.0.9 + YJIT; median of 9 within-trial ratios (18 for fib, gcbench and json_parse, which ran on both machines). * marks a program whose trials ranged wider than ±5 %.

Read more: all 28 programs, memory, GC settings and task size →

Measured: the cost of a message

One echo Ractor on 2 cores: send one Array of n Strings of 100 B, wait for a one-integer reply. The Queue column is the same round trip between two threads, where nothing is copied.

Time to send one message to a Ractor and get a one-integer reply, by payload size: a deep copy and a move grow with the payload, a shareable object costs the same at every size 1 µs 10 µs 100 µs 1 ms 10 ms 100 ms 100 B 1 KB 10 KB 100 KB 1 MB 10 MB Queue between threads (no copy) Ractor send (deep copy) send move: true send a shareable object Ractor.make_shareable, once payload: n strings of 100 B in one Array
One send to an echo Ractor plus a one-integer reply, by payload size, both axes logarithmic; median of 9 trials (3 passes × 3). The dotted line is the one-off cost of Ractor.make_shareable on the same payload.
Time to send one message to a Ractor and get a one-integer reply, by payload size: a deep copy and a move grow with the payload, a shareable object costs the same at every size 1 µs 10 µs 100 µs 1 ms 10 ms 100 ms 100 B 1 KB 10 KB 100 KB 1 MB 10 MB Queue between threads (no copy) Ractor send (deep copy) send move: true send a shareable object Ractor.make_shareable, once payload: n strings of 100 B in one Array
One send to an echo Ractor plus a one-integer reply, by payload size, both axes logarithmic; median of 9 trials (3 passes × 3). The dotted line is the one-off cost of Ractor.make_shareable on the same payload.
PayloadQueue (threads)Ractor: copyRactor: move: trueRactor: shareablemake_shareable, once
1 String, 100 B10.2 µs10.8 µs10.4 µs9.5 µs3.5 µs
10 Strings, 1 KB10.0 µs14.2 µs11.7 µs9.5 µs5.4 µs
100 Strings, 10 KB10.0 µs45.0 µs30.2 µs9.6 µs19.5 µs
1,000 Strings, 100 KB10.3 µs433 µs235 µs9.8 µs119 µs
10,000 Strings, 1 MB10.9 µs4.62 ms2.33 ms10.0 µs1.45 ms
100,000 Strings, 10 MB10.9 µs50.7 ms20.6 ms10.3 µs17.4 ms

Measured: starting one, and what it weighs

One core, medianThreadRactorfork
create, run an empty block, wait for it33.4 µs20.7 µs832 µs
resident memory per idle worker (200 workers that each ran fib(15), then wait on a receive)33.3 KB21.7 KB—

A Ractor starts faster than a Thread here and holds less memory while it waits. Spawn cost does not decide between them; fork is 40× slower to start than a Ractor, which is why servers fork their workers once at boot.

Pitfalls

When to use Ractors

WorkUse
Web requests, I/O, database callsthreads (Puma), or fibers with async; the GVL is released while waiting
CPU-bound Ruby code over integers, floats, existing Symbols, frozen dataRactors: 4.8–6.4× on 8 cores here, one process, no serialisation
CPU-bound code that allocates: building Strings, Hashes, parsing JSONfork: 7.6–7.9× on 8 cores; Ractors stay at 0.9–1.2×
Large inputs read by every workershare once with Ractor.make_shareable, or fork after loading them (copy-on-write)
Code that calls gems you do not controlfork or threads, until each gem is checked inside a Ractor

Method

SetupDetails
Ruby4.0.9, image pinned by digest (ruby@sha256:3251898a…2cd31d, full digest in the commands below; what the ruby:4.0-slim tag pointed to at the time of the run — a tag moves, a digest does not), arm64, --yjit unless a row says interpreter · json 2.18.0
CPU20-core ARM64 server (10 × Cortex-X925 + 10 × Cortex-A725). Benchmarks on the A725 cores at 2.8 GHz, governor performance: W = 1, 2, 4, 8 on --cpuset-cpus=1, 1-2, 1-4, 1-4,10-13
IsolationFor the whole run, every systemd service, every other container and every movable IRQ was confined to the ten X925 cores (cgroup v2 cpuset.cpus on system.slice, user.slice, init.scope); the benchmark containers ran in their own slice. Each cell measured foreign CPU time on its cores from /proc/stat minus its own slice, and was discarded and re-run above 0.05 + 0.03 × W cores; also re-run (after a 30 s wait) when the rest of the machine used more than 5 cores or the GPU, which shares the memory, was more than 5 % busy.
Why not the X925 coresWith --yjit, 64 × fib(22) on one X925 core took 0.145–0.153 s in most processes and 0.011 s in a few, depending on address layout (ASLR on/off, environment size); the interpreter took 0.066 s. The A725 cores gave 0.0274–0.0277 s in 18 of 18 processes, and fib on one Ractor ran 2,176–2,178 tasks per second in all 9 trials
Scale cellsPersistent workers (W threads fed by a Queue, W Ractors fed by Ractor#send and answering on one Ractor::Port, W forked children fed over pipes — the shape of a Puma cluster). 2 warm-up reps, then ≥ 5 reps and ≥ 3 s; the median rep. The same total tasks at every W; checksums equal across models and W
Message cellsOne echo Ractor on 2 cores; one send + a one-integer reply per sample; 3 warm-up sends, then 20–2,000 samples, median. Payload: an Array of n Strings of 100 B. move: sends a fresh payload each time (built before timing)
Trials3 passes × 3 interleaved trials (every cell once, then again); the median of the 9 is reported

Each cell runs in a fresh container; rb.rb prints one JSON line per cell (checksum, tasks per second or µs, peak RSS):

docker run --rm --cgroup-parent=bench651.slice --cpuset-cpus=1-4,10-13 -v "$PWD":/b -w /b \
  ruby@sha256:3251898a6b7ff1275a0dc279d401889c6c743c1fb3292fa3ce1a2e12fc2cd31d \
  ruby --yjit rb.rb scale json ractors 8
docker run --rm --cgroup-parent=bench651.slice --cpuset-cpus=1-2 -v "$PWD":/b -w /b \
  ruby@sha256:3251898a6b7ff1275a0dc279d401889c6c743c1fb3292fa3ce1a2e12fc2cd31d \
  ruby --yjit rb.rb msg move 10000

The GC.stat table and the interpreter rows come from a control run of the scale cells with rb2.rb in each pass: rb.rb plus GC.stat read around the timed reps (GC.stat[:time] is in ms and is one VM-wide counter for all Ractors). The interpreter rows ran it without --yjit. The whole difference:

@@ -75,13 +75,17 @@
   sums = []; times = []
   t_end = now + 3.0; reps = 0
   2.times { sums << rep.call }                                    # warm-up
+  g0 = GC.stat.slice(:count, :time, :minor_gc_count, :major_gc_count)
   while reps < 5 || now < t_end
     t = now; sums << rep.call; times << now - t; reps += 1
   end
+  g1 = GC.stat.slice(:count, :time, :minor_gc_count, :major_gc_count)
   abort "checksum drift #{sums.uniq}" unless sums.uniq.size == 1
   t = median(times)
+  gc = { gc_per_rep: ((g1[:count] - g0[:count]) / reps.to_f).round(2), gc_ms_per_rep: ((g1[:time] - g0[:time]) / reps.to_f).round(2),
+         gc_share: ((g1[:time] - g0[:time]) / 1000.0 / times.sum).round(4) }
   emit(test: "scale", workload: wl, model: model, w: w, tasks: total, reps: reps, median_s: t.round(6),
-       tasks_per_s: (total / t).round(1), checksum: sums[0], peak_rss_kb: rss_kb("VmHWM"))
+       tasks_per_s: (total / t).round(1), checksum: sums[0], peak_rss_kb: rss_kb("VmHWM"), **gc)
 end
 
 # ---------- msg: one message to an echo Ractor and a 1-int reply ----------

rb.rb:

# Ractor benchmarks (Ruby 4.0). One JSON line per run on stdout.
#   ruby --yjit rb.rb scale <workload> <model> <W>    workload: int float str hash json sym ; model: threads ractors fork
#   ruby --yjit rb.rb msg <mode> <n>                  mode: thread copy move shareable ; n = strings of 100 B in the payload
#   ruby --yjit rb.rb spawn <model>                   model: thread ractor fork
#   ruby --yjit rb.rb mem <model>                     model: thread ractor  (RSS per idle worker)
require "json"
Warning[:experimental] = false

def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
def median(a) = a.sort[a.size / 2]
def rss_kb(f = "VmRSS") = File.read("/proc/self/status")[/#{f}:\s+(\d+)/, 1].to_i
def emit(h) = puts(JSON.generate(h.merge(ruby: RUBY_VERSION, yjit: defined?(RubyVM::YJIT) && RubyVM::YJIT.enabled?, cpus: Etc.nprocessors)))
require "etc"

# ---------- workloads: task(i) -> Integer; every task does the same amount of work ----------
def fib(n) = n < 2 ? n : fib(n - 1) + fib(n - 2)

def w_int(i) = fib(22) + i

def w_float(i)                       # flonums: no heap allocation on 64-bit
  x = 0.0; y = 0.0; k = 0
  20_000.times { |j| x = x * 0.5 + (j + i) * 1.0e-3; y += x * x; k += 1 }
  (y * 1000).to_i + k
end

def w_str(i)                         # 2,000 short String objects
  a = Array.new(2_000) { |j| "item-#{i}-#{j}" }
  a.sum(&:bytesize)
end

def w_hash(i)                        # 500 Hash rows with a nested Array
  rows = Array.new(500) { |j| { id: j, name: "n#{j}", tags: [i, j, i + j] } }
  rows.sum { |r| r[:id] + r[:tags].sum + r[:name].bytesize }
end

DOC = Ractor.make_shareable(JSON.generate(Array.new(200) { |j| { "id" => j, "name" => "user-#{j}", "score" => j * 0.5, "tags" => %w[a b c], "active" => j.odd? } }))
def w_json(i)                        # parse a 15 KB document
  JSON.parse(DOC).sum { |r| r["id"] + r["name"].bytesize + r["tags"].size } + i
end

def w_sym(i)                         # 2,000 String -> Symbol lookups (all symbols already exist)
  s = 0
  2_000.times { |j| s += SYMSTR[(i + j) % 1000].to_sym.size }
  s
end
SYMSTR = Ractor.make_shareable(Array.new(1000) { |j| "sym_#{j}" })
SYMSTR.each(&:to_sym)

TASKS = { "int" => 256, "float" => 256, "str" => 512, "hash" => 512, "json" => 512, "sym" => 1024 }

def run_share(wl, ids) = ids.sum { |i| __send__(:"w_#{wl}", i) }   # not send: inside a Ractor block self is the Ractor, and Ractor#send is messaging

# ---------- scale ----------
def scale(wl, model, w)
  total = TASKS.fetch(wl)
  shares = Array.new(w) { |k| (k...total).step(w).to_a }
  rep = case model
  when "threads"
    qs = Array.new(w) { Queue.new }; out = Queue.new
    w.times { |k| Thread.new { while qs[k].pop; out << run_share(wl, shares[k]); end } }
    -> { qs.each { _1 << true }; Array.new(w) { out.pop }.sum }
  when "ractors"
    out = Ractor::Port.new
    rs = Array.new(w) { |k| Ractor.new(wl, shares[k], out) { |wl, ids, out| while Ractor.receive; out << run_share(wl, ids); end } }
    -> { rs.each { _1.send(true) }; Array.new(w) { out.receive }.sum }
  when "fork"
    kids = Array.new(w) do |k|
      cr, cw = IO.pipe; pr, pw = IO.pipe
      pid = fork { cw.close; pr.close; while cr.gets; pw.puts run_share(wl, shares[k]); end; exit! 0 }
      cr.close; pw.close; [cw, pr, pid]
    end
    -> { kids.each { |cw, _, _| cw.puts "go" }; kids.sum { |_, pr, _| pr.gets.to_i } }
  else abort "model?"
  end
  sums = []; times = []
  t_end = now + 3.0; reps = 0
  2.times { sums << rep.call }                                    # warm-up
  while reps < 5 || now < t_end
    t = now; sums << rep.call; times << now - t; reps += 1
  end
  abort "checksum drift #{sums.uniq}" unless sums.uniq.size == 1
  t = median(times)
  emit(test: "scale", workload: wl, model: model, w: w, tasks: total, reps: reps, median_s: t.round(6),
       tasks_per_s: (total / t).round(1), checksum: sums[0], peak_rss_kb: rss_kb("VmHWM"))
end

# ---------- msg: one message to an echo Ractor and a 1-int reply ----------
def payload(n) = Array.new(n) { |j| ("x" * 92) + format("%08d", j) }   # n strings of 100 B

def msg(mode, n)
  iters = [[200_000 / [n, 1].max, 20].max, 2_000].min
  if mode == "thread"
    q = Queue.new; back = Queue.new
    Thread.new { while (o = q.pop); back << o.size; end }
    obj = payload(n)
    send1 = ->(_) { q << obj; back.pop }
  else
    back = Ractor::Port.new
    r = Ractor.new(back) { |b| while (o = Ractor.receive); b << o.size; end }
    case mode
    when "copy"      then obj = payload(n); send1 = ->(_) { r.send(obj); back.receive }
    when "move"      then pool = Array.new(iters + 3) { payload(n) }; send1 = ->(k) { r.send(pool[k], move: true); back.receive }
    when "shareable"
      obj = payload(n)
      t = now; Ractor.make_shareable(obj); share_s = now - t
      send1 = ->(_) { r.send(obj); back.receive }
    else abort "mode?"
    end
  end
  3.times { |k| abort "bad reply" unless send1.(k) == n }
  ts = Array.new(iters) { |k| t = now; abort "bad reply" unless send1.(k + 3) == n; now - t }
  emit(test: "msg", mode: mode, n: n, bytes: n * 100, iters: iters, median_us: (median(ts) * 1e6).round(2),
       p10_us: (ts.sort[iters / 10] * 1e6).round(2), make_shareable_us: share_s && (share_s * 1e6).round(1), checksum: n)
end

# ---------- spawn: create one worker, run an empty block, wait for it ----------
def spawn_cost(model)
  one = case model
  when "thread" then -> { Thread.new { 1 }.value }
  when "ractor" then -> { Ractor.new { 1 }.value }
  when "fork"   then -> { pid = fork { exit! 0 }; Process.wait(pid); 1 }
  else abort "model?"
  end
  n = model == "fork" ? 300 : 2_000
  50.times { one.() }
  ts = Array.new(n) { t = now; one.(); now - t }
  emit(test: "spawn", model: model, n: n, median_us: (median(ts) * 1e6).round(2), p90_us: (ts.sort[n * 9 / 10] * 1e6).round(2), checksum: 1)
end

# ---------- mem: RSS added by 200 idle workers that each ran fib(15) once ----------
def mem(model)
  n = 200
  GC.start; base = rss_kb
  ws = case model
  when "thread" then Array.new(n) { q = Queue.new; [Thread.new { fib(15); q.pop }, q] }
  when "ractor" then Array.new(n) { Ractor.new { fib(15); Ractor.receive } }
  else abort "model?"
  end
  sleep 0.5; GC.start; after = rss_kb
  model == "thread" ? ws.each { |t, q| q << 1; t.join } : ws.each { |r| r.send(1); r.join }
  emit(test: "mem", model: model, n: n, kb_per_worker: ((after - base) / n.to_f).round(1), checksum: n)
end

case ARGV[0]
when "scale" then scale(ARGV[1], ARGV[2], Integer(ARGV[3]))
when "msg"   then msg(ARGV[1], Integer(ARGV[2]))
when "spawn" then spawn_cost(ARGV[1])
when "mem"   then mem(ARGV[1])
else abort "usage: see header"
end

Questions? Let's Chat :)

concurrency