Ruby vs Elixir concurrency

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 concurrencyThread (OS thread), Fiberprocess (spawn, Task, GenServer): a few KB, its own heap
Who switches tasksthe VM, every 100 ms, and on blocking callsthe 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 stateeverything, between threadsnone between processes; ETS tables, :counters, :atomics as explicit shared stores
Communicationshared objects + Mutex/Queuemessage passing (copied), send/receive
Failure handlingan exception kills its thread; the rest go on in a possibly broken statea crash kills one process; supervisors restart it (“let it crash”)
GCone heap, shared by all threadsone heap per process, collected independently
What blocks a corea C extension that keeps the GVLa long NIF (native function) that is not run on a dirty scheduler

The two schedulers

Ruby lets a CPU-bound thread hold the GVL for 100 ms; the BEAM preempts every process after a reduction budget, even on one scheduler Ruby (MRI): the GVL changes hands every 100 ms thread A · CPU fib(37) runs runs again ticker thread due at 10 ms, waits for the GVL due again, waits 100 ms time slice (measured: 100.6 ms late) 0 ms 50 ms 100 ms 150 ms 200 ms Elixir (BEAM), one scheduler: preempted every reduction budget fib process ticker process the ticker runs every 10 ms beside fib(37) on the same core (measured: 1.0 ms late) 0 ms 50 ms 100 ms 150 ms 200 ms
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 lets a CPU-bound thread hold the GVL for 100 ms; the BEAM preempts every process after a reduction budget, even on one scheduler Ruby: GVL every 100 ms thread A · CPU runs runs ticker thread waits waits 100.6 ms late 0 ms 50 ms 100 ms 150 ms 200 ms BEAM, 1 scheduler: preemptive fib process ticker process ticker on time: 1.0 ms late 0 ms 50 ms 100 ms 150 ms 200 ms
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

Elixir: processes on the BEAM

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.

Measured: Elixir processes use all 4 cores with no extra API and hold 10,000 waits in 0.134 s; Ruby needs Ractors or fork for cores and fibers or M:N threads for waits CPU-bound: 4 × fib(35) on 4 cores Ruby · sequential 0.266 s Ruby · 4 threads 0.266 s Ruby · 4 Ractors 0.075 s Ruby · 4 processes (fork) 0.072 s Elixir · sequential 0.211 s Elixir · 4 processes (Task) 0.058 s 0 s 0.1 s 0.2 s 0.3 s I/O-bound: 10,000 concurrent 100 ms waits · wall time · RSS Ruby · 10,000 threads 1.023 s · 192 MB Ruby · 10,000 threads, M:N 0.333 s · 147 MB Ruby · 10,000 fibers (async) 0.351 s · 133 MB Elixir · 10,000 processes 0.134 s · 126 MB 0 s 0.4 s 0.8 s 1.2 s ideal 0.100 s
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.
Measured: Elixir processes use all 4 cores with no extra API and hold 10,000 waits in 0.134 s; Ruby needs Ractors or fork for cores and fibers or M:N threads for waits CPU: 4 × fib(35), 4 cores wall time, shorter is better Ruby · sequential 0.266 s Ruby · 4 threads 0.266 s Ruby · 4 Ractors 0.075 s Ruby · 4 processes (fork) 0.072 s Elixir · sequential 0.211 s Elixir · 4 processes (Task) 0.058 s I/O: 10,000 × 100 ms waits wall time · resident memory Ruby · 10,000 threads 1.023 s · 192 MB Ruby · 10,000 threads, M:N 0.333 s · 147 MB Ruby · 10,000 fibers (async) 0.351 s · 133 MB Elixir · 10,000 processes 0.134 s · 126 MB dashed amber tick: ideal 0.100 s
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)

Rubywallspeed-upElixirwallspeed-up
sequential0.266 s1.0×sequential0.211 s1.0×
4 threads0.266 s1.0×4 processes (Task.async)0.058 s3.6×
4 Ractors0.075 s3.5×
4 processes (fork)0.072 s3.7×

2. I/O-bound: 10,000 concurrent 100 ms waits

