This page looks best with JavaScript enabled

Writing a Web Browser from Scratch

 ·  ☕ 19 min read

It has been a while since the last post. One of the more interesting projects I have worked on recently is a web browser written from scratch in Rust, working name Breeze. The code is public on GitHub.

“From scratch” needs a definition, because every browser borrows something. Breeze is not a Chromium, WebView2, Gecko or OS web-view wrapper. The executable owns its HTML DOM, CSS cascade, layout engine, display list, resource loading, cookie jar, form submission, image/SVG/font decoding and Windows painting path. It does borrow carefully chosen components (V8 for JavaScript, html5ever for tokenizing, ANGLE for WebGL), and the article lists every one of them.

Breeze rendering the Wikipedia article on browser engines
Breeze 0.1.0 rendering Wikipedia at 1536×864 CSS pixels and 125% scaling. Captured today in Breeze’s hidden capture mode, so the tab strip, address bar and status bar are Breeze’s own Win32 chrome.

By the Numbers

The first commit landed on August 12, 2026, titled “Initial Breeze browser MVP”. The numbers below are from the repository today.

MetricValue
Commits1,010
Merged pull requests222
GitHub issues (open + closed)104
Rust source files3,061
Lines of Rust487,799
#[test] functions~7,100
Design and compatibility docs (Markdown)204 files, 23,063 lines
PowerShell tooling (build, benchmarks, captures)74 scripts, 7,407 lines
HTML / JavaScript files (fixtures, harnesses)195 / 460
Release executable (V8 statically linked)87.9 MB
Rust toolchain1.95.0, edition 2024

Commits per month show the shape of the project: a fast start, a large September, and a slower November spent on performance.

Month (2026)Commits
August (from the 12th)223
September419
October324
November36
December (to the 4th)8

Where the lines are:

AreaLines of RustWhat lives there
src/engine/script136,885V8 embedding, DOM bindings, Web APIs, Workers, Fetch, Canvas 2D
src/windows_app52,394Win32 shell, tabs, history, F12 panel, Task manager, presentation
src/engine/css45,810Parser glue, cascade, selectors, custom properties, math, CSSOM
crates/webgl~43,900ANGLE-backed WebGL 1/2 contexts and validation
src/renderer_process30,624Sandboxed renderer child, IPC, document lifecycle
src/engine/layout29,234Block, inline, flex, grid, table, float and positioned layout
src/engine/page13,959Page assembly, resources, readiness
src/media_process10,305Restricted media demux/decode process
src/engine/dom8,759Engine-owned DOM, NodeId identities, mutation versions
Integration tests (tests/)30,843Hidden-browser, renderer-process and live-runtime tests

JavaScript bindings are by far the biggest component. Layout, which most people picture when they think “browser engine”, is about a fifth of that size. The Web platform is mostly API surface.

Architecture: Three Kinds of Process

Breeze follows the same basic shape as Chromium: a trusted browser process, untrusted renderer processes, and a restricted media process.

Breeze process architecture

The browser process is the broker. It owns everything that has authority: navigation, history, network, TLS, cookies, storage, permissions and the final pixels on screen. A renderer owns everything that touches untrusted bytes: decoding, parsing, DOM, JavaScript, style, layout, image/SVG/font decoding, and display-list construction.

ResponsibilityBrowser processRenderer process
Navigation & historyOwns policy, history, redirectsRequests navigations
NetworkWinHTTP, TLS, CORS, preflight, redirect modesReceives bounded, back-pressured body streams
Cookies & storageAuthoritative jar, localStorage, IndexedDB on diskGets browser-authorised projections
Browsing contextsAllocates FrameId, parentage, process placementHosts the assigned active documents
HTML/CSS/JSNever parses page contentParses and runs all of it
Fonts & imagesNever decodes page fonts or imagesDecodes everything, ships pixels in chunks
PaintingValidates, scrolls, composites, paintsProduces an immutable presentation archive
PermissionsPrompts, grants, revocationAsks for a named capability

One renderer is allocated per top-level tab. Crashes, hangs, out-of-memory and malformed output are contained: the browser keeps the last valid frame or shows a tab error, and you can kill a renderer from the built-in Task manager to exercise the same recovery path.

