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 concurrency
Thread (OS thread), Fiber
callback / Promise / async function
Who switches tasks
the VM, preemptively: every 100 ms, and on every blocking call
your 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
Parallelism
Ractor (experimental), fork / Puma workers
worker_threads / Web Workers, cluster
Shared mutable state
everything, between threads
nothing by default; SharedArrayBuffer opt-in
Data races
possible; the GVL hides some of them
impossible on one thread; possible on SharedArrayBuffer
What blocks everything
a C extension that keeps the GVL
any synchronous code: a loop, JSON.parse of 50 MB, fs.readFileSync
Async I/O
threads, or fibers + Fiber::Scheduler (Ruby 3.0+, e.g. the async gem)
built in: libuv (Node), the browser’s network stack
The two models
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).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
A Thread is a real OS thread. To run Ruby code it must hold the Global VM Lock (GVL).
A thread releases the GVL when it blocks: socket and file I/O, sleep, Queue#pop, and C code that calls rb_thread_call_without_gvl (zlib, many database drivers).
A CPU-bound thread is preempted after a 100 ms time slice (TIME_QUANTUM_MSEC in thread_pthread.c). The lag test below sees exactly that: 100.6 ms.
Because preemption can land between any two VM instructions that check for interrupts, shared state needs a Mutex, Queue or Concurrent::* structure.
Fibers are user-space coroutines. With a Fiber::Scheduler installed (Ruby 3.0+, the async gem), Net::HTTP, sleep and socket reads yield the fiber instead of blocking the thread — the same idea as await, without the keyword.
M:N threads (Ruby 3.3+, RUBY_MN_THREADS=1) run many Ruby threads on a few native threads (RUBY_MAX_CPU, default 8 per the Ruby 3.3 NEWS). Measured below: the 10,000-thread wait test finishes 3.1× sooner (1.039 s → 0.338 s).
Parallelism needs a second GVL: a Ractor (each one has its own; objects passed between them are copied, moved or deep-frozen), or a second process (fork, Puma workers, Sidekiq processes).
JavaScript: one thread and an event loop
Your code runs on one thread. A function runs to completion; nothing interrupts it.
I/O is started and handed off. Node’s libuv waits on sockets with epoll/kqueue/IOCP and runs file system, dns.lookup, crypto.pbkdf2 and zlib work on a thread pool of 4 (UV_THREADPOOL_SIZE, up to 1024). Browsers do the same with their own network stack.
When I/O finishes, a callback is queued. The loop takes one callback, runs it, then drains the microtask queue (process.nextTick, then promise reactions) before the next callback.
await is the only switch point. Code between two awaits is atomic with respect to other tasks — so a counter on one thread can never lose an update.
The price: anything synchronous stalls every other request. The lag test below: a 10 ms timer fired 156.3 ms late behind one fib(37) call.
Parallelism needs a second isolate: worker_threads (Node) or Web Workers, each with its own heap and event loop, talking by postMessage (structured clone) or sharing a SharedArrayBuffer coordinated with Atomics. Browsers expose SharedArrayBuffer only to cross-origin-isolated pages (COOP + COEP headers).
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.
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.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)
Ruby
wall
speed-up
Node
wall
speed-up
sequential
0.268 s
1.0×
sequential
0.238 s
1.0×
4 threads
0.268 s
1.0×
4 async functions
0.242 s
1.0×
4 Ractors
0.076 s
3.5×
4 worker_threads
0.091 s
2.6×
4 processes (fork)
0.074 s
3.6×
Threads and async functions add nothing to CPU work: one GVL, one thread.
With YJIT, one Ruby fib(35) (0.268 s / 4 = 67 ms) is within 13 % of V8’s (0.238 s / 4 = 60 ms).
Against a perfect 4× split (0.238 s / 4 = 0.060 s), workers take 31 ms longer (four V8 isolates to start, results to post back). Ractors and fork land 9 ms and 7 ms over their ideal (0.067 s).
2. I/O-bound: 10,000 concurrent 100 ms waits
Runtime · primitive
wall
over the 0.100 s ideal
RSS
Node · 10,000 promises (setTimeout)
0.104 s
+4 ms
56 MB
Ruby · 10,000 threads, M:N (RUBY_MN_THREADS=1)
0.338 s
+238 ms
147 MB
Ruby · 10,000 fibers (async 2.46)
0.350 s
+250 ms
133 MB
Ruby · 10,000 threads (default 1:1)
1.039 s
+939 ms
192 MB
A pending promise is a small heap object; a Ruby thread is an OS thread with its own stack, a fiber a VM stack.
Every primitive waits the same 100 ms; the gap above it is the cost of creating and scheduling 10,000 tasks. At 3–5 threads per Puma process (Rails 7.2 lowered the generated config/puma.rb default to 3, per its release notes) the difference is noise; at 10,000 WebSockets per process it decides the architecture.
3. Shared counter: 4 × 1,000,000 increments
Code
Result (expected 4,000,000)
Ruby MRI · 4 threads · c += 1
4,000,000 (3 / 3 runs)
Ruby MRI · 4 threads · v = c; Thread.pass; c = v + 1
1,000,000 (3 / 3)
Ruby MRI · same, inside Mutex#synchronize
4,000,000
JRuby 10.0.8 · 4 threads · c += 1
1,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] + 1
4,000,000
Node · 4 worker_threads on a SharedArrayBuffer · a[0] = a[0] + 1
2,246,884 (1,710,897 – 3,552,195)
Node · same, Atomics.add(a, 0, 1)
4,000,000
MRI’s c += 1 survived only because the GVL is never handed over inside that instruction sequence. That is an implementation detail: JRuby runs the same line without a GVL and loses 60 % of the updates.
Put a GVL release between the read and the write (measured with Thread.pass; a database call or any other blocking I/O releases it the same way) and MRI loses 75 %: all four threads read the same value, so four increments collapse into one.
JavaScript cannot race on one thread. The moment memory is shared between workers it races like C, and Atomics is the fix.
4. A blocked timer: 10 ms ticker next to fib(37)
Runtime · where fib(37) runs
worst ticker lateness
Ruby · another Thread
100.6 ms
Ruby · a Ractor
1.2 ms
Node · the main thread
156.3 ms (267–308 ms in a re-run with the host’s load average at 18)
Node · a worker_thread
1.8 ms
Ruby’s preemption caps the damage at one 100 ms time slice per turn — what a request thread sees on a Puma process whose neighbour thread is busy rendering or parsing.
JavaScript has no cap: the timer waits for the whole synchronous call, however long it runs (156 ms here).
Off-loading the CPU work to a second interpreter brings both down to ~1–2 ms.
The same task in both
Three HTTP requests at once:
# Ruby, threads — works everywhere, one OS thread per requestbodies = urls.map { |u| Thread.new { Net::HTTP.get(URI(u)) } }.map(&:value)# Ruby, fibers — Net::HTTP becomes non-blocking under the Fiber schedulerrequire "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 threeconst 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 objectsr = Ractor.new(rows) { |rows| rows.sum { |row| expensive(row) } }total = r.value
// Node — a worker has its own isolate; data arrives by structured cloneimport { 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
Ruby
JavaScript
Unsynchronised `@ivar
A C extension that never releases the GVL blocks every thread
fs.readFileSync, a long loop or a large JSON.parse blocks every request
Timeout.timeout raises into a thread at any line, even inside ensure
Four 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 child
SharedArrayBuffer without Atomics races exactly like C
Which one for what
Workload
Ruby
JavaScript
Request/response web app, DB-bound
Puma: threads per process × processes per box
one event loop per process × cluster / several containers
# 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.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 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`); }}