Runtime · primitivewallover the 0.100 s idealRSS
Elixir · 10,000 processes (Process.sleep)0.134 s+34 ms126 MB
Ruby · 10,000 threads, M:N (RUBY_MN_THREADS=1)0.333 s+233 ms147 MB
Ruby · 10,000 fibers (async 2.46)0.351 s+251 ms133 MB
Ruby · 10,000 threads (default 1:1)1.023 s+923 ms192 MB

3. Shared counter: 4 × 1,000,000 increments

CodeResult (expected 4,000,000)
Ruby · 4 threads · c += 14,000,000 (3 / 3 runs)
Ruby · v = c; Thread.pass; c = v + 11,000,000 (3 / 3)
Ruby · same, inside Mutex#synchronize4,000,000
Elixir · 4 processes · ETS lookup then insert1,359,256 (1,334,673 – 1,406,974)
Elixir · ETS :ets.update_counter/34,000,000
Elixir · one Agent owning the counter, Agent.update4,000,000
Elixir · :counters.add/34,000,000

4. A blocked timer: 10 ms ticker next to fib(37)

Runtime · where fib(37) runsCPU taskworst ticker lateness
Ruby · another Thread177 ms100.6 ms
Ruby · a Ractor180 ms0.5 ms
Elixir · another process, 4 schedulers138 ms1.0 ms
Elixir · another process, one scheduler (+S 1)143 ms1.0 ms

The same task in both

Three HTTP requests at once:

# Ruby, fibers — Net::HTTP becomes non-blocking under the Fiber scheduler
require "async"
bodies = Async { |task| urls.map { |u| task.async { Net::HTTP.get(URI(u)) } }.map(&:wait) }.wait
# Elixir — one process per request; Req is an HTTP client library
bodies = urls |> Task.async_stream(&Req.get!(&1).body, max_concurrency: 3) |> Enum.map(fn {:ok, b} -> b end)

State that many tasks update:

# Ruby — shared object + lock
counter = 0
lock = Mutex.new
threads = 4.times.map { Thread.new { 1_000.times { lock.synchronize { counter += 1 } } } }
threads.each(&:join)
# 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

RubyElixir
A CPU-heavy thread adds up to 100 ms to every other thread’s waitA 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-updatedOne process owning hot state (a single GenServer) becomes a bottleneck: its mailbox serialises everything
Ractors: most gems are not Ractor-safeLarge messages are copied between heaps; pass references (ETS keys, binaries) instead of big terms
Timeout.timeout raises into a thread at any lineAn unbounded mailbox (a producer faster than its consumer) grows until memory runs out

Which one for what

WorkloadRubyElixir
Request/response web app, DB-boundPuma: threads × processesPhoenix: one process per request on every core
10,000+ live connections (WebSockets, presence)fibers (async, Falcon) or M:N threads; usually a separate servicethe default: a process per connection (Phoenix Channels)
CPU work in app codefork/Sidekiq processes, Ractorsprocesses; nothing extra
Fault isolationprocess boundaries (Puma workers, Sidekiq)supervisors restart crashed processes in place

Method

SetupDetails
Ruby4.0.9, image ruby:4.0, --yjit; async 2.46.0
Elixir1.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
CPUAMD Ryzen AI Max+ 395, 4 cores (docker --cpuset-cpus=8-11), host not isolated
Runs6 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 processes
docker run --rm --cpuset-cpus=8-11 -v "$PWD":/b -w /b elixir:1.20 elixir --erl +S1:1 conc.exs lag scheduler1
docker run --rm --cpuset-cpus=8-11 -v "$PWD":/b -w /b elixir:1.20 elixir conc.exs race ets_read_write
docker 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
  end
end

[test, mode] = System.argv()
n_cpu = 4; fibn = 35; n_io = 10_000

case 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.0
def fib(n) = n < 2 ? n : fib(n - 1) + fib(n - 2)
N_CPU = 4; FIB = 35; N_IO = 10_000; WAIT = 0.1

test, mode = ARGV
case test
when "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

Questions? Let's Chat :)

concurrency