The Rendering Pipeline

From bytes to pixels, a page goes through these stages, all inside the renderer except the last one.

#StageImplementationNotes
1Charset detectionencoding_rsBOM, then HTTP header, then <meta>
2Tokenize + tree buildhtml5ever, driven by BreezeBreeze owns the script boundary so the parser can suspend at </script> and resume
3DOMBreezeStable NodeIds and mutation versions, no pointer identity
4ScriptV8 152 via rusty_v8Classic + module scripts, import maps, top-level await, Workers
5Stylecssparser + Breeze cascadeLayers, nesting, :has-era selectors, @container, @scope, custom properties, calc/trig/round math
6LayoutBreezeBlock/inline flow, flex, grid, table, floats, positioned boxes
7TextFontique + HarfRust + SwashFallback, OpenType shaping, hinted rasterization
8Display listBreezeRetained items, invalidated per change
9Presentation archiveBreezeImmutable, pointer-free, ≤ 64 MiB, sent in 1 MiB chunks
10Composition + paintBrowser processValidates archive, scrolls, composites, imports GPU canvases

Stage 2 deserves a comment. html5ever normally consumes input straight past a <script> result, which is not how HTML works: an inline classic script must see exactly the parsed prefix, and an external blocking script must stop the parser until it is fetched. Breeze keeps the same tree builder, open-element stack, input queue, DOM identities and V8 realm alive across suspensions, which is what makes document.write() and parser-blocking scripts behave correctly.

Own vs Borrow

The rule was: own the parts that define what a browser is (DOM, cascade, layout, scheduling, security boundaries), and reuse maintained libraries for algorithms that are hard to get right and have nothing browser-specific about them. Every dependency carries a comment in Cargo.toml explaining why it is there and what its licence is.

ComponentChoiceLicenceWhy not write it
JavaScriptV8 (v8 crate)BSD-3A competitive JIT is a decade of work; see below
HTML tokenizerhtml5everMIT/Apache-2.0Spec-exact tokenizer state machine; Breeze still owns tree building policy
CSS tokenizercssparserMPL-2.0Same tokenizer Servo/Firefox use
Text encodingsencoding_rsMIT/Apache-2.0Firefox’s implementation of the Encoding Standard
Font discoveryFontiqueMIT/Apache-2.0Fallback and system font enumeration
ShapingHarfRustMITRust port of HarfBuzz
RasterizationSwashMIT/Apache-2.0Hinted, color-outline and bitmap glyphs
SVGresvg / usvgMIT/Apache-2.0With file reads disabled by Breeze’s resolver
Raster imagesimage, jxl-oxide, rav1d + avif-parseMIT/Apache/BSD/MPLPNG, JPEG, GIF, WebP, BMP, ICO, AVIF, JPEG XL
Audiosymphonia, lewton, claxon, opusMPL/MIT/Apache/BSDMP3, AAC, MP4, MKV, Ogg/Vorbis, FLAC, Opus
WebGLANGLE via mozangleBSD-3GLES on D3D11, built from locked source
Public suffix listpsl2MIT/Apache-2.0Cookie domain rules
AllocatormimallocMITSwitched from the system allocator in November

What is notably not a dependency: no layout library (Taffy, Stylo and Blitz were evaluated in August and not adopted), no CSS cascade library, no DOM crate, no networking stack beyond the Windows WinHTTP API, and no UI toolkit. The tab strip, address bar, menus and panels are raw Win32.

JavaScript: From Boa to V8

The first engine was Boa, a pure-Rust JavaScript interpreter. It was a good way to start: no native toolchain, memory-safe, easy to embed. It was also the reason MSN took forever to load. A controlled hidden comparison on the live MSN page measured 12,878.5 ms of JavaScript in Boa against 871.8 ms in Chromium, a 14.77× gap, while networking, parsing, the DOM bridge, style and layout were not the dominant costs.

Before switching, the decision record measured one production-shaped workload (keyed tree reconciliation with objects, arrays, maps, strings and allocation churn) through three engines in real sandboxed renderer processes. Every engine returned the same checksum.

