JavaScript vs Ruby concurrency

Both languages are called “single-threaded”, and both run web servers that hold thousands of connections. They get there in opposite ways. Ruby gives you real OS threads and one lock (the GVL) that lets only one of them run Ruby code at a time. JavaScript gives you exactly one thread and an event loop, and it never switches tasks behind your back. Each choice has a cost you can measure.

At a glance

Ruby (MRI 4.0)JavaScript (Node 24 / browsers)
Unit of concurrencyThread (OS thread), Fibercallback / Promise / async function
Who switches tasksthe VM, preemptively: every 100 ms, and on every blocking callyour code, only at await or when a callback returns
Runs Ruby/JS code in parallel in one interpreter?✗ one thread holds the GVL✗ one thread, full stop
ParallelismRactor (experimental), fork / Puma workersworker_threads / Web Workers, cluster
Shared mutable stateeverything, between threadsnothing by default; SharedArrayBuffer opt-in
Data racespossible; the GVL hides some of themimpossible on one thread; possible on SharedArrayBuffer
What blocks everythinga C extension that keeps the GVLany synchronous code: a loop, JSON.parse of 50 MB, fs.readFileSync
Async I/Othreads, or fibers + Fiber::Scheduler (Ruby 3.0+, e.g. the async gem)built in: libuv (Node), the browser’s network stack

The two models

Ruby threads hand the GVL over every 100 ms; JavaScript runs each task to completion on one thread Ruby (MRI): threads take turns holding the GVL thread A · CPU runs queued for GVL runs thread B · CPU runs runs thread C · I/O in the kernel, GVL released 100 ms timer: the GVL is handed to the next thread JavaScript: one thread, each task runs to completion main thread fib(37), no await next task idle: waits for events libuv / kernel socket + fs I/O in parallel 10 ms timer due here; its callback (amber) runs only after the task (measured: 156.3 ms late) ▲ microtasks (promise callbacks) drain before the timer 0 ms 100 ms 200 ms 300 ms 400 ms
Schematic of the lag test measured below. MRI preempts a CPU-bound thread after 100 ms (measured: 100.6 ms worst wait); JavaScript never preempts, so a 10 ms timer waits for the whole synchronous task (measured: 156.3 ms).
Ruby threads hand the GVL over every 100 ms; JavaScript runs each task to completion on one thread Ruby: threads share one GVL thread A · CPU runs queued runs thread B · CPU runs runs thread C · I/O I/O, no GVL 100 ms: GVL handoff JavaScript: run to completion main thread sync task next idle libuv / kernel I/O in parallel timer runs after the task ▲ microtasks before the timer 0 ms 100 ms 200 ms 300 ms 400 ms
Schematic of the lag test measured below. MRI preempts a CPU-bound thread after 100 ms (measured: 100.6 ms worst wait); JavaScript never preempts, so a 10 ms timer waits for the whole synchronous task (measured: 156.3 ms).

Ruby: threads and one lock

JavaScript: one thread and an event loop

Measured: four tests, same 4 cores

Ruby 4.0.9 with YJIT, Node 24.22.2, both in Docker on the same 4 cores (--cpuset-cpus=8-11 of an AMD Ryzen AI Max+ 395), median of 3 runs. Scripts and commands are at the end.

Measured: CPU work only scales with Ractors, fork or worker_threads; 10,000 waits cost 0.104 s in Node, 0.338–1.039 s in Ruby CPU-bound: 4 × fib(35) on 4 cores Ruby · sequential 0.268 s Ruby · 4 threads 0.268 s Ruby · 4 Ractors 0.076 s Ruby · 4 processes (fork) 0.074 s Node · sequential 0.238 s Node · 4 async functions 0.242 s Node · 4 worker_threads 0.091 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.039 s · 192 MB Ruby · 10,000 threads, M:N 0.338 s · 147 MB Ruby · 10,000 fibers (async) 0.350 s · 133 MB Node · 10,000 promises 0.104 s · 56 MB 0 s 0.4 s 0.8 s 1.2 s ideal 0.100 s
Medians of 3 runs, Ruby 4.0.9 + YJIT and Node 24.22.2, each pinned to the same 4 cores. Threads and async functions take as long as the sequential loop; only a second interpreter (Ractor, forked process, worker isolate) adds cores. Dark bars Ruby, light bars Node.
Measured: CPU work only scales with Ractors, fork or worker_threads; 10,000 waits cost 0.104 s in Node, 0.338–1.039 s in Ruby CPU: 4 × fib(35), 4 cores wall time, shorter is better Ruby · sequential 0.268 s Ruby · 4 threads 0.268 s Ruby · 4 Ractors 0.076 s Ruby · 4 processes (fork) 0.074 s Node · sequential 0.238 s Node · 4 async functions 0.242 s Node · 4 worker_threads 0.091 s I/O: 10,000 × 100 ms waits wall time · resident memory Ruby · 10,000 threads 1.039 s · 192 MB Ruby · 10,000 threads, M:N 0.338 s · 147 MB Ruby · 10,000 fibers (async) 0.350 s · 133 MB Node · 10,000 promises 0.104 s · 56 MB dashed amber tick: ideal 0.100 s
Medians of 3 runs, Ruby 4.0.9 + YJIT and Node 24.22.2 on the same 4 cores. Dark bars Ruby, light bars Node.

