Performance
Where borgo's speed comes from, mechanically: what work has been moved out of the request path, what the network is asked to carry, and where the streams push back. No numbers on this page — it is about the machinery, and every claim on it is something you can go read in the source. Where borgo will lose is at the end, in as much detail as the rest. The numbers live in bench/, a harness written so that somebody who does not trust us can rerun it, with its committed results rendered as a page — republished by CI on every push to main — that is itself a borgo app (source).
If you are looking for the shape of the system first, read architecture; this page assumes it.
Work moved out of the request path#
The cheapest request is the one that finds everything already computed. borgo's boot sequence exists mostly to make that true.
The HTML shell is cut up once. index.html is read at boot and split into the exact pieces a render concatenates: the part before <!--app-->, that part split again at </head> in two versions (with and without the shell's <title>, so a page that sets its own does not end up with two), the tail split at the props slot, and two prebuilt tails for pages that ship no JavaScript. Injecting a page's <head> is then a join of three strings that already exist. The naive alternative — a regex rewrite of the shell head per request — is the kind of thing that costs nothing on a single request and shows up under load.
The asset index is built once. In production, one recursive walk of public/ records, for every file, its content type, whether it is worth compressing, whether a .br and a .gz sibling exist, and the byte length the build recorded for it — and reads the build's own hashed outputs into memory, up to 64 MiB in all. Serving a static file is then a map lookup plus a stat of the file and one of the sibling chosen: no directory read, and no file opened for what is held in memory. The stat stays on purpose — it settles whether the file still exists, whether it changed under the index, and whether a precompressed sibling has since been deleted, and the ETag and the cache policy are worked out from what it returns. A file written after boot is not in the index and falls back to a live lookup, so nothing breaks; it costs more.
The route table is decided at build time. pages/ is scanned by borgo build, not by the server. The generated manifest already holds each route's pattern, its module, its resolved layout chain, and whether it uses islands — and the array is already sorted so static segments come before dynamic ones. Matching a request is a walk of that array with no sorting, no filesystem access and no layout resolution.
The environment is read once. Ports, the API base URL, the render deadline, the body limit, the CSP template, whether CSRF is enforced — all resolved at boot into closures the handler captures, on both halves. No process.env lookups on any request path a browser reaches, and no chance of a request seeing a half-parsed limit.
Compression happens at build time where it can. borgo build writes .gz and .br siblings next to every compressible asset — gzip at maximum level, brotli at maximum quality with a size hint — and keeps them only when they are actually smaller. At request time the server picks a variant and sends it, from memory for the build's hashed outputs and off disk for the rest. Nothing is compressed per request that could have been compressed once.
Metrics reuse the match the request already did. The route pattern is the label a Prometheus histogram wants, and it is the one the front's own match of the request returned, so turning BORGO_METRICS=1 on does not add a scan of the route table. A file served from public/ skips the histogram, and asset paths and /favicon.ico skip the request line borgo dev prints; the access log, when BORGO_ACCESS_LOG turns it on, records them like any other request.
Static assets#
A static request in production answers from the index, with three things attached: ETag, Last-Modified, and Content-Length.
The ETag is derived from the file's size and mtime, and it is per variant — the brotli sibling has a different tag from the identity file, because the same URL negotiates to different bytes depending on Accept-Encoding. That matters more than it sounds: a shared tag across encodings is how a cache ends up handing brotli bytes to a client that asked for identity. It is a weak tag, W/"…", and deliberately so: size and mtime are weak evidence — two files of equal length share the first half, and every tool that copies a file with its date (cp -p, rsync -t, docker's COPY) carries the second across — so the header stops claiming an equality it cannot check. If-None-Match compares weakly, so the 304 below still works; what a weak tag gives up is If-Range, which is the one place a wrong match would splice new bytes onto an old prefix.
GET /assets/client-a1b2c3d4.js
If-None-Match: W/"i5-mt4ppeo5-br"
304 Not Modified
A 304 costs a map lookup, the stat and a header comparison. No body is sent, and for a build output held in memory no file is opened. If-Modified-Since is honored too, but only when there is no If-None-Match to decide first, as RFC 9110 requires.
Content-hashed build outputs are served public, max-age=31536000, immutable, so a returning browser does not even revalidate them — and immutable is a claim about bytes, so it is made only while the file on disk still has the byte length the build recorded for that name; a file swapped under its hashed name falls back to no-cache. A production build names everything it emits after its content — the entry bundle and the stylesheet as well as the split chunks — and your index.html goes on referencing /assets/client.js and /assets/style.css: the server resolves those names against the build's own record when it boots, so nothing in your HTML carries a hash you would have to maintain. A dev build keeps the plain names, since the dev server rebuilds behind a document it already sent. Anything borgo cannot vouch for is served no-cache, which costs one bodyless 304 per asset per navigation. A generated service worker is deliberately no-cache too: a heuristically cached sw.js would make every deploy lag behind by however long the browser felt like holding it.
One class of file is not served at all, whatever the index says: a file whose own name starts with a dot (.DS_Store, which carries the listing of its directory; .gitkeep; an .env somebody dropped into public/), and anything under a dot-directory (public/.git/config). Both answer 404. The single exemption is /.well-known/ as the first path segment, exact case, because RFC 8615 is a standard whose whole point is being fetched — ACME http-01 renews your certificate through it. A nested .well-known is not the standard's and is refused like any other dot-directory. borgo export applies the same rule before copying public/, and the precache.json a service worker installs from lists only what the build emitted, never a dotfile.
Range requests get one subtlety right that matters for correctness rather than speed. If-Range makes a range conditional on the client still holding the representation it started downloading, and RFC 9110 requires a strong validator on both sides before a range may be honoured. Because a borgo asset URL negotiates to different bytes per encoding, the mismatch is not exotic — a resume arriving without the original Accept-Encoding is asking for a slice of the brotli file to be filled from the identity one — and because borgo's validators are weak, every If-Range on an asset gets the full file instead, still streamed off disk, never buffered through memory. A bare Range with no If-Range is untouched, so media seeking is unaffected; the cost is confined to interrupted downloads, and it is the direction the RFC requires.
Compression, on both sides#
Go pools its gzip writers. A gzip.Writer carries roughly 800 KB of deflate window and hash tables; allocating one per response would dominate everything else the handler does. borgo.Serve keeps them in a sync.Pool, and a finished writer is reset to point at io.Discard before being parked — so a completed request is not kept alive by the pool, and a stray late write cannot land in someone else's stream.
Small responses stay identity. The Go middleware buffers the first kilobyte before deciding: under that, the gzip header and trailer eat most of the saving, so the response ships uncompressed. The same threshold governs buffered JSON on the Bun side. A Vary: Accept-Encoding is set regardless of the decision, because a cache that stored an identity response without it would serve those bytes to gzip-capable clients too.
Nothing is compressed twice. An /api/* response is written by the process that answered the port, so there is nothing in the path that could inflate it. On the page path the front's transport asks for no encoding the browser did not ask for, and forwards what comes back untouched — a proxy that inflated a compressed document and re-sent it as identity would pay for the decompress and throw the compression away.
Pre-encoded and streaming responses pass through. The Go middleware detects text/event-stream and an existing Content-Encoding at WriteHeader time and switches to passthrough, so an event stream is never buffered waiting to reach a compression threshold, and Flush on a still-buffering response commits it as identity immediately rather than holding it. Both readings are of the whole header, under every spelling of the key: a handler that added text/plain before text/event-stream, or assigned h["content-type"] through the map, used to walk past the gate and get gzip put over its stream — the browser folds the key and reads every line, so borgo does too. The reverse mistake is covered as well: an empty Content-Encoding value names no coding, so ["", "br"] is read as br and left alone rather than compressed twice and mislabelled. 1xx responses pass straight through, trailers survive whatever the body length, and a 204/304 is never given an encoding over zero bytes.
A Content-Length the handler declared is kept honest, not trusted. Under gzip it is deleted — it describes the uncompressed body. Under identity, a second contradictory line is dropped (the first is the one net/http sized the body by; two of them make a client drop the connection with no status), and a length the body has already outgrown at commit is deleted before the header leaves, instead of reaching a client that then reads a truncated body as unexpected EOF. Either way the mismatch is logged, once per response — Content-Length N but wrote M bytes — and M is what the wire accepted, not what the handler offered, so a client that hung up mid-download is not reported as an application bug.
Documents are gzipped, not brotli'd. Brotli's compression ratio is worth paying for once at build time; it is not worth paying for on every server-rendered document. Rendered HTML goes through gzip with a sync flush per chunk, which is what keeps streamed Suspense boundaries arriving progressively instead of pooling behind the compressor.
Streaming with real backpressure#
Server rendering produces a stream, and borgo pulls it rather than pushing it.
documentStream implements pull: React is asked for its next chunk only when the consumer has room for it. A slow client therefore throttles the render instead of letting a whole document pile up in memory ahead of a socket that is not draining. When the consumer goes away — the tab closed, the request aborted — the stream's cancel calls return() on React's iterator, which ends the render rather than letting it finish a page nobody will read.
Compression is where that property is usually lost, and borgo goes out of its way to keep it. Node's gzip pushes output from a data event that cannot consult the consumer's queue, so the pump does the waiting instead: before each read it parks while desiredSize is at or below zero, and wakes from the consumer's next pull. Without that, the moment a response was compressed — which in production is every document — the render would be drained as fast as zlib accepts writes and the backpressure would be decorative.
Two smaller versions of the same idea:
- A
HEADrenders for real, because its status and headers have to be honest, and then cancels the body. The render stops; it does not keep going into a stream with no reader. - A request whose client has already hung up answers
499and builds nothing. The alternative is expensive in exactly the wrong situation: a client that declares a long body and disconnects would otherwise buy a full_500render — loader, API round trip, document — per abandoned upload.
What the browser is asked to download#
Loader and action code never ships. Pages are transpiled for the client build with the loader, action, prerender and prerenderPaths exports eliminated and unused imports trimmed. A page can import your database module at the top of the file and the browser receives none of it — not the call, not the import, not the transitive dependency. CI greps the built assets for a sentinel to keep that honest.
One chunk per page. The client route manifest maps each pattern to a dynamic import(), and the build runs with splitting on, so the initial document carries the runtime, React and your layouts, and each page's code arrives when that page is first visited. Navigating fetches the chunk and the loader data in parallel.
Pages can opt out of JavaScript entirely. export const hydrate = false removes the page from the client manifest, and the render skips the props script and the client entry tag:
export const hydrate = false;
export default function About() {
return (
<main>
<h1>About</h1>
<p>Nothing on this page needs a runtime.</p>
</main>
);
}
That page ships HTML and CSS. The props are not serialized at all — not sent and not built — and the client entry is not referenced, so the browser never requests it. If such a page contains an <Island>, it gets a second, smaller entry that hydrates only the island markers. export const hydrate = "visible" keeps the full page bundle but defers the hydration work until the page scrolls into view. Client navigation and hydration covers the three modes.
Navigation transfers props, not documents. A client-side navigation asks the same URL with ?__borgo=props and gets the loader's return value as JSON — no shell, no markup, no re-render of anything the browser already has. The response is private, no-store, because it carries session-shaped data.
Prefetching is budgeted. Links scrolled into view get their route chunk prefetched — the chunk only, because that is a static file and prefetching it costs the server nothing. Loader props are prefetched on a settled hover (a short intent delay, so a pointer crossing a long list does not fire one loader per anchor it passes) and immediately on focus or touch, which are deliberate already. Prefetched props live in a small cache with a short TTL and a hard entry cap, and an entry that is evicted without being used has its response body cancelled — an abandoned prefetch would otherwise hold its socket open until the tab closed. A form submission clears the whole cache, because a mutation invalidates any loader data prefetched before it.
Realtime#
An SSE hub renders each frame once. Publish encodes the event and its JSON payload into wire bytes a single time, then hands the same byte slice to every subscriber's channel. The cost of a broadcast is one encode plus one channel send per subscriber, not one encode per subscriber.
The sends are non-blocking against a small per-subscriber buffer: a client too slow to keep up skips messages rather than blocking the publisher and, through it, every other subscriber. Each write arms a short deadline so one blackholed connection cannot pin its goroutine forever, and the connection's server-wide read and write deadlines are cleared when the stream opens, so a stream is not killed by a timeout meant for slow requests.
WebSocket topics are a relay, and the relay is dumb on purpose. A publish serializes the message once and writes it to every socket on the topic from the process that holds them — since 0.30 the Go process, so borgo.Push is a call with no hop at all. There is no per-message business logic in the path — that belongs in Go routes, reachable over /api/*.
The event stream is not buffered anywhere, and one line of it is not decoration. borgo.SSE writes a :ok comment — an SSE frame every client ignores — before it returns the stream to your handler, and without it a stream that stays quiet until its first real event leaves the browser hanging on fetch() for exactly that long. The X-Accel-Buffering: no header asks nginx and friends for the same favour, but they are the intermediaries you might not have. The one that used to be unavoidable was borgo's own: the stream crossed a Bun front server whose single socket deadline bounded the response write as well as the request read, which took a mechanism of its own to work around. It no longer crosses anything — the process that answers the public port is the one your handler runs in — and the write deadline that could cut it (BORGO_WRITE_TIMEOUT, a minute on the public port) is cleared by an event stream at its first byte, and borgo.SSE then bounds each of its own writes at 10 seconds. Realtime has the handler side.
The Go side#
The borgo package imports nothing outside the Go standard library. The golang.org/x/tools requirement in go.mod belongs to borgogen, which is a build-time tool and never links into your API binary; what you deploy is net/http plus your code. There is no router library, no ORM you did not choose, no dependency injection container resolving graphs at startup.
borgo.Serve mounts a plain http.ServeMux with method patterns — the standard library's own matcher, which is a trie, so the Go half of the routing is not the linear scan the page side is. Around it sit borgo's own wrappers and the middleware the app registered — the request's id and the counters, the security headers, the deadlines, the in-flight cap, the body limit — and, nearest the handlers, gzip and a panic recovery that answers 500 only while the response is still uncommitted, so a handler that panicked halfway through a streamed body is logged rather than having garbage appended to it.
borgo.JSON marshals before it commits a status, which buys two things: an unencodable value becomes a logged 500 instead of a truncated 200, and the response can state an honest Content-Length instead of falling into chunked encoding.
The timeout matrix is chosen rather than defaulted. ReadHeaderTimeout is set, because slow-header clients are a cheap denial of service. Read and write timeouts are a minute on the public port, and they measure silence rather than the whole request: every read of a body and every write of a response moves them forward, so a slow upload or a long streaming response that keeps making progress is never cut, and an event stream keeps its own deadlines. borgo.Bind's reader limit bounds how much a body may carry. IdleTimeout reclaims kept-alive connections. All of them are overridable — see request limits and timeouts.
For anything genuinely cacheable, borgo.Cache writes the header and lets a proxy do the work:
//borgo:route GET /api/tasks
func ListTasks(w http.ResponseWriter, r *http.Request) {
borgo.Cache(w, 60*time.Second, 10*time.Minute)
borgo.JSON(w, http.StatusOK, TaskList{Tasks: tasks})
}
It downgrades itself to private when the response carries a Set-Cookie, which keeps a shared cache from storing a personalized response — and since 0.21 the order no longer matters. The check used to run once, inside Cache, so Cache then SetSession emitted public on a response that ended up carrying a session cookie, and RFC 9111 §3.5 lists public as exactly the directive that lets a shared cache store a Set-Cookie response. Now the guard runs again where every header is staged at once, on the way out of the handler: on a response carrying any Set-Cookie — read under every spelling of the key — public becomes private, s-maxage is dropped, and a bare private is added if nothing else says it. max-age is left alone, because it is legitimate for a private cache and private beside it already bars the shared one. Caching covers the rule.
Cached pages: incremental regeneration#
A page that exports revalidate opts its rendered HTML into a shared cache — pages and routing covers the authoring side; this is what the mechanism does and refuses to do.
Shared by construction. The copy is rendered from an anonymised request — cookies, Authorization and Accept-Encoding removed, method forced to GET — so whatever a loader would personalise from is simply not there. The finished response is then still refused, loudly and per page, if it was not a 200, set a cookie under any spelling, or carries per-request bytes (the same requestResidue check borgo export runs). The failure direction is always no caching, never shared what was personal: a refused page serves fresh on every request with X-Borgo-Cache: bypass and one log line naming the reason.
One render per key, whatever the burst. Concurrent misses on one key await a single in-flight render. A stale copy — past its revalidate seconds — is served immediately with X-Borgo-Cache: stale while one background render replaces it, so the window expiring never turns into a thundering herd, and a regeneration that fails leaves the last good copy serving, said once in the log.
Invalidation is the data's, not the clock's, when you want it. borgo.Revalidate(path) and borgo.RevalidateTag(tag) reach the cache directly: it lives in the process your handler runs in, so dropping the pages that depend on the data you just wrote is a function call, not a round trip. (It used to ride an internal topic to the Bun front, which is why the publish endpoint still refuses that topic by name rather than acknowledging an invalidation nothing can act on.) revalidate = "manual" makes that the only way a copy leaves.
The replay is cheap, and the csp survives it. The stored copy is one identity representation; gzip is negotiated per replay like any render, compressed once at store time for pages that allow it. Pages whose scripts carry a CSP nonce are the exception twice over: a frozen nonce would be no CSP at all, so the stored copy keeps its render's nonce as a substitution key and every replay swaps in a fresh one — body and header together, re-compressing that response. Still far cheaper than a render.
Warm restarts. Copies persist under .borgo/cache/html (BORGO_CACHE_DIR moves it), each with the id of the build that rendered it. A restart on the same build boots with its cache warm and serves without rendering; a new build sweeps every old copy at boot, the same story hashed asset names tell. The write is fire-and-forget behind the response — a disk that stops taking writes costs the persistence, never the request.
The honest limits. The cache is per instance: two borgo processes behind a load balancer each hold their own copies, and borgo.Revalidate drops the pages in this one — for multiple instances you need to reach each, or accept the clock as the bound. The cache is bounded at 512 entries (the key includes the query string, so an attacker varying queries meets LRU eviction, not unbounded growth). And it is still your server doing the serving — a CDN edge in front of a cacheable page is faster than any of this; what ISR buys is dynamic data with render-once economics, no edge required.
What borgo does not optimize#
The list below is where borgo will lose, and to whom.
Rendered documents are not cached unless the page opts in. A document without a revalidate export goes out private, no-store, because it embeds the props of whoever asked for it — the page cache exists only for pages that declared themselves shareable, and it lives in your server's memory, not at an edge. A framework that serves a prerendered page from a CDN edge still beats borgo on a cacheable marketing page; borgo export for the genuinely static, revalidate for the shared-but-live, and borgo.Cache on API routes are the answers, and none of them is a CDN.
No image or font pipeline. No resizing, no format negotiation, no font subsetting. The build is one Bun.build call and stays that way. Put a CDN, an image proxy or vips in front if you need it.
The page route table is a linear scan. Every request walks the route array splitting path segments until something matches. Perfectly fine at the scale a pages/ directory reaches; a framework with a compiled radix trie wins on an app with a thousand routes.
Documents are gzipped through a pooled stream. Both halves pool: Go its writers, and the render service a small pool of zlib streams reused across documents (a fresh stream's native init and teardown showed plainly in the profile of the bench ssr page before the pool). A finished document flushes its gzip trailer without ending the transform, resets the native stream, and parks it — capped at 32 streams, ~26MB at the ceiling, reached only after a burst of that many concurrent compressed documents; a stream any failure touched dies instead of parking.
The API hop is a real HTTP round trip. Every loader call serializes JSON in Go, crosses loopback, and parses it in Bun. A monolith calls a function. Six sequential API calls in one loader cost six round trips — use Promise.all — and no amount of framework tuning removes the boundary, because the boundary is the design.
No component or fragment caching in SSR. Every document renders the whole tree. There is no memoized subtree, no partial rendering, no equivalent of a server component cache.
Loader data is not streamed on client navigations. One JSON payload, fetched in parallel with the route chunk. Streaming is applied to the initial SSR, where it matters most; a navigation waits for the whole loader result before rendering.
Islands download with the entry. Island components are registered eagerly, so client="visible" defers hydration work, not bytes. A page full of heavy islands ships them all.
Broadcast fan-out is a loop under a mutex. The SSE hub holds one mutex while it offers the frame to every subscriber's channel. Correct and cheap for hundreds of connected clients; it is not a message bus, and at tens of thousands of subscribers you want one.
One process per port. No clustering, no port reuse, no worker pool. Scale by running more instances behind your reverse proxy, each pair on its own public port.
No HTTP/2, no TLS. Both are the reverse proxy's job. That is a deliberate simplification and it means borgo alone, on port 3000, is not a complete edge.
Dev is not the thing to measure. In development React is built unminified, precompression is skipped, the asset index is not built, every module carries react-refresh instrumentation, and the render service restarts on every code change. Benchmark borgo start against a borgo build, or you are measuring the dev loop.