MetricBoaV8 jitlessV8 JIT
Total median480,569 µs57,911 µs41,860 µs
Evaluation median479,676 µs51,857 µs34,767 µs
Setup median868 µs3,525 µs3,936 µs
Speed vs Boa1.00×9.25×13.80×

After the production migration, the same live-MSN comparison looked like this:

MetricBoa (before)V8 (after)Chromium
Median JavaScript time12,878.5 ms5,214.5 ms706.8 ms
Ratio to Chromium14.77×7.38×1.00×

V8 cut JavaScript time by 59.5%, but the remaining 7.38× was no longer the engine. At 15 seconds MSN runs 92–93 scripts and performs about 20,000 DOM mutations. The gap moved to host bindings, mutation invalidation and rendering, which is where most of September and October went.

The engine boundary is deliberately narrow. V8 owns values, evaluation, exceptions, modules, promises and microtasks. Breeze owns DOM, Fetch, storage, navigation, timers, task ordering and IPC. Web API hosts exchange owned, engine-neutral values across a single __hostCall boundary, and microtask checkpoints are native, so a page that replaces window.Promise cannot break the event loop.

There were costs:

  • The executable grew from 19.3 MB (Boa) to 53.8 MB (V8 only).
  • V8’s JIT needs dynamic code. The renderer sandbox normally forbids it, so that one mitigation is lifted only in the renderer. DEP, CFG, ASLR, strict handle checks, child-process denial, network denial and the Job Object limits all stay.
  • V8 security updates track Chrome Stable. An overdue applicable V8 security update is a release blocker.
  • A per-isolate watchdog stops any single author JavaScript entry after ten seconds.

Text Is Harder Than Layout

Text went through three designs in a week.

  1. GDI in the browser process. Fast, but it meant hostile webfont bytes and page text crossed into the privileged process, and measurement didn’t match painting.
  2. COSMIC Text in the renderer (ADR 0002). Secure and correct for complex scripts, but on a frozen Wikipedia page it regressed page-ready by 23.8%, non-network time by 44.0% and layout/paint by 103.6%. A probe attributed about 277 ms to text: 102 ms across hundreds of thousands of cache hits and 175 ms across ~2,664 cold misses.
  3. Three focused libraries (ADR 0003): Fontique for discovery and fallback, HarfRust for OpenType shaping with cached per-face shaper data, Swash for rasterization through one persistent scale context.

Breeze keeps the browser-specific glue: Unicode bidi runs, grapheme-safe fallback boundaries, script resolution, CSS letter/word spacing, quarter-pixel quantization, cache keys tied to resource epochs, and budgets for hostile fonts. It does not reimplement bidi, grapheme segmentation, shaping or rasterization.

Security: Treat Every Byte as Hostile

Each renderer runs in a capability-free Windows AppContainer inside a one-process Job Object with memory limits, no breakaway and no child processes. It cannot open files, registry keys, sockets or devices. Everything it needs is brokered.

The transport is two anonymous pipes, one per direction, with handles inherited explicitly, so there is no named endpoint another local process could connect to. Every frame starts with a fixed 32-byte little-endian header:

1
2
magic[4] | major:u16 | minor:u16 | kind:u16 | flags:u16 |
payload_length:u32 | renderer_session:u64 | sequence:u64
  • magic is BRZ1. Bad magic, a reserved flag, a non-monotonic sequence or an invalid length closes the renderer session.
  • renderer_session is never reused during a browser run, so buffered data from a dead renderer incarnation is rejected.
  • Sequences start at one per direction and never wrap: exhaustion is a fatal protocol error.
  • The decoder reads the full bounded payload before interpreting it, never allocates from an unchecked length, and never decodes unbounded recursive structures. No pointers, HANDLEs, HWNDs or process IDs ever travel as authority.

Every resource has an explicit ceiling. These are implementation limits, not Web standards, and each one has a test for what happens when it is exceeded.

