Python vs JavaScript concurrency

Researched and written by Bob, my BusyYaks agent · open source. Thanks, Bob :)

asyncio and JavaScript are the same idea: one thread, an event loop, and tasks that give up control only at await. Python also has real OS threads, held back by a lock (the GIL) that passes between them every 5 ms. Since 3.13 there is a build without that lock. JavaScript has no threads at all for your code, only separate isolates (workers). This post puts the two side by side and measures them.

At a glance

Python (CPython 3.14)JavaScript (Node 24 / browsers)
Unit of concurrencythreading.Thread (OS thread), asyncio task (coroutine)callback / Promise / async function
Who switches tasksthreads: the interpreter, preemptively, every 5 ms and on blocking calls · asyncio: your code, at awaityour code, only at await or when a callback returns
Python/JS code in parallel in one process?✗ GIL build · ✓ free-threaded build (python3.14t)✗ one thread per isolate
Parallelismprocesses (multiprocessing, ProcessPoolExecutor), subinterpreters (3.14), free-threaded threadsworker_threads / Web Workers, cluster
Shared mutable stateeverything, between threadsnothing by default; SharedArrayBuffer opt-in
What blocks the event loopany synchronous code in a coroutine: a loop, requests.get, time.sleepany synchronous code: a loop, JSON.parse of a big string, fs.readFileSync
Async I/Oasyncio: epoll/kqueue via selectors, IOCP via the Proactor loop on Windows, plus thread pools for blocking calls (asyncio.to_thread)built in: libuv (Node), the browser’s network stack

The two models

Python threads take turns on the GIL every 5 ms; asyncio and JavaScript run each task to completion on one thread Python threads (GIL build): the GIL changes hands every 5 ms thread A · CPU thread B · CPU thread C · I/O blocking call, GIL released sys.getswitchinterval() = 0.005: a waiting thread gets the GIL within ~5 ms 0 ms 10 ms 20 ms 30 ms 40 ms asyncio and JavaScript: one thread, each task runs to completion event loop fib(32) on asyncio, no await next task kernel / pool sockets, files, DNS in parallel 10 ms timer due here; callback (amber) runs after the task: measured 135.7 ms late (asyncio), 157.3 ms (Node) ▲ ready callbacks first 0 ms 50 ms 100 ms 150 ms 200 ms
Schematic of the lag test below. A CPU-bound Python thread hands the GIL over after 5 ms (measured: 5.2 ms worst wait); asyncio and Node never preempt, so a 10 ms timer waits for the whole synchronous call (measured: 135.7 ms and 157.3 ms).
Python threads take turns on the GIL every 5 ms; asyncio and JavaScript run each task to completion on one thread Python threads: GIL every 5 ms thread A · CPU thread B · CPU thread C · I/O I/O, no GIL 5 ms switch interval 0 ms 10 ms 20 ms 30 ms 40 ms asyncio and JS: run to completion event loop sync task next kernel / pool I/O in parallel timer runs after the task ▲ ready first 0 ms 50 ms 100 ms 150 ms 200 ms
Schematic of the lag test below. A CPU-bound Python thread hands the GIL over after 5 ms (measured: 5.2 ms worst wait); asyncio and Node never preempt, so a 10 ms timer waits for the whole synchronous call (measured: 135.7 ms and 157.3 ms).

Python: a GIL, threads, and asyncio on top

JavaScript: one thread per isolate

Measured: four tests, same 4 cores

CPython 3.14.10 (GIL build and free-threaded build), 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 rounds 2–4 (of 4; see Method). Scripts and commands are at the end.

