Ruby and Elixir look alike on the page and are opposites underneath. Ruby runs OS threads that share every object and take turns on one lock (the GVL). Elixir runs on the BEAM, Erlang’s virtual machine. There every task is a tiny process with its own heap. Processes share nothing, talk by message, and the VM preempts each one after a fixed budget of work, on one scheduler per core. This post compares the two and measures them on the same cores.
At a glance
Ruby (MRI 4.0)
Elixir (1.20 on Erlang/OTP 29)
Unit of concurrency
Thread (OS thread), Fiber
process (spawn, Task, GenServer): a few KB, its own heap
Who switches tasks
the VM, every 100 ms, and on blocking calls
the VM, after a reduction budget (4,000 reductions, roughly one per function call) and on receive
Runs code on all cores in one OS process?
✗ threads · ✓ Ractors (experimental)
✓ one scheduler thread per core, by default
Shared mutable state
everything, between threads
none between processes; ETS tables, :counters, :atomics as explicit shared stores
Communication
shared objects + Mutex/Queue
message passing (copied), send/receive
Failure handling
an exception kills its thread; the rest go on in a possibly broken state
a crash kills one process; supervisors restart it (“let it crash”)
GC
one heap, shared by all threads
one heap per process, collected independently
What blocks a core
a C extension that keeps the GVL
a long NIF (native function) that is not run on a dirty scheduler
The two schedulers
Schematic of the lag test below. A ticker next to fib(37) waits one 100 ms GVL time slice in Ruby. On the BEAM the CPU-bound process is preempted after its reduction budget (4,000 reductions), so the ticker runs on time even when both share one scheduler (+S 1).Schematic of the lag test below. A ticker next to fib(37) waits one 100 ms GVL time slice in Ruby. On the BEAM the CPU-bound process is preempted after its reduction budget (4,000 reductions), so the ticker runs on time even when both share one scheduler (+S 1).
Ruby: threads under a GVL
A Thread is an OS thread. It must hold the GVL to run Ruby code, so a single process runs Ruby on one core at a time.
The GVL is released on blocking I/O, sleep, Queue#pop and C code that asks for it; threads overlap waits, not computation.
A CPU-bound thread keeps the GVL for a 100 ms time slice (TIME_QUANTUM_MSEC). The lag test below measures it: 100.6 ms.
More cores: fork (Puma workers, Sidekiq processes) or Ractor (its own GVL; objects crossing Ractors are copied, moved or deep-frozen; experimental in 4.0).
Many waits: fibers under a Fiber::Scheduler (the async gem) or M:N threads (RUBY_MN_THREADS=1, Ruby 3.3+).
Elixir: processes on the BEAM
A process is a VM object, not an OS thread: a few hundred words of heap and stack to start, with its own mailbox and garbage collector.
The BEAM starts one scheduler per core (System.schedulers_online/0 reported 4 on 4 pinned cores) and spreads processes across them, migrating work to idle schedulers.
Scheduling is preemptive by reductions: each function call costs a reduction, and after its budget a process goes to the back of the run queue. A tight loop cannot starve others. The lag test below shows it: a ticker beside fib(37) stays on time, even with one scheduler (+S 1).
Processes share no memory. They send messages, which are copied into the receiver’s heap (large binaries are reference-counted instead).
Shared state, when you need it, is explicit: an ETS table, :counters/:atomics, or one process (an Agent, a GenServer) that owns the state and serialises access to it.
The weak spot is native code. A NIF that runs long without being marked dirty blocks its scheduler for that time.
Measured: four tests, same 4 cores
Ruby 4.0.9 with YJIT, Elixir 1.20.4 on Erlang/OTP 29 (JIT), both in Docker on the same 4 cores (--cpuset-cpus=8-11 of an AMD Ryzen AI Max+ 395). Median of 3 rounds (see Method). Scripts and commands are at the end. For single-core speed across eight everyday tasks, see Ruby vs Elixir: eight everyday fragments.
Medians of 3 rounds (see Method), Ruby 4.0.9 + YJIT and Elixir 1.20.4 on Erlang/OTP 29, each pinned to the same 4 cores. Dark bars Ruby, light bars Elixir.Medians of 3 rounds, Ruby 4.0.9 + YJIT and Elixir 1.20.4 / OTP 29 on the same 4 cores. Dark bars Ruby, light bars Elixir.
1. CPU-bound: 4 × fib(35)
Ruby
wall
speed-up
Elixir
wall
speed-up
sequential
0.266 s
1.0×
sequential
0.211 s
1.0×
4 threads
0.266 s
1.0×
4 processes (Task.async)
0.058 s
3.6×
4 Ractors
0.075 s
3.5×
4 processes (fork)
0.072 s
3.7×
Elixir needs no special API: four Task.async calls are four processes, and the four schedulers run them on four cores.
Ruby threads add nothing; Ractors and fork reach 3.5–3.7×, the same range as Elixir’s 3.6×.
Against a perfect 4× split, Elixir is 5.3 ms over (0.211 / 4 = 0.0528 s), Ractors 8.5 ms and fork 5.5 ms (0.266 / 4 = 0.0665 s).
One core: the BEAM JIT runs this recursion in 0.211 s, YJIT in 0.266 s.
2. I/O-bound: 10,000 concurrent 100 ms waits
Runtime · primitive
wall
over the 0.100 s ideal
RSS
Elixir · 10,000 processes (Process.sleep)
0.134 s
+34 ms
126 MB
Ruby · 10,000 threads, M:N (RUBY_MN_THREADS=1)
0.333 s
+233 ms
147 MB
Ruby · 10,000 fibers (async 2.46)
0.351 s
+251 ms
133 MB
Ruby · 10,000 threads (default 1:1)
1.023 s
+923 ms
192 MB
Above the 100 ms wait, spawning and scheduling 10,000 processes costs 34 ms. Ruby’s cheapest option (M:N threads) costs 233 ms, 6.9× that overhead.
RSS includes each runtime’s own footprint; the totals are within 126–192 MB.
An Elixir process is also the unit that handles a request in Phoenix, a WebSocket channel or a background job, so this is the normal model there, not a special mode.
3. Shared counter: 4 × 1,000,000 increments
Code
Result (expected 4,000,000)
Ruby · 4 threads · c += 1
4,000,000 (3 / 3 runs)
Ruby · v = c; Thread.pass; c = v + 1
1,000,000 (3 / 3)
Ruby · same, inside Mutex#synchronize
4,000,000
Elixir · 4 processes · ETS lookup then insert
1,359,256 (1,334,673 – 1,406,974)
Elixir · ETS :ets.update_counter/3
4,000,000
Elixir · one Agent owning the counter, Agent.update
4,000,000
Elixir · :counters.add/3
4,000,000
Elixir has no shared variable to race on: a process’s state is its own. The race appears as soon as state moves into a shared store and the code reads, then writes. Separate ETS lookup and insert lose 66 % of the updates.
The fixes are atomic operations on the store (update_counter, :counters) or one owning process that receives the updates in turn (Agent, GenServer). That last one is the idiomatic default.
Ruby’s c += 1 is right under the GVL only because the GVL is never handed over inside it; put a release between the read and the write and 75 % are lost.
4. A blocked timer: 10 ms ticker next to fib(37)
Runtime · where fib(37) runs
CPU task
worst ticker lateness
Ruby · another Thread
177 ms
100.6 ms
Ruby · a Ractor
180 ms
0.5 ms
Elixir · another process, 4 schedulers
138 ms
1.0 ms
Elixir · another process, one scheduler (+S 1)
143 ms
1.0 ms
With one scheduler, the CPU-bound process and the ticker share a single core, and the ticker is still on time. Reduction-based preemption does what Ruby’s 100 ms time slice does, but in slices short enough not to matter.
All six Elixir runs reported exactly 1.0 ms. receive … after 10 works in whole milliseconds, so this reads as the timer’s own granularity, not as delay caused by fib.
Ruby gets the same result only by moving the work to a second interpreter: a Ractor (0.5 ms).
# Elixir — one process per request; Req is an HTTP client librarybodies = urls |> Task.async_stream(&Req.get!(&1).body, max_concurrency: 3) |> Enum.map(fn {:ok, b} -> b end)
# Elixir — one process owns the state; others send it messages{:ok, counter} = Agent.start_link(fn -> 0 end)1..4 |> Enum.map(fn _ -> Task.async(fn -> for _ <- 1..1_000, do: Agent.update(counter, &(&1 + 1)) end) end) |> Task.await_many()
Pitfalls
Ruby
Elixir
A CPU-heavy thread adds up to 100 ms to every other thread’s wait
A long NIF (native code) blocks its scheduler; mark it dirty or keep it short
Code safe only because of the GVL (`@x
A crashed thread can leave shared objects half-updated
One process owning hot state (a single GenServer) becomes a bottleneck: its mailbox serialises everything
Ractors: most gems are not Ractor-safe
Large messages are copied between heaps; pass references (ETS keys, binaries) instead of big terms
Timeout.timeout raises into a thread at any line
An unbounded mailbox (a producer faster than its consumer) grows until memory runs out
Which one for what
Workload
Ruby
Elixir
Request/response web app, DB-bound
Puma: threads × processes
Phoenix: one process per request on every core
10,000+ live connections (WebSockets, presence)
fibers (async, Falcon) or M:N threads; usually a separate service
the default: a process per connection (Phoenix Channels)
CPU work in app code
fork/Sidekiq processes, Ractors
processes; nothing extra
Fault isolation
process boundaries (Puma workers, Sidekiq)
supervisors restart crashed processes in place
Method
Setup
Details
Ruby
4.0.9, image ruby:4.0, --yjit; async 2.46.0
Elixir
1.20.4 on Erlang/OTP 29 (JIT), image elixir:1.20; default 4 schedulers on 4 cores, --erl +S1:1 for the one-scheduler lag run
CPU
AMD Ryzen AI Max+ 395, 4 cores (docker --cpuset-cpus=8-11), host not isolated
Runs
6 rounds of every test; only rounds whose pinned cores were ≥ 90 % idle at the start count: rounds 2, 3, 5 (92–96 %, 92–96 %, 94–97 % idle); rounds 1, 4, 6 dropped (64–69 %, 51–58 %, 82–88 %). Median of the 3 kept rounds, ranges where the spread matters
docker run --rm --cpuset-cpus=8-11 -v "$PWD":/b -w /b elixir:1.20 elixir conc.exs cpu processesdocker run --rm --cpuset-cpus=8-11 -v "$PWD":/b -w /b elixir:1.20 elixir --erl +S1:1 conc.exs lag scheduler1docker run --rm --cpuset-cpus=8-11 -v "$PWD":/b -w /b elixir:1.20 elixir conc.exs race ets_read_writedocker run --rm --cpuset-cpus=8-11 -e GEM_HOME=/b/gems -v "$PWD":/b -w /b ruby:4.0 ruby --yjit conc.rb lag thread
conc.exs:
# Elixir side of "Ruby vs Elixir concurrency". Usage: elixir [--erl "+S 1:1"] conc.exs <test> <mode>defmodule C do def fib(n) when n < 2, do: n def fib(n), do: fib(n - 1) + fib(n - 2) def now, do: System.monotonic_time(:microsecond) / 1_000_000 def rss_mb do File.read!("/proc/self/status") |> then(&Regex.run(~r/VmRSS:\s+(\d+)/, &1)) |> Enum.at(1) |> String.to_integer() |> Kernel./(1024) end def f(x, d), do: :erlang.float_to_binary(x / 1, decimals: d) def ticker(worst, parent) do t = now() receive do :stop -> send(parent, {:worst, worst}) after 10 -> ticker(max(worst, now() - t - 0.01), parent) end endend[test, mode] = System.argv()n_cpu = 4; fibn = 35; n_io = 10_000case test do "cpu" -> t = C.now() case mode do "seq" -> for _ <- 1..n_cpu, do: C.fib(fibn) "processes" -> 1..n_cpu |> Enum.map(fn _ -> Task.async(fn -> C.fib(fibn) end) end) |> Enum.map(&Task.await(&1, :infinity)) end IO.puts("cpu #{String.pad_trailing(mode, 10)} #{C.f(C.now() - t, 3)} s schedulers #{System.schedulers_online()}") "io" -> t = C.now() 1..n_io |> Enum.map(fn _ -> Task.async(fn -> Process.sleep(100) end) end) |> Enum.each(&Task.await(&1, :infinity)) IO.puts("io #{String.pad_trailing(mode, 10)} #{C.f(C.now() - t, 3)} s rss #{C.f(C.rss_mb(), 0)} MB") "race" -> # 4 processes x 1,000,000 increments of one shared counter run = fn f -> 1..4 |> Enum.map(fn _ -> Task.async(fn -> for _ <- 1..1_000_000, do: f.() end) end) |> Enum.each(&Task.await(&1, :infinity)) end result = case mode do "ets_read_write" -> tab = :ets.new(:c, [:public, write_concurrency: true]); :ets.insert(tab, {:n, 0}) run.(fn -> [{:n, v}] = :ets.lookup(tab, :n); :ets.insert(tab, {:n, v + 1}) end) [{:n, v}] = :ets.lookup(tab, :n); v "ets_update_counter" -> tab = :ets.new(:c, [:public, write_concurrency: true]); :ets.insert(tab, {:n, 0}) run.(fn -> :ets.update_counter(tab, :n, 1) end) [{:n, v}] = :ets.lookup(tab, :n); v "agent" -> {:ok, a} = Agent.start_link(fn -> 0 end) run.(fn -> Agent.update(a, &(&1 + 1)) end) Agent.get(a, & &1) "counters" -> ref = :counters.new(1, [:write_concurrency]) run.(fn -> :counters.add(ref, 1, 1) end) :counters.get(ref, 1) end IO.puts("race #{mode} #{result} (expected 4000000)") "lag" -> # a 10 ms ticker process next to a CPU-bound process me = self() tk = spawn(fn -> C.ticker(0.0, me) end) Process.sleep(50) t = C.now() Task.async(fn -> C.fib(37) end) |> Task.await(:infinity) took = C.now() - t send(tk, :stop) worst = receive do {:worst, w} -> w end IO.puts("lag #{String.pad_trailing(mode, 10)} worst ticker lateness #{C.f(worst * 1000, 1)} ms (cpu task #{C.f(took * 1000, 0)} ms, schedulers #{System.schedulers_online()})")end
conc.rb:
# Ruby side of the concurrency comparisons. Usage: ruby conc.rb <test> <mode>require "etc"def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)def rss_mb = File.read("/proc/self/status")[/VmRSS:\s+(\d+)/, 1].to_i / 1024.0def fib(n) = n < 2 ? n : fib(n - 1) + fib(n - 2)N_CPU = 4; FIB = 35; N_IO = 10_000; WAIT = 0.1test, mode = ARGVcase testwhen "cpu" # 4 × fib(35), sequential vs threads vs ractors vs forked processes t = now case mode when "seq" then N_CPU.times { fib(FIB) } when "threads" then N_CPU.times.map { Thread.new { fib(FIB) } }.each(&:join) when "ractors" rs = N_CPU.times.map { Ractor.new { def f(n) = n < 2 ? n : f(n - 1) + f(n - 2); f(35) } } rs.each(&:value) when "fork" then N_CPU.times.map { fork { fib(FIB) } }.each { Process.wait(_1) } end puts format("cpu %-8s %.3f s", mode, now - t)when "io" # 10,000 concurrent 100 ms waits t = now case mode when "threads" then N_IO.times.map { Thread.new { sleep WAIT } }.each(&:join) when "fibers" require "async" Async { |task| N_IO.times.map { task.async { sleep WAIT } }.each(&:wait) } end puts format("io %-8s %.3f s rss %.0f MB", mode, now - t, rss_mb)when "race" # 4 threads × 1,000,000 increments of one shared counter c = 0; m = Mutex.new ths = 4.times.map do Thread.new do case mode when "plain" then 1_000_000.times { c += 1 } when "mutex" then 1_000_000.times { m.synchronize { c += 1 } } when "yield" then 1_000_000.times { v = c; Thread.pass; c = v + 1 } # GVL released between read and write, as any I/O call does when "yield_mutex" then 1_000_000.times { m.synchronize { v = c; Thread.pass; c = v + 1 } } end end end ths.each(&:join) puts "race #{mode} #{c} (expected 4000000)"when "lag" # a 10 ms ticker next to a CPU-bound thread: worst lateness worst = 0.0; stop = false ticker = Thread.new do until stop t = now; sleep 0.01; late = now - t - 0.01; worst = late if late > worst end end sleep 0.05 t0 = now case mode when "thread" then Thread.new { fib(37) }.join when "ractor" then Ractor.new { def f(n) = n < 2 ? n : f(n - 1) + f(n - 2); f(37) }.value end took = now - t0 stop = true; ticker.join puts format("lag %-8s worst ticker lateness %.1f ms (cpu task %.0f ms)", mode, worst * 1000, took * 1000)end