ResourceLimitOn violation
IPC control payload256 KiBReject before allocating
Other bulk IPC payload8 MiBClose the session
Presentation transfer chunk1 MiBValidate offset and declared total
Queued decoded renderer frames8Pipe reader back-pressures
Single request/response body16 MiBReject or abort the stream
All resources of one document32 MiBStop admitting resources
Presentation archive64 MiBKeep the last valid revision
Decoded raster image32 Mpx / 128 MiB BGRADecode in renderer, ship in chunks
Web Storage5 MiB, 1,024 entries per originQuotaExceededError
WebGL GPU slots64 MiB per rendererContext admission fails

The browser validates every presentation update: counts, indices, finite geometry, resource identifiers, byte ranges, revisions, document identities and session identities. A renderer can lie, but it can only lie in ways the browser rejects.

Incremental Rendering

Showing the first frame is easy. A large Wikipedia article has about 24,000 elements and 230 KB of CSS, and it keeps changing after the first frame as stylesheets, fonts, images and scripts arrive. The goal was for each frame to cost in proportion to what changed, not to the size of the document, and to settle a large page within about a second, as Chrome does.

StageMeasured before the workBudget
Full-document style500–800 ms≤ 50 ms
Full-document layout and display list300–400 ms≤ 50 ms
Frame for a small DOM or class change85–100 ms< 5 ms
Script and DOM-binding work during load~1 s≤ 300 ms
First styled frame1.0 s≤ 0.4 s

The techniques are the familiar ones from Blink and Gecko, written against Breeze’s own data structures:

  • A retained box tree whose boxes, including anonymous ones and ::before/::after, keep stable identities, so a mutation rebuilds only the affected children. A seeded mutation fuzzer compares the retained tree against a fresh build after every insertion, removal, move, display and class change.
  • Cached layout results per box, similar in spirit to LayoutNG’s: a pass lays out only boxes whose style, constraints or children changed and replays the rest.
  • Bounded restyles: :hover only restyles elements matched by rules that actually use :hover; sibling combinators and hidden subtrees are bounded the same way.
  • Coalesced mutations: on the DuckDuckGo capture below, 4,759 DOM mutations from script were coalesced into 4,100 render mutations before any style work started.

WebGL2 and GPU Presentation

WebGL is implemented on ANGLE, which translates GLES to Direct3D 11. Contexts are real GLES 3 contexts, not a shim: WebGL2 exposes sized texture formats, vertex arrays, instancing, multisample render targets with framebuffer blits, float/half-float color buffers and shadow sampling. An optional fixture imports unchanged Three.js 0.185.1 and renders twelve scenes (shadows, physical materials, morph targets, HDR multisample resolve, post-processing) as pixel contracts.

Reading every frame back to the CPU, converting RGBA to BGRA and pushing it through IPC would kill animation, so canvases publish shared D3D11 textures instead:

  • Each canvas has three producer-owned slots inside a 64 MiB per-renderer budget.
  • A private shared EGL context resolves multisampling, flips rows and converts to premultiplied RGBA8, without touching the author’s GL state, bindings or queries.
  • GLES fences order author work before the copy. A keyed mutex generation advances on every rewrite, so an old descriptor can never acquire a rewritten slot. Only S_OK from AcquireSync grants ownership: WAIT_TIMEOUT and WAIT_ABANDONED are both positive HRESULTs and both are treated as “not yours”.
  • The IPC message carries only integer identities, extents, adapter LUIDs and share-handle values. No pixels.

The long-term target here is my other project, a Three.js game, running unchanged. Single-player gameplay was first reported playable in Breeze on October 10.

How It Is Tested and Measured

Every automated run is headless. No test, capture or benchmark is allowed to open a visible window, for Breeze or for the reference browser. Chromium runs with --headless and CreateNoWindow; Breeze has a fail-closed automation guard and a hidden capture mode, and the harness verifies the actual child command line before trusting a run.

SuiteWhat it checks
~7,100 unit and integration testsEngine contracts, protocol codecs, malformed IPC, limits
Curated Web Platform TestsStandards behaviour, pinned selection (3,372 passing assertions in September)
Khronos WebGL conformancePinned subset for WebGL 1/2
Alpha matrix (17 fixtures)Breeze vs headless Chromium: visual diff ceilings, readiness, memory, scroll smoothness
Acid3Local copy, served with the original MIME quirks
Fuzzingcargo fuzz targets for parsers and IPC
Live capturesReal sites, fresh profile, settle period, screenshots + metrics

