Moving From Threads to Fibers for Efficient In-Browser Play
Today, we’re beginning to release the public beta for the technology that will allow those with a Roblox account to click a link to play Roblox games on any Chrome desktop or Android browser—no need to download the app. This will become available on more browsers over the next few months. Making this possible on the web, for Chrome browsers, meant rethinking several of the assumptions that have been baked into the Roblox engine, including networking, rendering, and content delivery. But the biggest challenge was rethinking how the engine handles concurrent programming.
In modern operating systems, every instruction runs as part of a lightweight process, called a thread. The operating system (OS) decides when threads run—giving applications very little influence. When a thread has to wait for a lock or the network, the OS suspends it while another thread runs. Every switch between threads can cost thousands of CPU cycles. With dozens of parallel tasks in flight, those cycles can add up fast.
To mitigate this, we use fibers, or lightweight threads, which we can create and schedule in user space, moving them from the OS to user-level code. When a fiber has to wait (called blocking) for a lock or for the network, we suspend it and resume another one, without involving the OS at all. Behind the scenes, switching fibers comes down to one tiny operation, usually called swap_context. That operation saves the current fiber’s CPU registers to its stack, points the stack pointer at the other fiber’s stack, then loads that fiber’s registers back. It’s a couple of dozen lines of assembly per CPU architecture, and the rest of the engine never has to think about it.

The Browser Doesn’t Wait
When running JavaScript, the code runs to completion. The browser calls a function we write, and nothing else can happen until the function returns. Our code doesn’t wait for the network request to return a response. Instead, the browser returns a JavaScript Promise, a placeholder for a value that’s not ready yet. We attach a callback to that Promise, which the browser will call when the response is ready. We cannot wait for the response, because that would block the browser from making progress. And Promises are contagious: Once a function has to wait on one, it has to return a Promise itself, and so does its caller, all the way up. This is how code is traditionally written for the browser.
WebAssembly (Wasm) has an even stricter model and always runs to completion—but Roblox has 20 years of C++ code that assumes the opposite. The first time we ran the Wasm build of our engine, it froze almost immediately. At start-up, the engine requests config flags over HTTP and waits for the reply. But the reply can’t be delivered until the engine hands control back to the browser, which we can’t do until we have the reply, so we’re deadlocked. Rewriting the entire Roblox engine so it never blocks obviously isn’t an option. We could make the initialization a fiber, but Wasm has no registers to save and no stack pointer to swap. The browser manages the execution state, outside of our control.

We tried Asyncify, an Emscripten pass that rewrites every function in a program so it can pause and resume itself. While it works well for smaller programs, the Roblox engine is so large we couldn’t overcome the code bloat and slowdown. Our second attempt was to make every fiber a real thread, since JavaScript now has threads in the form of Web Workers. Each thread sleeps until another one wakes it up, so switching means waking the target thread and putting the current thread to sleep. All the convenience of fibers, with all the efficiency of threads. While this got us all the way into game-join on a high-end MacBook, we ran out of memory quickly on an Android device.
JavaScript Promise Integration (JSPI)
Then a Wasm feature we’d been waiting for shipped in Chrome. JSPI lets Wasm call a JavaScript function that returns a Promise and suspends Wasm until that Promise is resolved. The browser puts the Wasm call stack aside, gives control back to the caller, and resumes exactly where it left off when the Promise resolves. From the C++ side, it looks like an ordinary function call. For instance, JavaScript still has no portable Promise-based sleep. It provides setTimeout(f, ms), which calls f later. But anyone can make their own Promises, so building one is a single line.
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
With JSPI, C++ can call that like any other function:
extern "C" void sleep(int32_t ms);
void foo() {
sleep(10); // no explicit await or Promise
}
This alone isn’t a fiber switch, of course. We can’t just say “suspend this and resume that fiber.” But it is the core primitive, enough to build everything else on top of.
Building a Context Switch Out of Promises
When we create a Promise object, JavaScript passes a function called resolve that fulfills it. In sleep, we passed it to setTimeout. But nothing forces us to call it there and then. We can just stash it to be called later.
let stashed = null;
function suspend() {
return new Promise(resolve => { stashed = resolve; });
}
function resume() {
stashed();
}
A fiber that calls suspend remains suspended until someone calls resume. It’s essentially a handle to a paused fiber. So switching fibers becomes as simple as wake target, then pause. Note that this is not a direct transfer. Waking the target simply marks the target as runnable, and the browser will run it after we return by suspending.

