《分布式系统架构原理和实践指南》15.1 端到端:把全书组件拼成迷你缓存

把第 1~14 章十四个机制组件拼成迷你缓存 NewMini:get 走 L1→L2 提升→单飞回源,写走副本组→双 origin→journal→失效广播;e2e 七条断言锚定启动、并发合并、失效广播、容量守卫与配额拒载,runall 79 全绿。

一台能跑起来的迷你缓存

前十四章分别产出一个可运行包:boot 的注册池、cache 的 TTL 存储、evict 的 LRU 准入、load 的双形态 origin、ring 的一致性哈希、shard 的拓扑路由、repl 的副本版本组、rebal 的故障检测与重分片、coher 的 L1/L2 与失效总线、storm 的单飞、quota 的窗口配额、persist 的快照与 WAL、meta 的控制器、scale 的度量账本。这些零件各自在自己的包测试里行为正确,可缓存不是零件的清单——站在客户端面前的是一个能并发 get/set、坏了一台还能继续服务的东西。第 15 章做的是这个收口:NewMini(n, lruCap, opsMax) 把十四种机制按真实调用次序装进一台 Mini,再配七条端到端断言,证明「拼起来」真的能转。

单飞合并、失效广播、配额拒绝这些机制原理已在《大规模分布式计算深入解析》卷二十五(分布式缓存内核)讲透,本节不重写机制清单,只把它们捏成一个共享时钟、共享总线、全局一把锁的整体。

全部零件,一枚 Mini 装下

Mini 的每个字段都是前面某章产物的真实实例,没有任何新发明。mu 是全局串行锁,nodes 按 id 存每台 Node,order 保持启动次序,dead 标记故障节点。先看结构本身:

// file: internal/platform/e2e/mini.go
// tier: L3
// verify: go test ./internal/platform/e2e/ -count=1
// Node is one cache server in the mini cluster: a local TTL store (chapter 2)
// behind an LRU admission guard (chapter 3) and an L1 tier (chapter 9)
// subscribed to the shared invalidation bus.
type Node struct {
	id    string
	local *cache.Store
	guard *evict.LRU
	l1    *coher.L1
}

// Mini is the mini distributed cache. Every field is a real component from a
// preceding chapter; the cluster keeps them consistent with explicit invariants
// (single-flight to the origin, invalidation broadcast, fencing writes).
type Mini struct {
	mu      sync.Mutex
	clock   *cache.Clock
	pool    *boot.Registry
	ring    *ring.Ring
	topo    *shard.Topology
	l2      *coher.L2
	bus     *coher.Bus
	origin  *load.Origin  // the physical store behind the cache (chapter 4).
	sOrigin *storm.Origin // the same logical origin, read-counter form (chapter 10).
	flight  *storm.Flight
	journal *persist.Journal
	ctrl    *meta.Controller
	det     *rebal.Detector
	reshard *rebal.Resharder
	repl    *repl.Group
	quote   *quota.Ledger
	meter   *scale.Meter
	capLed  *scale.Ledger
	nodes   map[string]*Node
	order   []string
	dead    map[string]bool
}

逐字段追回它来自哪一章,读路径与写路径各消费哪些:

Mini 字段包(章)在集群里的角色
clockcache(2)全局时钟,让跨节点 TTL 到期确定
poolboot(1)连接池注册表,启动时注册 "orders" 池
ringring(5)一致性哈希环,拓扑未覆盖或主节点死亡时回落 Owner
toposhard(6)64 分片主备拓扑,route 的第一判据
l2 / buscoher(9)共享层最新版本;失效广播总线
origin / sOriginload(4)/ storm(10)同一个逻辑 origin 的两种形态(写透与读计数)
flightstorm(10)并发未中合并成一次回源
journalpersist(12)每次写的持久化底账
ctrlmeta(13)节点注册、MarkDead、领导权帧
det / reshardrebal(8)心跳判死;死节点键迁移
replrepl(7)epoch/version 写门禁与 Handoff
quotequota(11)窗口配额 Allow 与 Rejected 计数
meter / capLedscale(14)命中度量;准入总账

NewMini:装配车间,一份时序图

NewMini(n, lruCap, opsMax) 是整台集群的构造函数。参数的含义都写在注释里:lruCap 决定每台 Node 的准入守卫容量,opsMax 决定配额账本每个窗口放行多少操作。装配顺序不是随手排的,它决定 route 与失效广播依赖的对象必须比使用者先存在:

