DEV Community

Cover image for I moved my graph layout to Rust. It fixed one of three bottlenecks.
Fred 🍓
Fred 🍓

Posted on

I moved my graph layout to Rust. It fixed one of three bottlenecks.

VibeDesk has a window I call the brain. It shows what Claude Code knows about a project as a graph: notes as dots, the files they mention as smaller dots, lines between them. With a few dozen notes it looks calm and pretty. With a big project it fell apart.

I wanted to know how badly, so I generated a synthetic brain: 500 notes, 3,000 files. That came out as 3,242 nodes and 12,038 edges. Hovering over the notes ran at 6 to 13 fps. Zooming with the files visible ran at 1 fps.

I'm already moving VibeDesk to Rust one piece at a time, so the plan looked obvious. Port the force layout to Rust, compile it to WebAssembly, done.

It runs at 60 fps now. But Rust fixed only one of the three things that were wrong. The other two had nothing to do with the language.

The profile said "idle"

The first thing I did was record a CPU profile of the renderer while hovering. It was about 90% idle.

So JavaScript wasn't the bottleneck, at least not while hovering. A low frame rate with an idle CPU means something else is slow, and in a browser that's usually the GPU. From there I measured one layer at a time:

  • the Electron main process: event loop lag, with a setInterval that checks how late it fires
  • the renderer: the CDP profiler
  • the GPU: turn off drawing layers one by one and watch the frame rate

That turned up three separate causes.

Cause 1: lines wider than one pixel

The graph was drawn with Canvas 2D. In Chrome that's Skia, and on the GPU Skia takes a slow path for strokes wider than one device pixel. A test with 2,200 edges:

Canvas 2D edges fps
lineWidth wider than 1 device pixel 11
hairlines (lineWidth = 1, identity transform) 45

Lots of arc() paths were expensive too. Drawing a pre-rendered circle with drawImage was cheaper.

So the bottom layer moved to WebGL: edges as gl.LINES, nodes, glows and rings as quads that a fragment shader turns into circles. That's three draw calls per frame. Pulses, sparks and labels stay on a 2D canvas on top, because there are few of them.

The bigger surprise was one flag:

// without MSAA: at 12,000 edges it cost two thirds of the frame rate.
// The shader smooths the circles itself.
gl = canvas.getContext('webgl', { antialias: false, premultipliedAlpha: true, alpha: true })
Enter fullscreen mode Exit fullscreen mode

With the default antialias: true the graph ran at 16 fps. Without it, 60. The circles still have soft edges because the shader fades them over half a pixel:

a = clamp(r - d + 0.5, 0.0, 1.0);
Enter fullscreen mode Exit fullscreen mode

One more GPU thing: when you zoom in, hundreds of big glow quads overlap and the fill rate goes through the roof. The glow radius on screen is now capped at 56 CSS pixels.

If WebGL isn't available, the old 2D path still runs, now with hairlines and pre-rendered disc sprites. Nothing in this section involved Rust.

Cause 2: d3-force on the window thread

This is the part Rust fixed.

The layout used d3-force. At 3,200 nodes one simulation step took 32 ms, on the window thread, and after every change the graph runs about 200 steps until it settles. A single step is already two frames' worth of time at 60 fps.

vibedesk-layout is a small Rust crate with the same forces as my d3 configuration: springs for the links, Barnes-Hut repulsion with a quadtree, collision on a grid, a pull towards the center. It has no dependencies and doesn't use wasm-bindgen. It exports plain functions and raw pointers:

#[unsafe(no_mangle)]
pub unsafe extern "C" fn layout_tick(l: *mut Layout, alpha: f64) {
    unsafe { (*l).tick(alpha) }
}
Enter fullscreen mode Exit fullscreen mode

The worker writes the input straight into WebAssembly memory and reads the positions back the same way:

// new views every time: if the memory grows, old views become invalid
const f64 = (ptr: number, len: number) => new Float64Array(e.memory.buffer, ptr, len)
f64(e.layout_x(l), n).set(input.x)
f64(e.layout_y(l), n).set(input.y)
// ...
e.layout_tick(l, alpha)
Enter fullscreen mode Exit fullscreen mode

In a Web Worker that's 11 ms per step instead of 32, and the window thread doesn't do any of it.

I kept the JavaScript version as a fallback, because that's the rule for every piece I move to Rust. Both engines sit behind the same small interface:

engine = mod ? wasmEngine(mod, m.input) : jsEngine(m.input)
Enter fullscreen mode Exit fullscreen mode

If the WebAssembly module is missing (someone built VibeDesk without Rust) or won't compile (a Content Security Policy without wasm-unsafe-eval), the worker runs d3. If the worker itself can't start, the same code runs on the window thread like before. The tests run the same checks against both engines: no big overlaps, the graph stays centered, a dragged node stays where you put it. One extra test checks that Rust is faster than d3.

One Electron detail cost me some time. The renderer loads from file://, so it can't fetch() a .wasm file sitting next to it, and Vite's ?inline import didn't work inside the worker bundle. The build script now writes the module into a TypeScript file as a base64 string. If that file doesn't exist, import.meta.glob returns an empty object and the worker uses d3.

Cause 3: reading 500 files on every call

The third problem wasn't in the window at all.

The Electron main process has a BrainStore.list() that returns all notes. It read every note file from disk on every call. On Windows, opening a file costs about 0.6 ms, so 500 notes took 300 to 500 ms. While that runs, the main process is blocked, and with it the whole app. list() runs on every brain tool call Claude makes, at session start, and whenever the graph reloads.

Now there's a cache per brain folder. fs.watch sets a dirty flag. As long as nothing changed, list() returns the cached list without touching the disk. When something did change, it only re-reads files whose modification time or size differs:

const hit = c.files.get(p)
if (hit && hit.mtime === st.mtimeMs && hit.size === st.size) note = hit.note
else {
  note = parseNote(title, fs.readFileSync(p, 'utf8'), st.mtimeMs)
  c.files.set(p, { mtime: st.mtimeMs, size: st.size, note })
}
Enter fullscreen mode Exit fullscreen mode

Two small details: the flag is cleared before reading, so a change during the read marks the list dirty again. And the app's own writes set the flag right away instead of waiting for the watcher.

While I was in there I found a loop. When Claude read a file that wasn't in the graph, the brain window reloaded the graph, the file still wasn't in it, and the next read reloaded it again. Now that happens at most once per file.

Before and after

Measured in the real app with Playwright, on my Windows 11 laptop:

fps Before After
Hover, notes only 6-13 60
Show files (3,200 nodes) 3-5 60
Hover with files 4-5 60
Zoom with files 1 60
Claude reads 40 files 2-4 59

So how much of this was Rust?

Less than the commit message suggests.

Hovering and zooming were limited by the GPU (remember the idle CPU profile), so that's where WebGL and the missing MSAA did the work. The blocked main process had nothing to do with drawing at all. Rust made the layout step about three times faster, 32 ms down to 11.

To be fair to d3: moving it into a worker would have taken it off the window thread too. That's exactly what my fallback does. What Rust adds on top is that the graph needs about a third of the compute time to settle.

I'd still do it again. But if I had started with "rewrite it in Rust" and skipped the measuring, I'd have a faster layout and the same 1 fps zoom.

What this doesn't prove

  • One laptop. Other GPUs and drivers take different slow paths. I'd expect the MSAA cost in particular to vary a lot between machines.
  • A synthetic brain. It came from a generator script, not from a real project. Real graphs have a different shape, and I didn't measure at which size the old code starts to hurt.
  • Noisy numbers. My own VibeDesk was running next to the test instance, which costs GPU time. I measured every version several times and compared A and B in the same run, which is why the "before" column has ranges.
  • It's not a language benchmark. My crate does exactly one job, and d3 is a general library. Collision uses a grid in mine and a quadtree in d3.

One tip if you measure Electron with Playwright: page.evaluate sends its return value back over CDP. Returning 1.5 MB from it took seconds and made my numbers worse than the app. Return small values only.

What's next

This is the second piece of VibeDesk that moved to Rust. The first one sits between Claude Code and the app (hooks, statusline, MCP server); more on that in a later post. The layout is on main now and ships with VibeDesk 2.1 on December 13.

Question

When an app gets slow, where do you look first?

A) the JavaScript / CPU profiler
B) rendering and the GPU
C) I/O, the backend, the database
D) honestly, I start rewriting it

(I build VibeDesk on my own: a free, open-source Windows desktop for Claude Code. The layout crate is about 500 lines of Rust plus tests: native/layout. The plan for the whole move to Rust is in native/README.md.)

Top comments (0)