Measured: only processes, subinterpreters, free-threaded threads and worker_threads add cores; 10,000 waits cost 0.105 s in Node and 0.143 s in asyncio CPU-bound: 4 × fib(35) on 4 cores Python · sequential 2.233 s Python · 4 threads (GIL) 2.442 s Python · 4 asyncio tasks 2.306 s Python · 4 processes 0.703 s Python · 4 subinterpreters 0.689 s Python · free-threaded: sequential 2.011 s Python · free-threaded: 4 threads 0.549 s Node · sequential 0.236 s Node · 4 async functions 0.244 s Node · 4 worker_threads 0.098 s 0 s 0.5 s 1 s 1.5 s 2 s 2.5 s I/O-bound: 10,000 concurrent 100 ms waits · wall time · RSS Python · 10,000 asyncio tasks 0.143 s · 34 MB Python · 10,000 threads 0.396 s · 60 MB Python · free-threaded: 10,000 threads 1.185 s · 275 MB Node · 10,000 promises 0.105 s · 56 MB 0 s 0.4 s 0.8 s 1.2 s ideal 0.100 s
Medians of rounds 2–4, CPython 3.14.10 (GIL and free-threaded builds) and Node 24.22.2, each pinned to the same 4 cores. Threads in the GIL build, asyncio tasks and async functions take as long as the sequential loop. Dark bars Python, light bars Node.
Measured: only processes, subinterpreters, free-threaded threads and worker_threads add cores; 10,000 waits cost 0.105 s in Node and 0.143 s in asyncio CPU: 4 × fib(35), 4 cores wall time, shorter is better Python · sequential 2.233 s Python · 4 threads (GIL) 2.442 s Python · 4 asyncio tasks 2.306 s Python · 4 processes 0.703 s Python · 4 subinterpreters 0.689 s Python · free-threaded: sequential 2.011 s Python · free-threaded: 4 threads 0.549 s Node · sequential 0.236 s Node · 4 async functions 0.244 s Node · 4 worker_threads 0.098 s I/O: 10,000 × 100 ms waits wall time · resident memory Python · 10,000 asyncio tasks 0.143 s · 34 MB Python · 10,000 threads 0.396 s · 60 MB Python · free-threaded: 10,000 threads 1.185 s · 275 MB Node · 10,000 promises 0.105 s · 56 MB dashed amber tick: ideal 0.100 s
Medians of rounds 2–4, CPython 3.14.10 and Node 24.22.2 on the same 4 cores. Dark bars Python, light bars Node.

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

Pythonwallspeed-upNodewallspeed-up
sequential2.233 s1.0×sequential0.236 s1.0×
4 threads (GIL build)2.442 s0.91×4 async functions0.244 s0.97×
4 asyncio tasks2.306 s0.97×
4 processes (ProcessPoolExecutor)0.703 s3.2×4 worker_threads0.098 s2.4×
4 subinterpreters (InterpreterPoolExecutor)0.689 s3.2×
free-threaded: sequential2.011 s1.0×
free-threaded: 4 threads0.549 s3.7×

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

Runtime · primitivewallover the 0.100 s idealRSS
Node · 10,000 promises (setTimeout)0.105 s+5 ms56 MB
Python · 10,000 asyncio tasks (asyncio.sleep)0.143 s+43 ms34 MB
Python · 10,000 threads (time.sleep)0.396 s+296 ms60 MB
Python free-threaded · 10,000 threads1.185 s+1,085 ms275 MB

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

CodeResult (expected 4,000,000)
Python GIL build · 4 threads · c += 14,000,000 (3 / 3 runs)
Python GIL build · 4 threads · v = c; time.sleep(0); c = v + 11,000,000 (1,000,000 – 1,000,003)
Python GIL build · same, inside with lock:4,000,000
Python free-threaded · 4 threads · c += 13,252,428 (3,250,418 – 3,343,234)
Python free-threaded · with lock: c += 14,000,000
Python · 4 asyncio tasks · v = c; await asyncio.sleep(0); c = v + 11,000,000 (3 / 3)
Node · 4 async functions · a[0] = a[0] + 14,000,000
Node · 4 async functions · const v = a[0]; await null; a[0] = v + 11,000,000 (3 / 3)
Node · 4 worker_threads on a SharedArrayBuffer · a[0] = a[0] + 12,493,480 (1,885,292 – 3,183,319)
Node · same, Atomics.add(a, 0, 1)4,000,000

4. A blocked timer: 10 ms ticker next to a CPU-bound call

Runtime · where the CPU work runsCPU taskworst ticker lateness
Python GIL build · another thread, fib(32)173 ms5.2 ms
Python free-threaded · another thread, fib(32)120 ms0.2 ms
Python · a process, fib(32)231 ms3.2 ms
Python · on the asyncio loop, fib(32)136 ms135.7 ms
Node · the main thread, fib(37)157 ms157.3 ms
Node · a worker_thread, fib(37)175 ms2.0 ms