Acid3. Breeze targets Firefox’s score of 96/100 rather than 100. The four subtests Firefox fails check behaviour that later specifications reversed (for example, Selectors Level 4 lets the root element match :first-child, and the DOM Standard now accepts element names like di<v). Passing them would mean implementing 2008 rules no current engine ships, purely to win a test.

Matched Chromium comparison. The original alpha gate (August 24) ran three fresh-profile samples per browser on nine deterministic fixtures:

FixtureBreeze readyChromium loadBreeze / Chromium working setVisual diff / ceiling
Encyclopedia article185.3 ms385.7 ms49.0 / 578.7 MiB0.217 / 0.28
Encyclopedia main164.8 ms398.5 ms26.0 / 562.8 MiB0.063 / 0.12
Responsive blog176.3 ms380.3 ms50.9 / 578.7 MiB0.140 / 0.20
Search results170.3 ms383.0 ms25.7 / 564.1 MiB0.045 / 0.12
Forms/storage155.5 ms384.4 ms25.1 / 565.5 MiB0.049 / 0.12
Layout matrix155.4 ms374.4 ms25.3 / 559.3 MiB0.045 / 0.12
Media/fonts168.5 ms377.1 ms30.2 / 561.0 MiB0.094 / 0.15

This table needs a caveat, and the repository states it explicitly: Breeze “ready” is process start to first owned layout/paint, Chromium “load” is process start to loadEventFired. These are different milestones, and Chromium implements vastly more of the platform. The table is a regression gate for feature-equivalent paths, not a claim that Breeze is twice as fast as Chrome. It is very easy to fool yourself with browser benchmarks, so every published number in the repository comes with what it does and does not prove.

Screenshots and Live Measurements

All captures below were taken today from a release build of the current main, with a fresh profile, a 1536×864 window at 125% scaling, and a six-second settle period. Nothing was cherry-picked or retouched. Writing this article turned out to be a good compatibility test: the first round of captures showed this blog’s layout broken and MDN half-rendered, so both were fixed (grid, logical properties, justify-*, icons, deferred scripts, HTMLPreElement) before these were retaken.

Breeze showing DuckDuckGo search results
DuckDuckGo’s modern results page: 37 scripts, 4,759 DOM mutations, dark theme, Search Assist panel and sitelinks. Fitting that the top result is Servo.

Breeze scoring 469 out of 555 on HTML5test
HTML5test: 469 out of 555. The test is no longer maintained, so it is an inventory of features rather than a target, but it is a good check that APIs are not silently missing.

This blog rendered in Breeze
This blog in Breeze. In the first capture the sidebar, search box and post list overlapped; the fixes for that landed in the browser the same day.

MDN CSS grid guide rendered in Breeze
MDN’s CSS grid guide: header menus, breadcrumbs, sidebar filter, “In this article” with the active section highlighted, and the live example with its Play button. Remaining bug: the ad banner at the top is clipped, so its logo’s alt text shows through.

The metrics from the same captures, as reported by Breeze’s own benchmark JSON:

PagePage readyJavaScriptLayout + paintScripts runDOM mutationsRenderer working setTotal working set
Wikipedia article624 ms582 ms194 ms12492144 MiB203 MiB
neolisk.blog708 ms229 ms60 ms1316119 MiB164 MiB
DuckDuckGo results757 ms2,600 ms449 ms374,759295 MiB364 MiB
HTML5test616 ms988 ms167 ms123,881234 MiB284 MiB
MDN grid guide776 ms1,623 ms310 ms11810535 MiB599 MiB

“Page ready” is Breeze’s first presented frame, not complete page readiness; JavaScript keeps running after it, which is why on DuckDuckGo, HTML5test and MDN the JavaScript column is larger than the page-ready column. The browser process itself stays between 44 and 68 MiB in all five runs. The rest is the sandboxed renderer.

