/docs/internals/go-sidecar

Go Sidecar Internals

Overview

The Go Sidecar is a ~3,000-line Go binary with no external runtime dependencies. It binds on the port configured in nextdeploy.yml and proxies requests to Next.js, caching full HTTP responses in memory.

Radix tree indexing

Cache keys are stored in a compressed radix (Patricia) tree keyed on the request path plus a normalised query string. Lookup is O(k) where k is the path length โ€” typically under 50 ns on modern hardware regardless of cache size.

// Simplified cache key structure
type CacheKey struct {
    Path        string   // e.g. "/blog/hello-nextdeploy"
    QueryHash   uint64   // FNV-1a hash of sorted query params
    AcceptEnc   string   // "br" | "gzip" | ""
}

// Radix tree node
type node struct {
    prefix   string
    children []*node
    entry    *cacheEntry   // nil for internal nodes
}

Worker pool

Cache population (fetching from Next.js and storing the response) runs in a fixed goroutine pool. If all workers are busy โ€” a thundering-herd scenario after a cold start or purge โ€” subsequent requests for the same key coalesce via a singleflight group: only one goroutine fetches, and all waiters receive the same response.

var group singleflight.Group

func (c *Cache) populate(key string, fetch func() (*Response, error)) (*Response, error) {
    res, err, _ := group.Do(key, func() (interface{}, error) {
        return fetch()
    })
    return res.(*Response), err
}

Keep-alive proxy

The sidecar maintains a persistent HTTP/1.1 keep-alive connection pool to the Next.js upstream. Connection reuse eliminates the TCP and TLS handshake cost on cache misses, keeping proxy overhead under 200 ยตs even on a loopback connection.

transport := &http.Transport{
    MaxIdleConnsPerHost: cfg.MaxImageWorkers * 2,
    IdleConnTimeout:     90 * time.Second,
    DisableCompression:  true,  // sidecar manages its own compression
}

Cache invalidation

On each nextdeploy ship, the daemon sends a POST /internal/purge request to the sidecar over the loopback interface before the Caddy cutover. This guarantees no stale HTML is served after a deploy. The endpoint is firewalled and only reachable from localhost.