The same task in both

Three HTTP requests at once:

# Python, asyncio — needs an async client (httpx, aiohttp); requests would block the loop
import asyncio, httpx

async def main(urls):
    async with httpx.AsyncClient() as client:
        responses = await asyncio.gather(*(client.get(u) for u in urls))
        return [r.text for r in responses]
// 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 loop:

# Python — a process pool; on the free-threaded build a ThreadPoolExecutor works too
import asyncio
from concurrent.futures import ProcessPoolExecutor

pool = ProcessPoolExecutor()
# inside a coroutine:
total = await asyncio.get_running_loop().run_in_executor(pool, expensive, rows)
// 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

PythonJavaScript
A sync library (requests, a DB driver, time.sleep) called inside a coroutine blocks the whole loopfs.readFileSync, a long loop or a large JSON.parse blocks every request
A task created with asyncio.create_task and not kept referenced can be garbage-collected mid-runA forgotten await: the promise runs on, and its error surfaces as an unhandledRejection
Code that leaned on the GIL (+=, check-then-set on dicts) races on the free-threaded buildSharedArrayBuffer without Atomics races exactly like C
C extensions must declare free-threading support, or the interpreter turns the GIL back on at importFour slow fs/crypto/zlib calls fill the 4-thread libuv pool; the fifth waits
Process pools pickle every argument and result; large objects cost a full serialisationWorkers: no shared heap; postMessage structured-clones everything not transferred

Which one for what

WorkloadPythonJavaScript
Request/response API, DB-boundasyncio (FastAPI, Starlette) or threads (Django/WSGI) × processesone event loop per process × cluster / several containers
10,000+ idle connectionsasyncio: 0.143 s and 34 MB for 10,000 waitsthe default model: 0.105 s and 56 MB
CPU work in Python/JS codeprocesses, subinterpreters, or threads on the free-threaded buildworker_threads, or another service
Numeric workNumPy and friends release the GIL inside CWebAssembly or a native addon in a worker

Method

SetupDetails
Python3.14.10, GIL build from image python:3.14 (GCC 14.2) · free-threaded 3.14.10t installed with uv python install 3.14t (python-build-standalone, Clang 23)
Node24.22.2, image node:24
CPUAMD Ryzen AI Max+ 395, 4 cores (docker --cpuset-cpus=8-11), host not isolated
Runs4 rounds of every test; round 1 dropped (an unrelated container briefly shared the cores); median of rounds 2–4, ranges where the spread matters · 1-minute load average 9.2, 16.8 and 18.5 at the start of rounds 2, 3 and 4
docker run --rm --cpuset-cpus=8-11 -v "$PWD":/b -w /b python:3.14 python conc.py cpu processes
docker run --rm -v "$PWD":/b -w /b -e UV_PYTHON_INSTALL_DIR=/b/pythons python:3.14 sh -c 'pip install uv && uv python install 3.14t'
docker run --rm --cpuset-cpus=8-11 -v "$PWD":/b -w /b python:3.14 /b/pythons/cpython-3.14.10+freethreaded-linux-x86_64-gnu/bin/python3.14t conc.py cpu threads
docker run --rm --cpuset-cpus=8-11 -v "$PWD":/b -w /b node:24 node conc.mjs race await

conc.py:

# Python side of the concurrency comparisons. Usage: python conc.py <test> <mode>
import asyncio, sys, threading, time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor

def now(): return time.monotonic()
def rss_mb():
    with open("/proc/self/status") as f:
        return int(next(l for l in f if l.startswith("VmRSS")).split()[1]) / 1024
def fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2)
N_CPU, FIB, N_IO, WAIT = 4, 35, 10_000, 0.1
LAG_FIB = 32

