Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 37 ยท Deploy and Interop

Workers, FFI and WebAssembly in Deno

Run CPU-heavy work off the main thread with Web Workers, call native libraries with Deno.dlopen and FFI, and run fast portable code with WebAssembly. Includes permissions and safety notes.

JavaScript runs your code on one thread. That is wonderful for I/O-heavy servers, because waiting for a database costs nothing, but a long calculation blocks everything: while one request hashes a huge file or resizes an image, the server cannot answer anything else. Deno gives you three ways to go beyond that single thread or beyond JavaScript itself:

  • Web Workers run JavaScript in parallel on other threads.
  • FFI (foreign function interface) calls functions in native libraries written in C, Rust or Zig.
  • WebAssembly runs compiled code from many languages in a sandbox, at near-native speed.

Deno is not available on this site, so Deno.* code is read-only. The runnable examples use Node 24 equivalents (worker_threads, and the identical WebAssembly API, which is a web standard) to demonstrate the ideas.

Web Workers

A worker is a separate JavaScript environment with its own thread and event loop. You talk to it by messages; nothing is shared by default, so there are no data races.

TypeScript
// main.ts
const worker = new Worker(new URL("./worker.ts", import.meta.url).href, {
  type: "module",
});

worker.onmessage = (event: MessageEvent<number>) => {
  console.log("result:", event.data);
  worker.terminate();
};

worker.postMessage(40);
TypeScript
// worker.ts
function fib(n: number): number {
  return n < 2 ? n : fib(n - 1) + fib(n - 2);
}

self.onmessage = (event: MessageEvent<number>) => {
  self.postMessage(fib(event.data));
};
Terminal
deno run main.ts

Points to know:

  • Use { type: "module" }, so the worker can use import.
  • Messages are copied with the structured clone algorithm (objects, arrays, Maps, Dates, typed arrays). Functions and class methods cannot be sent.
  • To avoid copying big buffers, transfer them: worker.postMessage(buffer, [buffer]) moves ownership with no copy. SharedArrayBuffer with Atomics allows true shared memory when you need it.
  • A worker inherits the parent's permissions, and you can restrict one: new Worker(url, { type: "module", deno: { permissions: "none" } }) runs it without any access, a good way to isolate untrusted or risky code.
  • Creating a worker costs a few milliseconds and some memory. Keep a small pool of workers instead of making one per request.

This runnable example uses Node's worker_threads with the same message pattern, running a heavy computation in the background while the main thread stays responsive.

Node.js A worker keeps the main thread free (Node stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

For communication between isolates that are not parent and child (separate workers, or several server instances in one region on Deno Deploy), use BroadcastChannel:

TypeScript
const channel = new BroadcastChannel("chat");
channel.onmessage = (e) => console.log("received", e.data);
channel.postMessage({ text: "hello everyone" });

FFI: calling native code

Sometimes the code you need already exists as a shared library: a C image codec, a Rust crypto crate, a system API. Deno.dlopen loads it and describes each function's signature:

TypeScript
const lib = Deno.dlopen(
  "./libmath.so",     // .dll on Windows, .dylib on macOS
  {
    add: { parameters: ["i32", "i32"], result: "i32" },
    scale: { parameters: ["f64", "f64"], result: "f64" },
    greet: { parameters: ["buffer"], result: "void" },
  } as const,
);

console.log(lib.symbols.add(2, 3));        // 5
console.log(lib.symbols.scale(1.5, 4));    // 6

const text = new TextEncoder().encode("hello\0");  // C strings end with a zero byte
lib.symbols.greet(text);

lib.close();
Terminal
deno run --allow-ffi main.ts

The C side it loads:

C
int add(int a, int b) { return a + b; }
double scale(double x, double k) { return x * k; }
void greet(const char *name) { printf("Hello, %s\n", name); }

Types map directly to C: i8...i64, u8...u64, f32, f64, bool, pointer, buffer (a typed array), void, and struct descriptions. Mark slow, blocking calls with nonblocking: true so they run on a thread pool and return promises.

FFI is the least safe feature in Deno. Native code is not sandboxed: a bug or a malicious library can read any memory, crash the process or bypass every permission. That is why --allow-ffi is separate, and why you should never grant it casually, never load libraries you did not build or audit, and prefer WebAssembly when it can do the job.

WebAssembly

WebAssembly (Wasm) is a compact binary format that runs in a sandbox at near-native speed. You compile Rust, C, C++, Zig or Go to .wasm and call it from JavaScript. Unlike FFI, a Wasm module cannot touch the system unless you hand it functions to do so, so no extra permission is needed. The API is the same web standard as in browsers:

TypeScript
const bytes = await Deno.readFile("./add.wasm");   // needs --allow-read
const { instance } = await WebAssembly.instantiate(bytes);
const add = instance.exports.add as (a: number, b: number) => number;
console.log(add(20, 22));   // 42

A module can also be fetched and compiled while streaming: WebAssembly.instantiateStreaming(fetch(url)).

The module below is a tiny hand-assembled one with an add function, so you can run real WebAssembly right here:

Node.js Run a real WebAssembly module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Wasm only knows numbers. For strings or structures you write bytes into the module's linear memory and pass pointers. Tools such as wasm-bindgen (Rust) generate that glue for you, and you load their output like any other module.

Choosing the right tool

Problem Best fit
Long calculation that blocks requests Worker (or a pool of workers)
Isolate risky or untrusted code Worker with permissions: "none", or Wasm
Reuse an existing C/Rust library FFI (trusted code only)
Fast, portable, sandboxed algorithm WebAssembly
Just waiting for I/O Plain async/await, no extra thread needed

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do a Worker and the main thread exchange data?

    Workers have separate memory. Messages are copied (or transferred), which avoids data races.
  2. 2. Which permission flag is needed for Deno.dlopen?

    --allow-ffi gates loading native libraries, because native code is not sandboxed.
  3. 3. Why is WebAssembly safer than FFI?

    A Wasm module has no access to the system by default, unlike a native library that runs with the process's full power.
  4. 4. What is the cheap way to send a 100 MB ArrayBuffer to a worker?

    Transferring moves ownership of the buffer to the worker without copying.

Summary

  • Workers run JavaScript on other threads and communicate by messages; transfer big buffers instead of copying them, and pool workers.
  • new Worker(url, { type: "module", deno: { permissions } }) can restrict a worker.
  • Deno.dlopen calls native libraries and needs --allow-ffi; treat it as unsafe and use only trusted libraries.
  • WebAssembly runs compiled code in a sandbox with the same API as browsers.
  • Use BroadcastChannel to message between isolates.

Next: Deploy, Compile and Docker