Moli: The Headless Browser That Throws Away Its Layout Tree
Hook
Most browsers spend 80% of their memory keeping layout trees you'll query once. Moli deletes them immediately after each use—and somehow runs faster.
Context
AI agents are terrible browser citizens. A typical RAG crawler spawns 500 Chromium instances to scrape documentation sites, each consuming 697 MiB and 11 processes just to extract text from rendered DOM. Playwright and Puppeteer weren't designed for this—they wrap Chrome, a browser optimized for human interaction where layout trees persist because users scroll, resize windows, and hover over elements. Agents don't. They load a page, query the DOM once, extract structured data, and move on. Yet they pay the full memory cost of Chrome's incremental rendering engine, retained display lists, and GPU compositing pipeline.
The obvious alternative—lightweight scrapers like BeautifulSoup or even Lightpanda—goes too far in the other direction. They skip JavaScript execution or fake layout geometry, breaking on the 67% of modern web pages that rely on client-side rendering or computed styles for content visibility. What agents actually need is a browser that runs real JavaScript and CSS but treats layout as a one-time calculation, not a persistent data structure. Moli delivers exactly that: a Rust-based browser kernel that maintains DOM and style trees continuously but generates layout and paint on-demand, then immediately discards them. It's a fundamentally different architecture that unlocks 7x memory reduction while maintaining compatibility with frameworks like React, Vue, and Angular that simpler scrapers choke on.
Technical Insight
Moli's core innovation is splitting browser concerns into three layers with radically different lifecycles. The web runtime layer—V8 for JavaScript, Servo's Stylo for CSS cascade, html5ever for parsing, and libcurl for networking—runs continuously and maintains persistent state. The layout layer using Taffy (a Rust flexbox/grid engine) and Parley (text shaping) only executes when code explicitly queries element geometry, producing an immutable FrozenLayoutTree snapshot that caches computed positions. The paint layer with Vello CPU rendering rebuilds from DOM and style for each screenshot request, then throws away all rendering artifacts. No retained display lists, no GPU textures lingering in memory.
The FrozenLayoutTree is where the magic happens. When you call element.getBoundingClientRect() or request a screenshot, Moli builds a complete Taffy layout tree, walks it to extract coordinates into a compact cache, then freezes it. Subsequent geometry queries read from this frozen snapshot without touching Taffy again—until a DOM mutation invalidates the generation token. Here's what the automation code looks like:
// Standard CDP/WebDriver commands work identically
const client = await CDP({ port: 9222 });
const { DOM, Runtime } = client;
// DOM traversal happens against live tree
const doc = await DOM.getDocument();
const node = await DOM.querySelector({
nodeId: doc.root.nodeId,
selector: '.price'
});
// First geometry query triggers layout build + freeze
const box = await DOM.getBoxModel({ nodeId: node.nodeId });
// { content: [x, y, width, height], generation: 42 }
// Second query reads frozen cache, no Taffy rebuild
const box2 = await DOM.getBoxModel({ nodeId: node.nodeId });
// Same generation token = zero layout cost
// DOM mutation invalidates frozen tree
await Runtime.evaluate({ expression: 'document.body.style.fontSize = "20px"' });
// Next query rebuilds layout with generation: 43
const box3 = await DOM.getBoxModel({ nodeId: node.nodeId });
The three-tier cost model gives you surgical control over resource usage. By default, Moli runs in MockLayout mode where getBoundingClientRect() returns deterministic fake values (0, 0, 1024, 768 for most elements). This sounds useless, but 70% of agent tasks only need DOM selectors and text content—they never actually query layout. For agents doing visibility checks or scroll calculations, you enable --layout which activates real Taffy computations. Only when you need screenshots or Canvas rendering do you pay for --resource mode that fetches images and fonts. Each tier adds cost:
# Tier 1: DOM + JS only, 28 MiB baseline
moli --url https://example.com
# Tier 2: + real layout calculations, 45 MiB
moli --layout --url https://example.com
# Tier 3: + media fetching + paint, 89 MiB
moli --resource --url https://example.com
# Chrome equivalent: 697 MiB regardless of what you use
The protocol layer unifies CDP, WebDriver Classic, and WebDriver BiDi through a single Rust scheduler. Unlike Playwright which translates commands to Chrome's CDP or Firefox's Marionette, Moli implements all three protocols natively against the same kernel. When you send a WebDriver findElement command, it doesn't get translated to CDP—it directly invokes Moli's DOM traversal. This eliminates an entire IPC layer and means WebDriver and CDP commands have identical performance characteristics.
Screencast polling demonstrates the architecture's efficiency. Instead of encoding video frames, Moli's screencast mode returns generation tokens. Your agent polls for changes, and if the token matches the last request, Moli sends an empty response—no layout rebuild, no paint, no JPEG encoding. Only when DOM mutations bump the generation does Moli render a new frame:
// Traditional approach: polls full JPEG frames
while (true) {
const frame = await Page.screencastFrame(); // 50KB JPEG
if (hashChanged(frame)) process(frame);
await sleep(100); // Wasted bandwidth on unchanged pages
}
// Moli approach: polls generation tokens
let lastGen = 0;
while (true) {
const update = await Page.screencastToken();
// { generation: 42, data: null } if unchanged, 2 bytes
if (update.generation > lastGen) {
const frame = await Page.screenshot(); // Only when needed
process(frame);
lastGen = update.generation;
}
await sleep(100);
}
This token-based observation is critical for RL training loops where agents watch pages for state changes but 90% of poll intervals see no mutations. Chrome sends 50KB JPEG frames regardless; Moli sends 2-byte tokens.
The Lexbench results validate the architecture with real workloads: 15% of Chrome's CPU time, 13% of memory (89 MiB vs 697 MiB), but 81.9% task success rate vs Chrome's 99.8%. That 18-point gap reveals the cold layout trade-off. Tasks involving rapid layout queries—like waiting for an element to become visible in a precise viewport position—pay repeated rebuild costs. And software CPU rendering means complex Canvas apps or WebGL visualizations either fail or run 10x slower than Chrome's GPU path.
Gotcha
The 81.9% Lexbench success rate isn't a bug to be fixed—it's the architectural trade-off made explicit. Moli optimizes for agent workloads that load, query, extract, and close. Sites relying on perfect layout fidelity for functionality (responsive design frameworks that measure container width in JavaScript, infinite scrollers calculating visible items, Canvas-heavy dashboards) will break. The ephemeral layout model means that if your agent does measure-mutate-measure cycles—query an element's height, adjust padding, query again—each iteration rebuilds the Taffy tree. Chrome amortizes layout across mutations with incremental updates; Moli starts cold every time.
The single-process architecture with 24 threads creates a blast radius problem. One site triggering a panic in the Rust runtime kills the entire browser instance. For agent workflows processing untrusted web content, you need external sandboxing—spawn Moli in containers or VMs, not bare metal. And there's no site isolation: all tabs share one process, so a malicious page can potentially observe side-channel timing from other tabs' JavaScript execution. Chrome's multi-process architecture with per-origin processes prevents this; Moli trades that security for lower memory overhead. The software-only Vello renderer also means no WebGL, degraded Canvas performance, and missing Chrome features like full-page screenshots with device emulation or print-to-PDF with exact pagination.
Verdict
Use if: You're building AI agents that process thousands of pages in parallel where memory per instance is the bottleneck, your workload is read-heavy (load page, query DOM, extract, close) rather than interaction-heavy, you can tolerate 80% task success and handle compatibility failures gracefully, or you're running large-scale web crawlers for RAG pipelines where 7x density improvement directly cuts infrastructure costs. Moli shines when you need real JavaScript and CSS execution that lightweight scrapers can't provide, but don't need Chrome's pixel-perfect rendering or GPU acceleration. Skip if: You require production-grade 99%+ reliability on arbitrary web content, need WebGL/Canvas rendering for visual validation tasks, depend on Chrome's exact layout behavior for legal/compliance screenshots, or your agents do frequent measure-mutate-measure loops where cold layout starts become a bottleneck. For UI testing, visual regression checks, or anything requiring sub-100ms layout query latency, stick with Playwright and Chrome.