// file: internal/platform/e2e/mini.go
// tier: L3
// verify: go test ./internal/platform/e2e/ -count=1
// NewMini boots an n-node cluster whose LRU guards hold at most lruCap keys and
// whose admission ledger accepts at most opsMax operations per window. A global
// clock keeps expiry deterministic across nodes.
func NewMini(n, lruCap, opsMax int) *Mini {
	mc := &Mini{
		clock:   cache.NewClock(),
		pool:    boot.NewRegistry(),
		ring:    ring.NewRing(128),
		topo:    shard.NewTopology(64),
		l2:      coher.NewL2(),
		bus:     coher.NewBus(),
		origin:  load.NewOrigin(),
		sOrigin: storm.NewOrigin(),
		journal: persist.NewJournal(),
		ctrl:    meta.NewController(),
		det:     rebal.NewDetector(3),
		reshard: rebal.NewResharder(),
		repl:    repl.NewGroup(3),
		quote:   quota.NewLedger(100, opsMax, 1<<20),
		meter:   scale.NewMeter(),
		capLed:  scale.NewLedger(),
		nodes:   map[string]*Node{},
		dead:    map[string]bool{},
	}
	_ = mc.pool.RegisterPool("orders", 1_000, 64)
	for i := 0; i < n; i++ {
		id := fmt.Sprintf("n%d", i)
		node := &Node{
			id:    id,
			local: cache.NewStore().WithClock(mc.clock),
			guard: evict.NewLRU(lruCap),
			l1:    coher.NewL1(mc.bus, mc.l2),
		}
		mc.bus.Subscribe(node.l1)
		mc.nodes[id] = node
		mc.order = append(mc.order, id)
		mc.ring.Add(id)
		mc.topo.RegisterNode(id)
		mc.ctrl.Register(id)
		mc.det.Touch(id)
		mc.capLed.Add(id, 0)
	}
	mc.flight = storm.NewFlight(mc.sOrigin)
	for s := 0; s < 64; s++ {
		primary := mc.order[s%n]
		backup := mc.order[(s+1)%n]
		_ = mc.topo.AssignShard(s, primary, backup)
	}
	return mc
}

四段装配各说明白一件事:

第一段搭共享基建。 全局时钟、注册池、一致性哈希环、拓扑、L2 共享层、失效总线、双 origin、journal、控制器、检测器、重分片器、副本组、配额账本、度量器;ring 带 128 个虚拟位置、topo 固定 64 个分片、repl 组大小 3、配额账本字节预算 1<<20。这些对象互相不引用彼此,顺序没有强约束。

第二段装每台节点,并把它注册进五张账。 每台 Node = TTL 存储(ch2)+ LRU 准入守卫(ch3)+ 挂了 bus 的 L1(ch9)。mc.bus.Subscribe(node.l1) 让这台节点成为失效广播的订阅者。此后同一台 id 依次进入 ring.Add、topo.RegisterNode、ctrl.Register、det.Touch、capLed.Add(id, 0)——环、拓扑、控制器、心跳探测、容量账本五处掌握的全是同一份成员清单。缺一次注册,route 或检测就会少看见它。

第三段造单飞。 mc.flight = storm.NewFlight(mc.sOrigin),单飞与读计数共用同一个 origin 形态。

第四段指派分片。 64 个分片按 order 轮转绑定主备:order[s%n] 为主,order[(s+1)%n] 为备。AssignShard 的返回值被显式忽略,因为分片数 64 一定小于 n==1 时也不越界——四台集群每台平均负责 16 个主分片。

决定点:单飞只发生在 L1 与 L2 都未中之后

读路径三个出口,每个出口都有明确的构造理由。先上代码:

// Get implements the full read path: admission gate, L1 hit, L2 promote, and
// finally a single-flight load that fills L2/L1 from the origin.
func (mc *Mini) Get(key string) (string, bool) {
	mc.mu.Lock()
	defer mc.mu.Unlock()
	if !mc.quote.Allow(64) {
		return "", false // over budget: rejected under load (chapter 11).
	}
	if e, ok := mc.nodes[mc.route(key)].l1.Get(key); ok {
		mc.meter.Hit()
		return e.Value, true
	}
	n := mc.nodes[mc.route(key)]
	if e, ok := n.l1.Read(key); ok { // promote from shared tier.
		mc.meter.Hit()
		return e.Value, true
	}
	value, ok := mc.flight.Get(key) // single-flight to the origin.
	if !ok {
		mc.meter.Miss()
		return "", false
	}
	ver := mc.l2.Write(key, value)
	n.l1.Copy(key, coher.Entry{Value: value, Version: ver})
	n.guard.Put(key) // admission: this node now holds the key.
	mc.capLed.Add(n.id, 1)
	mc.meter.Hit()
	return value, true
}

逐一拆解,每个决定都是一个可辩护的边界:

第一道门是配额,不是路由。 quote.Allow(64) 不通过直接拒绝——带 64 字节读取成本的准入先于任何缓存查找。窗口配额(ch11)回答「这台集群现在能不能接新的操作」,它比数据在哪里更优先;过载时吐出 ("", false),客户端据此退避。