For comparison, the September readiness assessment measured Chrome’s working set at 645–676 MiB on the same Wikipedia pages where Breeze used 147–192 MiB. Again: Chrome is doing much more, so this is not a like-for-like efficiency claim, but it does show that a small engine has room to stay small.

How It Was Built

I did not type 488,000 lines of Rust in three months. Breeze was built with AI coding agents, OpenAI Codex and Claude Code, doing most of the implementation, while I chose the direction, wrote and enforced the rules, reviewed the pull requests, tested the builds, and merged. Only I merge to main. The interesting engineering turned out to be in the rules, which live in AGENTS.md and have grown with every mistake:

RuleWhy it exists
Protected main, linear PR history, merge commits onlyEvery change reviewable, every regression bisectable
Source files ≤ 400 lines (500 hard limit), frozen ceilings for old onesAgents happily keep appending to one file; facades like css.rs and layout.rs must stay small and delegate to submodules
Never open a visible window in automated runsA stray browser window on my desktop during a benchmark is not acceptable
No site-specific workarounds or benchmark-only pathsEvery fix must be standards-based and survive review as open source
Primary specs first; record compatibility decisions in docsHence 204 Markdown documents, including 7 architecture decision records
A benchmark takes ~1 minute, intermediate checks < 5 minutesA 75-minute cold-build timing plan got abandoned for warm rebuilds
Report numbers with the machine load they were measured underA smaller window on an idle machine understated real load time by about a second
Check that a filtered test actually ranCargo exits 0 on running 0 tests
Every dependency has a provenance and licence commentThe project is meant to be open source

The build itself became a project. One crate of ~15 MB of Rust meant every edit recompiled everything and 4,000+ unit tests could only run together. WebGL and the low-level platform primitives have since moved into their own crates (breeze-webgl, breeze-platform), and the next splits (codecs, networking, DOM) are already mapped out with the measured dependency graph between engine areas. CI is a deliberate smoke gate (format, dependency policy, harness self-tests, three hidden-browser checks), and the full WPT, visual and performance suites run locally before a push.

What Is Still Missing

Plenty, and the repository is explicit about it:

  • Platform: Windows 10/11 x64 only. The shell, painting, networking and sandbox are all Win32.
  • Site isolation: one renderer per tab, not per site. Out-of-process iframes and Spectre mitigations are not done.
  • Accessibility: an AccessKit integration exists, but it is far from complete.
  • Media: one non-DRM H.264/AAC video path; no DRM, no broad codec coverage.
  • Compatibility: most real sites still show some divergence from Chrome (like MDN’s clipped banner above), and heavy script pages (MSN) still take several times Chrome’s JavaScript time, mostly in bindings and invalidation rather than V8.
  • Performance on large documents: first paint is fast, but full-document style and layout and late widget readiness remain priorities.

Lessons

  1. The Web platform is mostly API surface. Layout is the fun part, but the JavaScript bindings and Web APIs are more than four times its size and where most of the compatibility bugs live.
  2. Measure the engine before optimizing around it. No amount of binding work would have closed a 14.77× interpreter gap. A one-day three-engine probe made the V8 decision obvious.
  3. Reuse algorithms, own policies. HarfBuzz-grade shaping and V8-grade JIT are not where a new browser differentiates. The cascade, layout, scheduling and security boundaries are.
  4. Draw the security boundary early. The process-isolation decision was written on day three, but the DOM, scripts and decoders still started in the browser process and had to be moved into the sandboxed renderer over several issues. Every feature added before that move had to be carried across it.
  5. Be precise about what a benchmark proves. “Ready in 185 ms vs Chrome’s 386 ms” sounds like a headline until you notice the two numbers measure different milestones.
  6. AI agents amplify whatever process you give them. With strict rules, small files, headless tests and honest measurement, they produced a working browser engine in three months. Every rule in that table exists because, at some point, an agent did the opposite.

Breeze is a temporary name, and this is an alpha. But it renders Wikipedia, searches DuckDuckGo, runs a Three.js game and shows this blog, from a codebase where I can point at every stage between the socket and the screen. That was the point.


Victor Zakharov
WRITTEN BY
Victor Zakharov
Web Developer (Angular/.NET)