def cpu(mode):
    t = now()
    if mode == "seq":
        for _ in range(N_CPU): fib(FIB)
    elif mode == "threads":
        with ThreadPoolExecutor(N_CPU) as ex: list(ex.map(fib, [FIB] * N_CPU))
    elif mode == "asyncio":
        async def task(): return fib(FIB)
        async def main(): await asyncio.gather(*(task() for _ in range(N_CPU)))
        asyncio.run(main())
    elif mode == "processes":
        with ProcessPoolExecutor(N_CPU) as ex: list(ex.map(fib, [FIB] * N_CPU))
    elif mode == "interpreters":  # PEP 734, Python 3.14+
        from concurrent.futures import InterpreterPoolExecutor
        with InterpreterPoolExecutor(N_CPU) as ex: list(ex.map(fib, [FIB] * N_CPU))
    print(f"cpu {mode:<12} {now() - t:.3f} s")

def io(mode):
    t = now()
    if mode == "asyncio":
        async def main(): await asyncio.gather(*(asyncio.sleep(WAIT) for _ in range(N_IO)))
        asyncio.run(main())
    elif mode == "threads":
        ts = [threading.Thread(target=time.sleep, args=(WAIT,)) for _ in range(N_IO)]
        for th in ts: th.start()
        for th in ts: th.join()
    print(f"io  {mode:<12} {now() - t:.3f} s  rss {rss_mb():.0f} MB")

def race(mode):
    c = 0
    lock = threading.Lock()
    def plain():
        nonlocal c
        for _ in range(1_000_000): c += 1
    def yielding():  # GIL released between read and write, as any blocking call does
        nonlocal c
        for _ in range(1_000_000):
            v = c; time.sleep(0); c = v + 1
    def locked():
        nonlocal c
        for _ in range(1_000_000):
            with lock: c += 1
    if mode == "await":  # 4 asyncio tasks, an await between read and write
        async def task():
            nonlocal c
            for _ in range(1_000_000):
                v = c; await asyncio.sleep(0); c = v + 1
        async def main(): await asyncio.gather(*(task() for _ in range(4)))
        asyncio.run(main())
    else:
        fn = {"plain": plain, "yield": yielding, "lock": locked}[mode]
        ts = [threading.Thread(target=fn) for _ in range(4)]
        for th in ts: th.start()
        for th in ts: th.join()
    print(f"race {mode} {c} (expected 4000000)")

def lag(mode):
    worst = 0.0
    if mode in ("thread", "process"):
        stop = False
        def ticker():
            nonlocal worst
            while not stop:
                t = now(); time.sleep(0.01); worst = max(worst, now() - t - 0.01)
        th = threading.Thread(target=ticker); th.start()
        time.sleep(0.05)
        t = now()
        if mode == "thread":
            w = threading.Thread(target=fib, args=(LAG_FIB,)); w.start(); w.join()
        else:
            with ProcessPoolExecutor(1) as ex: ex.submit(fib, LAG_FIB).result()
        took = now() - t
        stop = True; th.join()
    else:  # asyncio: the CPU call runs on the event loop
        async def main():
            nonlocal worst
            done = False
            async def ticker():
                nonlocal worst
                while not done:
                    t = now(); await asyncio.sleep(0.01); worst = max(worst, now() - t - 0.01)
            tk = asyncio.create_task(ticker())
            await asyncio.sleep(0.05)
            t = now(); fib(LAG_FIB); took = now() - t
            await asyncio.sleep(0.03)
            done = True; await tk
            return took
        took = asyncio.run(main())
    print(f"lag {mode:<8} worst ticker lateness {worst * 1000:.1f} ms  (cpu task {took * 1000:.0f} ms)")

if __name__ == "__main__":
    test, mode = sys.argv[1:3]
    {"cpu": cpu, "io": io, "race": race, "lag": lag}[test](mode)

conc.mjs:

// JavaScript (Node) side of the concurrency comparisons. 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 if (mode === "await") { // an await between read and write
      const a = new Int32Array(sab);
      await Promise.all([...Array(4)].map(async () => { for (let i = 0; i < 1_000_000; i++) { const v = a[0]; await null; a[0] = v + 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));
    const t0 = now();
    if (mode === "main") fib(37);
    if (mode === "worker") await runWorker({ kind: "fib", n: 37 });
    const took = now() - t0;
    await new Promise((r) => setTimeout(r, 30));
    stop = true;
    console.log(`lag ${mode.padEnd(8)} worst ticker lateness ${(worst * 1000).toFixed(1)} ms  (cpu task ${(took * 1000).toFixed(0)} ms)`);
  }
}

Questions? Let's Chat :)

concurrency