route 被调用了三次,且共用同一把锁。 mc.route(key) 在 L1 命中、L2 提升、写入三重出口各解析一次,但都发生在 mc.mu 之内——主节点不会在一条读的中间被 FailNode 换掉。三次解析消耗可忽略,换来的是一致性保证。

展开是 L1 数据面 → L2 共享层 → 单飞回源。 l1.Get 命中直接落地;n.l1.Read 把共享层最新版本提升进本地数据面;两处都未中才轮到 mc.flight.Get。决定点是:单飞绝不越过还热着的共享层。热键第一次未中时,L2 里往往还有权威值,12 个并发 miss 若全部直接打 origin 就是一场人为惊群;先问过 L2,缓存仍热的场景只回一次共享层就收敛。

回源成功后,四步联动。 l2.Write 落共享层并拿到版本 ver;l1.Copy 把同版本拷进本节点数据面;guard.Put 记准入、capLed.Add 记账(ch3/ch14)——容量守卫看到的驻留集和账本看到的完全一致;最后 meter.Hit 交观测。四步的顺序不是巧合:先共享层后本地、先数据后账本,缺一步都会让断言抓不到一致状态。

决定点:写透广播的是一对新版本,不是删除

写路径的问题比读更细:缓存与 origin 哪个先写?副本怎么取得一致版本?所有 L1 副本怎么知道自己手里的旧值作废?Set 用六步把答案钉死:

// Set writes through: applies the mutation to the replica group (fencing stale
// writers), persists to both origin representations, appends the durability
// journal, stamps the shared tier, and broadcasts the new version so every L1
// copy is invalidated.
func (mc *Mini) Set(key, value string) error {
	mc.mu.Lock()
	defer mc.mu.Unlock()
	if err := mc.repl.Apply(mc.repl.Epoch(), mc.repl.Version(), key, value); err != nil {
		return err
	}
	mc.origin.Set(key, value)
	mc.sOrigin.Set(key, value)
	mc.journal.Apply(key, value)
	mc.reshard.Put(key, value, mc.route(key)) // who owns the key now.
	ver := mc.l2.Write(key, value)
	mc.bus.Publish(key, ver)
	return nil
}

第一步是副本门禁。 mc.repl.Apply(mc.repl.Epoch(), mc.repl.Version(), key, value) 把当前 epoch 与版本随写入一起送进副本组(ch7)。epoch 是领导权代际:failover 之后旧主再写必定因为 epoch 不符被拒——这是第 15 章「不双写」的根。

第二步双写同一逻辑 origin。 origin.Set 与 sOrigin.Set 是同一份键值的两种形态——一个作为 ch4 的物理存储、一个作为 ch10 单飞的读计数来源。双写保证读路径无论走哪条计数线看到的都是同一条值的同一版本。

第三步进 journal。 journal.Apply(key, value) 把这次变更追加进持久化底账(ch12),崩溃后由快照加 WAL 尾重放找回。

第四步记重分片账。 mc.reshard.Put(key, value, mc.route(key)) 记录「此刻这条键归谁」。它不迁移任何数据,只让重分片器持有与 route 一致的归属答案。

第五、六步是写透的核心决定:广播的是一对新版本,不是删除指令。 ver := mc.l2.Write(key, value) 更新共享层,然后 mc.bus.Publish(key, ver) 把新版本号广播给所有订阅的 L1。每个 L1 对比自己手里的版本与广播版本,低于即自失效。发「新版本」而不是「请删掉 key」的原因很清楚:版本让作废判断与读并发安全共存——读正在 Hold v1 时,广播 v2 只会让之后的读拿到 v2,不会让在途读看到半片删除。

边界断言:七条断言钉住整台机器

e2e 包的七条断言由同一个标准测试驱动跑进 go test:

// file: internal/platform/e2e/checks_test.go
// tier: L3
// verify: go test ./internal/platform/e2e/ -count=1
package e2e

import "testing"

// TestChecks runs every assertion in this integration package through the
// standard Go test driver, so `go test ./internal/platform/e2e/` and the dslab
// harness agree on the same expected properties.
func TestChecks(t *testing.T) {
	for _, c := range Checks() {
		if err := c.Fn(); err != nil {
			t.Fatalf("%s: %v", c.Name, err)
		}
	}
}

本节主题要求「集群启动、并发合并、失效广播、容量守卫、配额拒载」五条边界,先看第一条——它证明整台集群启动后能路由并服务,且两条 origin 形态与缓存三方一致:

{Name: "e2e:cluster-boots-and-serves-routed-keys", Fn: func() error {
	mc := NewMini(4, 100, 100_000)
	if err := mc.Set("orders:u1", "balance=100"); err != nil {
		return err
	}
	got, ok := mc.Get("orders:u1")
	if !ok || got != "balance=100" {
		return fmt.Errorf("read=%q ok=%v want balance=100 true", got, ok)
	}
	// Both origin representations agree with the cache.
	if ov, _ := mc.origin.Get("orders:u1"); ov != "balance=100" {
		return fmt.Errorf("load-origin=%q diverged", ov)
	}
	if sv, _ := mc.flight.Get("orders:u1"); sv != "balance=100" {
		return fmt.Errorf("storm-origin=%q diverged", sv)
	}
	if mc.topo.Coverage() != 64 {
		return fmt.Errorf("coverage=%d want 64 shards assigned", mc.topo.Coverage())
	}
	return nil
}},

第二条是失败口径的对立面:先写后读,写能读回、双 origin 一致——「读自己的写」在整集群层面成立:

{Name: "e2e:write-broadcasts-invalidation-to-all-copies", Fn: func() error {
	mc := NewMini(4, 100, 100_000)
	_ = mc.Set("u1", "old")
	_, _ = mc.Get("u1") // the owner's L1 now holds version 1.
	primary := mc.route("u1")
	if _, ok := mc.nodes[primary].l1.Get("u1"); !ok {
		return fmt.Errorf("owner L1 should hold a copy before the update")
	}
	_ = mc.Set("u1", "new") // published version 2.
	if _, ok := mc.nodes[primary].l1.Get("u1"); ok {
		return fmt.Errorf("stale version-1 copy must be invalidated by the bus")
	}
	got, ok := mc.Get("u1")
	if !ok || got != "new" {
		return fmt.Errorf("post-invalidation read=%q ok=%v want new true", got, ok)
	}
	return nil
}},

其余三条各自锚定一个边界,断言与期望如下:

  • e2e:concurrent-misses-merge-into-one-origin-load:先把 hot=P0 种进 sOrigin,12 个 goroutine 并发 flight.Get("hot"),要求 mc.sOrigin.Loads()==1——12 个 miss 合并成一次真实回源,每个等待者都拿到 P0。
  • e2e:capacity-guards-bound-resident-set:NewMini(4, 4, 100_000),只种 origin,40 把键全部读出后,要求每台节点 guard.Len()>4 即为错、resident<40、capLed.Total()==40——准入账本收到过 40 次、驻留集却被 LRU 压得远小于 40。
  • e2e:quota-guards-and-rejects-over-budget:NewMini(4, 100, 3)(每窗口 3 次操作),前 3 次 get 必须放行、第 4 次必须拒绝,且 mc.quote.Rejected()==1——拒载既发生又有账可查。

边界与常见错误

  • 注册必五处,漏一处就有「看不见的节点」。 新节点若只进 ring 不进 topo,route 不会以它为 primary;只进 det 不进 ctrl,故障检测与领导权就会对同一台节点打架。NewMini 里 ring.Add、topo.RegisterNode、ctrl.Register、det.Touch、capLed.Add 必须同次出现。
  • route 返回值要用变量接住。 Get 里三处调用 mc.route(key),若其中任一重算发生在 FailNode 之后又不在锁内,读数会分裂。mc.mu 必须覆盖整条读/写路径。
  • L2 写与 L1 拷贝必须同一版本。 ver := mc.l2.Write(...) 拿到的版本必须原样传给 n.l1.Copy,两个组件各写各的版本会让 L1/L2 版本号失配,失效广播对比错位。
  • 单飞不是并发穿透的替代品。 Get 在 L1 与 L2 都未中才进 flight;若把 flight.Get 提到 l1.Read 之前,热键第二次访问会绕过共享层直接回源。
  • 写透里 shutdown 与 journal 的次序不能换。 repl.Apply 失败必须直接返回、不碰任何 origin 与 journal——被 fence 的旧主写出半条会污染账本。

小结

NewMini 把十四章的产物按「共享基建 → 节点五注册 → 单飞 → 分片指派」四段装成一台 Mini:Get 走门禁→L1→L2 提升→单飞回源,Set 走副本门禁→双 origin→journal→重分片账→新版本广播。七条端到端断言把「拼起来的集群能并发读写、坏了节点还一致」这个命题跑成 go test ./internal/platform/e2e/ -count=1 里能失败能通过的真实约束,全卷 79 条断言经 go run ./cmd/runall 全绿。拼装完成之后,下一问是横向的:一条 orders:u1 从客户端到落进某个分片,中间每一站到底在干什么——这是 15.2 卷线的课题。

阅读导航:上一节:14.3 观测与追踪:命中率/穿透率账本 · 下一节:15.2 卷线:一条 key 的完整旅程 。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「books」更多文章

  1. 《分布式系统架构原理和实践指南》9.3 降级与恢复:fallback 与半开探测
  2. 《分布式系统架构原理和实践指南》9.2 舱壁隔离:并发池与信号量
  3. 《分布式系统架构原理和实践指南》9.1 熔断三态:闭合、打开与半开