Deep Dive: Coalescing, Popularity Residency and the Regional Shield, Coded

Companion to the main guide's Global distribution. That part names three mechanisms — request coalescing, popularity-weighted residency, and a regional shield tier — as prose, one sentence each. This file makes each one a working code sketch: what data structure it needs, what the control flow looks like under concurrent load, and where each one's guarantee actually comes from. It also answers a question worth asking directly first: is Colossus itself globally replicated so it can serve traffic? The short answer is no, and the reason why is the key that unlocks the other three.

First: Colossus Is Not the Thing That Gets Globally Replicated

It's a reasonable first guess: if you want a video fast everywhere, replicate the file everywhere, the way a multi-region database replicates rows. That's not what the Origin storage and Global distribution parts describe, and the distinction matters for everything below.

Multi-region data replication (not this system)What the Origin storage/Global distribution parts actually do
What movesThe authoritative copy itself, to N regions, kept consistentNothing about Colossus moves. A separate, disposable cache tier (GGC + regional shield) pulls copies outward on demand.
Who decides where a copy landsA placement/replication policy, decided ahead of viewingViewer request pattern decides — a segment only exists at a GGC node because someone near it actually asked for it (the Global distribution part’s "popularity-proportional replication").
What happens if a copy is lostRe-replicate from another authoritative replica — still a durability eventNothing durability-relevant happens. A GGC node losing its cached copy just means the next request there is a miss, refilled from origin. The Origin storage part’s invariant: Colossus survives regardless of what any cache tier does.
Consistency model neededReal one — replicas must agree, or reads divergeNone needed between cache nodes. Every cache tier is a read-through view of one single upstream; two GGC nodes can legitimately hold different subsets of segments with zero coordination between them.

So when the video says (or implies) "Colossus is globally replicated, then served" — the more precise statement is: Colossus itself stays put as a small number of large, durable clusters (Google doesn't publish exact placement, but it is not thousands of nodes — it's normal-datacenter-count infrastructure). What actually reaches 1,300+ cities is a completely different, purpose-built layer sitting in front of it: the regional shield tier and GGC nodes, which hold ephemeral, evictable, re-fetchable copies — not additional durable replicas. Colossus may well have its own internal multi-datacenter redundancy for disaster-recovery reasons (any serious durable store does), but that redundancy exists to protect the one source of truth, not to shorten the path to a viewer in Jakarta. The thing that shortens that path is everything in the rest of this file.

Request Coalescing, Coded

The naive version, and why it breaks

Without coalescing, a cache node's miss path looks like: if not in cache: fetch from upstream; store; return. Under a single request at a time, that's correct. Under concurrency — say a segment goes cold, then 400 viewer requests for it land on the same GGC box within the same 5 ms window — every one of those 400 goroutines/threads independently observes a miss, and every one independently calls upstream. 400 concurrent misses become 400 origin fetches for the same bytes, which is exactly the thundering-herd failure the Global distribution part’s production trap describes.

The fix: a singleflight-shaped in-flight map