1. CPU-bound: 4 × fib(35)

Rubywallspeed-upNodewallspeed-up
sequential0.268 s1.0×sequential0.238 s1.0×
4 threads0.268 s1.0×4 async functions0.242 s1.0×
4 Ractors0.076 s3.5×4 worker_threads0.091 s2.6×
4 processes (fork)0.074 s3.6×

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

Runtime · primitivewallover the 0.100 s idealRSS
Node · 10,000 promises (setTimeout)0.104 s+4 ms56 MB
Ruby · 10,000 threads, M:N (RUBY_MN_THREADS=1)0.338 s+238 ms147 MB
Ruby · 10,000 fibers (async 2.46)0.350 s+250 ms133 MB
Ruby · 10,000 threads (default 1:1)1.039 s+939 ms192 MB

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

CodeResult (expected 4,000,000)
Ruby MRI · 4 threads · c += 14,000,000 (3 / 3 runs)
Ruby MRI · 4 threads · v = c; Thread.pass; c = v + 11,000,000 (3 / 3)
Ruby MRI · same, inside Mutex#synchronize4,000,000
JRuby 10.0.8 · 4 threads · c += 11,597,031 (1,231,887 – 1,680,228)
JRuby 10.0.8 · Mutex#synchronize { c += 1 }4,000,000
Node · 4 async functions on one thread · a[0] = a[0] + 14,000,000
Node · 4 worker_threads on a SharedArrayBuffer · a[0] = a[0] + 12,246,884 (1,710,897 – 3,552,195)
Node · same, Atomics.add(a, 0, 1)4,000,000

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

Runtime · where fib(37) runsworst ticker lateness
Ruby · another Thread100.6 ms
Ruby · a Ractor1.2 ms
Node · the main thread156.3 ms (267–308 ms in a re-run with the host’s load average at 18)
Node · a worker_thread1.8 ms

The same task in both

Three HTTP requests at once:

# Ruby, threads — works everywhere, one OS thread per request
bodies = urls.map { |u| Thread.new { Net::HTTP.get(URI(u)) } }.map(&:value)

# 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
// JavaScript — fetch never blocks; Promise.all waits for all three
const bodies = await Promise.all(urls.map(async (u) => (await fetch(u)).text()));

A CPU-heavy job off the request path:

# Ruby — a Ractor has its own GVL; the block may only touch shareable objects
r = Ractor.new(rows) { |rows| rows.sum { |row| expensive(row) } }
total = r.value
// Node — a worker has its own isolate; data arrives by structured clone
import { Worker } from "node:worker_threads";
const total = await new Promise((ok, ko) =>
  new Worker(new URL("./sum.js", import.meta.url), { workerData: rows })
    .on("message", ok).on("error", ko));

Pitfalls