There’s no way to express a JavaScript function in C++, so we leave the resolve functions in a JavaScript array and give C++ the index.
const paused = []; // [resolve, stackPointer] per paused fiber
function swap_context_js(myIndexAddr, target) {
return new Promise(resolve => {
// suspend ourselves...
const me = paused.length;
paused[me] = [resolve, get_stack_ptr()];
HEAPU32[myIndexAddr >> 2] = me;
// ...and resume the target
const [wake, sp] = paused[target];
set_stack_ptr(sp);
wake(false);
});
}
void swap_context(context* from, context* to) {
swap_context_js(&from->index, to->index);
}
If Wasm has no stack pointer, what is get/set_stack_ptr doing here? Wasm’s own execution stack has no addresses, but C++ lets you take the address of a local variable. So the compiler keeps a second shadow stack in regular memory, tracked by a global called __stack_pointer. Every fiber has its own, and we swap __stack_pointer on every switch.
Creating a fiber uses a browser API to acquire a fresh call stack. In addition to allocating a call stack, that API runs the function we pass to it right away on that stack. But we want the fiber to remain suspended until someone explicitly switches to it. We solved this problem by wrapping the actual fiber function in a trampoline that pauses as its first task. An eager fiber that immediately suspends is indistinguishable from one that starts suspended.
void new_fiber_trampoline(void (*fn)(), context* self, context* creator) {
swap_context(self, creator); // pause until someone resumes us
fn();
}
From the caller’s side, this looks just like native: It returns a suspended fiber as if it never ran, ready to start as soon as someone switches to it. We don’t have access to the processor state directly, but we can orchestrate existing APIs to make the browser do roughly what we want.
JSPI fibers switch 14x faster, start hundreds of times faster, and use 1/70th the memory of threads. These numbers show that without JSPI, this web client would not have worked.
The Memory Leak
Like threads, fibers eventually exit. We destroy an exited fiber by marking it dead before it suspends for the last time and switching away. Whichever fiber runs next cleans the exited fiber up by freeing the related re: We simply drop the reference to the dead fiber’s resolve function and let the garbage collector handle the rest
That’s how we first implemented it—and it worked. However, our tab was using a growing amount of memory, even with a stable number of fibers. This initially manifested as crashes on Android. Later, a Mac running macOS Tahoe kernel-panicked after running out of page table entries. How did we crash the host OS from a web page? After a few weeks of head-scratching, we found it: Chromium keeps a suspended JSPI stack alive even when nothing can ever resume it. Every fiber we created claimed fresh pages from the OS, and none of them were given back. Every fiber we destroyed leaked 17 KB of memory.

The only reliable way to make the browser release a JSPI stack is for the initial call to return, unwinding all the way back to JavaScript. But our dead fibers are paused deep inside the engine code, and threading a “keep unwinding” signal through every function call would mean rewriting everything and killing performance. We needed something that could unwind a stack efficiently by force—which meant using an exception. To destroy a fiber, we wake the fiber one last time with an argument telling it to self-destruct.
function destroy_fiber(index) {
paused[index][0](true);
}
void swap_context(context* from, context* to) {
if (swap_context_js(&from->index, to->index)) {
__builtin_trap();
}
}
The __builtin_trap line compiles to Wasm’s unreachable instruction, and nothing in C++ catches that, not even catch (…). We can’t use a regular C++ throw for this: Some random catch (…) in the engine could accidentally swallow it. The stack unwinds right back to JavaScript, the browser releases it, and the memory is returned to the OS. Who said exceptions are useless in game development?
JSPI allows a few dozen lines of JavaScript to implement the core fiber API: create, swap_context, and destroy. Twenty years of engine code still gets to wait, even on a web page.
If you enjoy solving these kinds of challenges, come join us.