The standard fix (this is literally what Go's golang.org/x/sync/singleflight package is for — a real, widely-used library, not a hypothetical) is: track in-flight fetches in a map keyed by request key. The first caller for a key becomes the "leader" and does the real fetch; every other caller for the same key that arrives while the leader is still working attaches to the same in-flight future instead of starting its own.

coalescing.go — request coalescing for a cache miss path

package cache

import "sync"

// call tracks one in-flight upstream fetch that other goroutines can join.
type call struct {
	wg  sync.WaitGroup
	val []byte
	err error
}

// Coalescer collapses concurrent misses on the same key into one fetch.
type Coalescer struct {
	mu    sync.Mutex
	inFlight map[string]*call
}

func NewCoalescer() *Coalescer {
	return &Coalescer{inFlight: make(map[string]*call)}
}

// Fetch returns segment bytes for key, guaranteeing that no matter how many
// goroutines call Fetch(key) concurrently, upstream() runs at most once
// per key at a time — every other caller shares the first caller's result.
func (c *Coalescer) Fetch(key string, upstream func() ([]byte, error)) ([]byte, error) {
	c.mu.Lock()
	if existing, ok := c.inFlight[key]; ok {
		// Someone is already fetching this key. Don't call upstream again —
		// just wait for their result.
		c.mu.Unlock()
		existing.wg.Wait()
		return existing.val, existing.err
	}

	// We're the first. Register ourselves as the in-flight call for this
	// key BEFORE releasing the lock, so nobody else can slip in and also
	// become "first" for the same key.
	cl := &call{}
	cl.wg.Add(1)
	c.inFlight[key] = cl
	c.mu.Unlock()

	cl.val, cl.err = upstream() // the ONE real fetch, for however many callers
	cl.wg.Done()

	c.mu.Lock()
	delete(c.inFlight, key) // future misses start a fresh fetch, not this stale one
	c.mu.Unlock()

	return cl.val, cl.err
}

Two details that are easy to get wrong and are exactly why this is worth writing out instead of hand-waving: (1) registering the in-flight call in the map has to happen before the lock is released and before upstream() runs — otherwise a second goroutine can slip through the gap and also become a "leader," which defeats the whole point. (2) the entry is deleted from the map only after the fetch completes, and only by the leader — a follower never mutates the map, it only reads and waits. Every later miss for the same key (after this one's callers have all been served) starts a genuinely fresh fetch, so a follow-up request an hour later doesn't get some ancient cached error.

5 concurrent misses on the same segment, coalesced to 1 fetch
5 concurrent misses on the same segment, coalesced to 1 fetch

Popularity-Weighted Residency, Coded

Coalescing (above) only protects one miss event. If a segment gets requested, coalesced-fetched, cached with a flat TTL, evicted at TTL expiry, and then gets hit again — the whole herd re-forms at the next expiry. Popularity-weighted residency is what prevents that: track request rate per key, and let that rate control how long a segment stays resident and how eagerly it should be pre-pushed to more nodes, instead of every object getting an identical, popularity-blind TTL.

Tracking "hot," cheaply

A per-request counter that never resets would just measure lifetime total requests — a video popular a year ago would look permanently "hot" long after nobody's watching it. What's needed is recent rate, and the cheap way to track that without storing a timestamped log per key is exponential decay: each access bumps a running score up, and the score decays toward zero between accesses. A key requested constantly stays near its ceiling; a key requested once and then never again decays back to "cold" within a bounded window.

residency.go — exponential-decay popularity score and tiering

package cache

import (
	"math"
	"sync"
	"time"
)

type popularity struct {
	score    float64
	lastSeen time.Time
}

// ResidencyTracker turns raw access events into a decayed popularity score
// per key, and maps that score onto a residency tier (replica count + TTL).
type ResidencyTracker struct {
	mu      sync.Mutex
	scores  map[string]*popularity
	halfLife time.Duration // time for a score to decay to half its value
}

func NewResidencyTracker(halfLife time.Duration) *ResidencyTracker {
	return &ResidencyTracker{
		scores:   make(map[string]*popularity),
		halfLife: halfLife,
	}
}

// RecordAccess bumps key's score, decaying it first for elapsed time since
// the last access — so a burst long ago doesn't count the same as a burst
// happening right now.
func (r *ResidencyTracker) RecordAccess(key string) float64 {
	r.mu.Lock()
	defer r.mu.Unlock()

	p, ok := r.scores[key]
	now := time.Now()
	if !ok {
		p = &popularity{lastSeen: now}
		r.scores[key] = p
	} else {
		elapsed := now.Sub(p.lastSeen)
		decayFactor := math.Pow(0.5, float64(elapsed)/float64(r.halfLife))
		p.score *= decayFactor
	}
	p.score += 1.0
	p.lastSeen = now
	return p.score
}

// Tier is a residency decision: how many nodes should hold this key, and
// for how long, given its current decayed popularity score.
type Tier struct {
	ReplicaCount int
	TTL          time.Duration
}

// TierFor converts a popularity score into a concrete residency decision.
// Thresholds are illustrative — real systems tune these against actual
// traffic distributions, not fixed constants.
func TierFor(score float64) Tier {
	switch {
	case score >= 1000: // viral — pin widely, hold long
		return Tier{ReplicaCount: 5000, TTL: 6 * time.Hour}
	case score >= 50: // warm — moderate spread
		return Tier{ReplicaCount: 200, TTL: 30 * time.Minute}
	default: // cold / long-tail — single-node, short-lived
		return Tier{ReplicaCount: 1, TTL: 2 * time.Minute}
	}
}

The important architectural point isn't the specific numbers (those are illustrative) — it's that the residency decision is a pure function of a decayed counter, not a static config value per video. This is also exactly why the Global distribution part’s production trap (a flat, popularity-blind TTL) fails: a system without this tracker has no signal at all to differentiate a segment being hit 10,000 times/sec from one hit once an hour, so it can't help but treat them identically.

The Regional Shield Tier, Coded

This is the detail that's easy to miss: the Coalescer above only helps if the concurrent misses share a process's memory. Two different GGC boxes, in two different ISPs, both missing on the same segment 50ms apart, have no way to know about each other — each one independently thinks it's the first to ask. Without another layer, request coalescing's guarantee ("N misses → 1 fetch") silently degrades back to "N misses at this one node → 1 fetch, but still N nodes → N fetches to origin."

The regional shield tier closes that gap by being a shared upstream that many GGC nodes fan into. It runs the exact same Coalescer logic as before — the code doesn't need to change — but now the "callers" joining an in-flight fetch are entire GGC nodes across a region, not goroutines within one process. Composing them is just wiring a GGC node's miss path to call the shield instead of origin directly, and the shield's own miss path to call origin through its own Coalescer:

shield.go — a two-tier cache hierarchy composed from the same Coalescer

package cache

// GGCNode is one edge box, physically inside an ISP. Its "upstream" is not
// origin — it's the regional shield, which many GGC nodes in the same
// region share.
type GGCNode struct {
	local    map[string][]byte // this node's own cached segments
	coalesce *Coalescer        // dedupes concurrent LOCAL misses only
	shield   *RegionalShield   // this node's one upstream
}

func (g *GGCNode) Get(segmentKey string) ([]byte, error) {
	if b, ok := g.local[segmentKey]; ok {
		return b, nil // hit — never leaves this box
	}
	return g.coalesce.Fetch(segmentKey, func() ([]byte, error) {
		b, err := g.shield.Get(segmentKey) // may itself be a miss upstream
		if err == nil {
			g.local[segmentKey] = b
		}
		return b, err
	})
}

// RegionalShield sits between many GGCNodes and origin. Its Coalescer's
// in-flight map is now doing the SAME job as GGCNode's, but scoped across
// every GGC node in the region that fans into this one shield — which is
// exactly what a single node's local Coalescer structurally cannot do.
type RegionalShield struct {
	cached   map[string][]byte
	coalesce *Coalescer
	origin   OriginFetcher // Colossus, reached over the private backbone (B4/B2)
}

func (s *RegionalShield) Get(segmentKey string) ([]byte, error) {
	if b, ok := s.cached[segmentKey]; ok {
		return b, nil
	}
	return s.coalesce.Fetch(segmentKey, func() ([]byte, error) {
		b, err := s.origin.Fetch(segmentKey) // the ONE call origin ever sees
		if err == nil {
			s.cached[segmentKey] = b
		}
		return b, err
	})
}

Trace what happens when a segment goes viral in one region under this composition: 300 GGC nodes each independently miss within the same second. Each node's own Coalescer collapses its own concurrent viewer requests into exactly 1 call to the shield — so the shield sees 300 calls, not however many total viewers there were. But 300 is still 300 origin fetches if the shield doesn't also coalesce — which is exactly what its own Coalescer does, on the same segment key, collapsing all 300 into 1 real call to origin.Fetch. Two coalescing layers, same code, different scope, and the fan-in ratio compounds: node-level coalescing collapses viewers→node, shield-level coalescing collapses node→origin.

Fan-in compounding across two coalescing layers
Fan-in compounding across two coalescing layers

This is why the Global distribution part frames the regional shield as specifically absorbing the case of "many GGC boxes missing on the same newly-popular segment at once" — it's not a bigger cache, it's coalescing applied at the one scope where node-local coalescing structurally can't reach.

Putting All Three Together

The three mechanisms aren't independent features bolted on side by side — they cover three different scopes of the same underlying problem, and each one's absence would reopen a gap the others don't cover:

Request coalescing (node-local)Collapses concurrent viewer requests hitting one box into one upstream call. Scope: within a single process's memory.
Regional shield (coalescing, one scope up)Collapses concurrent node misses across a whole region into one origin call. Scope: across machines, via a shared upstream.
Popularity-weighted residencyPrevents the herd from re-forming at the next TTL expiry by pre-emptively keeping hot segments resident at more nodes, longer. Scope: across time, not concurrency.

Coalescing (both scopes) protects a single burst. Residency protects against the same burst recurring. Take any one away and a specific failure mode reopens: no node-level coalescing → one box's own viewers thundering-herd it; no shield-level coalescing → a viral segment's fan-in from hundreds of nodes hits origin directly; no popularity residency → even a perfectly coalesced viral segment gets evicted on the same flat TTL as everything else and re-triggers the whole coalescing dance every few minutes indefinitely, instead of settling into a stable, widely-replicated, long-TTL steady state.

The Invariants

  • Guarantees: For any given segment, at any given moment, at most one fetch to origin is in flight per coalescing scope — one per node for viewer-level bursts, one per region for node-level bursts. However many concurrent callers exist at either scope, the upstream call count is bounded by the number of distinct keys being requested, never by the number of callers.
  • Does not guarantee: That the very first request for a genuinely cold, never-before-seen segment is fast — coalescing only helps once a second caller arrives while the first is still in flight; it does nothing for a lone first request, which still pays the full round trip to origin. This is the same caveat the Global distribution part’s own invariants section already states: a cold object's first hit anywhere in the world is necessarily slower than its steady-state traffic once every tier has caught up.