RubyJavaScript
Unsynchronised `@ivar
A C extension that never releases the GVL blocks every threadfs.readFileSync, a long loop or a large JSON.parse blocks every request
Timeout.timeout raises into a thread at any line, even inside ensureFour slow fs/crypto/zlib calls fill the 4-thread libuv pool; the fifth waits
Ractors: most gems are not Ractor-safe yet (non-shareable constants, global state)Workers: no shared heap; copying a large object costs a full serialisation
fork after threads start: only the forking thread survives in the childSharedArrayBuffer without Atomics races exactly like C

Which one for what

WorkloadRubyJavaScript
Request/response web app, DB-boundPuma: threads per process × processes per boxone event loop per process × cluster / several containers
10,000+ idle connections (WebSockets, SSE)fibers (async, Falcon) or M:N threadsthe default model; 56 MB for 10,000 waits
CPU work in the request pathanother process (Sidekiq) or a Ractora worker_thread, or another service
Code that must not raceMutex, Queue, concurrent-rubyfree on one thread; Atomics across workers

Method

SetupDetails
Ruby4.0.9, image ruby:4.0, --yjit; async 2.46.0 · JRuby 10.0.8.0 on OpenJDK 21.0.13 (race test only)
Node24.22.2, image node:24
CPUAMD Ryzen AI Max+ 395, 4 cores (docker --cpuset-cpus=8-11), host not isolated
Runs3 process runs per test, median reported; ranges where the spread matters · host not idle (load average 5.7 during the main matrix)
docker run --rm --cpuset-cpus=8-11 -e GEM_HOME=/b/gems -v "$PWD":/b -w /b ruby:4.0 gem install async --no-document
docker run --rm --cpuset-cpus=8-11 -e GEM_HOME=/b/gems -v "$PWD":/b -w /b ruby:4.0 ruby --yjit conc.rb cpu ractors
docker run --rm --cpuset-cpus=8-11 -e GEM_HOME=/b/gems -e RUBY_MN_THREADS=1 -v "$PWD":/b -w /b ruby:4.0 ruby --yjit conc.rb io threads
docker run --rm --cpuset-cpus=8-11 -v "$PWD":/b -w /b jruby:10.0.8.0-jdk21 jruby conc.rb race plain
docker run --rm --cpuset-cpus=8-11 -v "$PWD":/b -w /b node:24 node conc.mjs race workers

conc.rb:

# Ruby side of "JavaScript vs Ruby concurrency". 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
  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
  stop = true; ticker.join
  puts format("lag %-8s worst ticker lateness %.1f ms", mode, worst * 1000)
end

conc.mjs:

// JavaScript (Node) side of "JavaScript vs Ruby concurrency". Usage: node conc.mjs <test> <mode>
import { Worker, isMainThread, workerData, parentPort } from "node:worker_threads";
const now = () => performance.now() / 1000;
const fib = (n) => (n < 2 ? n : fib(n - 1) + fib(n - 2));
const N_CPU = 4, FIB = 35, N_IO = 10_000, WAIT = 100;
const runWorker = (data) => new Promise((ok, ko) => {
  const w = new Worker(new URL(import.meta.url), { workerData: data });
  w.on("message", ok); w.on("error", ko);
});

if (!isMainThread) {
  const d = workerData;
  if (d.kind === "fib") parentPort.postMessage(fib(d.n));
  if (d.kind === "inc") {
    const a = new Int32Array(d.sab);
    if (d.atomic) for (let i = 0; i < 1_000_000; i++) Atomics.add(a, 0, 1);
    else for (let i = 0; i < 1_000_000; i++) a[0] = a[0] + 1;
    parentPort.postMessage(0);
  }
} else {
  const [test, mode] = process.argv.slice(2);
  if (test === "cpu") {
    const t = now();
    if (mode === "seq") for (let i = 0; i < N_CPU; i++) fib(FIB);
    if (mode === "promises") await Promise.all([...Array(N_CPU)].map(async () => fib(FIB)));
    if (mode === "workers") await Promise.all([...Array(N_CPU)].map(() => runWorker({ kind: "fib", n: FIB })));
    console.log(`cpu ${mode.padEnd(8)} ${(now() - t).toFixed(3)} s`);
  }
  if (test === "io") {
    const t = now();
    await Promise.all([...Array(N_IO)].map(() => new Promise((r) => setTimeout(r, WAIT))));
    console.log(`io  ${mode.padEnd(8)} ${(now() - t).toFixed(3)} s  rss ${(process.memoryUsage().rss / 2 ** 20).toFixed(0)} MB`);
  }
  if (test === "race") {
    const sab = new SharedArrayBuffer(4);
    if (mode === "single") { // async tasks on the one thread
      const a = new Int32Array(sab);
      await Promise.all([...Array(4)].map(async () => { for (let i = 0; i < 1_000_000; i++) a[0] = a[0] + 1; }));
    } else {
      await Promise.all([...Array(4)].map(() => runWorker({ kind: "inc", sab, atomic: mode === "atomics" })));
    }
    console.log(`race ${mode} ${new Int32Array(sab)[0]} (expected 4000000)`);
  }
  if (test === "lag") {
    let worst = 0, last = now(), stop = false;
    const tick = () => { const t = now(); const late = t - last - 0.01; if (late > worst) worst = late; last = t; if (!stop) setTimeout(tick, 10); };
    setTimeout(tick, 10);
    await new Promise((r) => setTimeout(r, 50));
    if (mode === "main") fib(37);
    if (mode === "worker") await runWorker({ kind: "fib", n: 37 });
    await new Promise((r) => setTimeout(r, 30));
    stop = true;
    console.log(`lag ${mode.padEnd(8)} worst ticker lateness ${(worst * 1000).toFixed(1)} ms`);
  }
}

Questions? Let's Chat :)

concurrency