
Show HN 项目演示用 Go 和 Rust 构建支持百万级 RPS 的分布式引擎
来源标题:Show HN: Building 1M+ RPS Distributed Engines in Go and Rust
一个 Show HN 项目展示了用 Go 和 Rust 构建支持 100 万以上 RPS 的分布式引擎,技术栈包括 io_uring、Raft 共识、SIMD 和无锁缓存。项目附带五章完整手册和测试仓库,内容涵盖 LSM-Tree 存储引擎、WAL、无锁数据结构与内核旁路 I/O。完整资料通过 Telegram 机器人获取。
以下正文由 AI 翻译自 Hacker News 最新(原文版权归原站所有),可能存在偏差,重要内容请以原文为准。
用 Go 和 Rust 构建 1M+ RPS 分布式引擎:io_uring、Raft 共识、SIMD 与无锁缓存。 🚀 Snowden SAY | 深度系统工程实验室社区: 每日深度剖析生产环境事故、内存泄漏、Linux 内核调优与无锁模式——尽在我们的工程频道:@snowdensay。 📚 完整专著(全部 5 章 + 含测试的代码仓库):可通过 Telegram 机器人 @Snowden_book_bot 获取 模块 1(含于下文):架构基础、内存布局与不变量 模块 2:高并发核心与无锁数据结构(完整手册) 模块 3:生产环境崩溃恢复、WAL 与状态机一致性(完整手册) 模块 4:内核旁路 I/O、SIMD 加速与硬件卸载(完整手册) 模块 5:线上事故复盘、混沌工程与生产基准测试(完整手册) 第 1 章 — LSM-Tree 存储引擎:从零实现预写日志与多线程压缩
- 架构概览 LSM-tree 通过将随机点写转换为顺序追加 I/O,以读放大为代价换取写放大。写路径严格按顺序经过五个组件: flowchart LR W[Writer] -->|1. append| WAL[Write-Ahead Log<br/>group-commit fsync] W -->|2. insert| MT[Memtable<br/>skiplist, 64MB cap] WAL --> Q{fsync ack} Q --> ACK[Ack to client] MT -->|3. rotate when full| IMM[Immutable memtable queue] IMM -->|4. flush| L0[L0 SSTs: 4-8 files<br/>overlapping, newest wins] L0 -->|5. compaction| L1[L1..Ln SSTs<br/>non-overlapping runs] Loading 最重要的一条不变量:当且仅当其 WAL 记录已 fsync 时,写入才是持久化的——且这必须发生在 memtable 插入对读可见之前。违反这一顺序会产生经典的“删除复活”异常:墓碑只存在于丢失的 memtable 中,因此检查点之后被删除的记录会在崩溃恢复后重新出现。 指标 目标 参考实现达成值(§2/§3) 写吞吐(16B 键,fsync=off)
1.1M ops/s 1.24M ops/s,16 个写线程 组提交下的写 p99(fsync=on,O_DSYNC) <8ms 180K ops/s 时 5.7ms 压缩写放大(size-tiered,4 层) <12x 实测 11.3x 读 p99(点查,L0-L2 命中率 80%,块缓存 2GB) <2.5ms 1.9ms kill -9 后的恢复时间(64MB memtable,10GB WAL) <4s 2.8s 稳态内存(不含块缓存) <200MB 148MB
- 组件 1:预写日志 2.1 记录格式与撕裂写问题 WAL 必须能承受部分磁盘写入(撕裂写)。对一条记录直接调用 write() 并非原子操作——断电前内核可能只持久化了 4,096 字节中的 2,000 字节。因此每条 WAL 记录都携带对其 payload 的 CRC32C 校验以及长度头;恢复过程在遇到第一条 CRC 校验失败的记录时停止。 +------------+------------+------------+------------+ | len: uint32| crc32c:u32 | type: u8 | payload... | +------------+------------+------------+------------+ 头部 = 13 字节,小端序。type ∈ {FULL=0, FIRST=1, MIDDLE=2, LAST=3} 大于块大小(32KB)的记录会被拆分为 FIRST/MIDDLE/LAST 链,与 LevelDB 完全一致,这样单个超大值就不会毒化整个块的恢复过程。 在 NVMe 上每次写 fsync 约需 80–200µs;SATA SSD 约 1ms;云 EBS gp3 约 5ms。在 100K 写/秒的情况下,这要么占用一个核心 10–20% 的时间在 fsync 系统调用上,要么导致队列深度爆炸。组提交可以摊薄这一开销:写者将自己的记录入队,然后在条件变量上等待,由单个提交线程将当前队列中的所有内容批量合并为一次 fsync。 延迟计算:设提交间隔为 T、到达率为 λ,则平均附加延迟 ≈ T/2 + fsync_time,fsync 次数/秒 ≈ 1/T·(批次数)。最优做法是将批量等待上限设为约 200µs,并让批量大小浮动。低于 10K ops/s 时,批量会缩小到 1–3 条记录,fsync 占主导——这是预期且正确的行为。 // wal.go — Torn-write-safe WAL with group commit. package lsm import ( "encoding/binary" "errors" "fmt" "hash/crc32" "io" "os" "sync" "sync/atomic" "time" ) const ( walBlockSize = 32 * 1024 walHeaderSize = 13 walMaxPayload = walBlockSize - walHeaderSize recFull byte = 0 recFirst byte = 1 recMiddle byte = 2 recLast byte = 3 ) var ( ErrWalCorrupt = errors.New("wal: crc mismatch during recovery") ErrWalClosed = errors.New("wal: closed") ErrRecordTooBig = errors.New("wal: record exceeds 4GB hard limit") ) var castagnoli = crc32.MakeTable(crc32.Castagnoli) // WriteBatch is one durable unit: a set of mutations committed atomically. type WriteBatch struct { Data []byte // opaque payload; engine-level format lives in memtable.go type walRecord struct { typ byte data []byte // groupCommitQueue batches concurrent writers into single fsyncs. type groupCommitQueue struct { mu sync.Mutex pending []*commitWaiter // writers waiting for the next fsync committing bool type commitWaiter struct { errCh chan error // buffered, size 1 func (q *groupCommitQueue) join() (*commitWaiter, bool) { q.mu.Lock() defer q.mu.Unlock() if len(q.pending) > 4096 { // concurrency bound: shed load before RAM blowup return nil, false w := &commitWaiter{errCh: make(chan error, 1)} q.pending = append(q.pending, w) return w, true // WAL appends records and group-commits them. One instance per DB. // Safe for concurrent use by any number of goroutines. type WAL struct { f *os.File path string gcq groupCommitQueue seq atomic.Uint64 // logical LSN of last acked write fileSize int64 closeMu sync.Mutex closed bool // committer lifecycle stopCh chan struct{} doneCh chan struct{} func OpenWAL(path string) (*WAL, error) { // O_DSYNC: write() itself flushes to platter; we still issue explicit // Fdatasync-compatible syncs in batches because O_DSYNC on every write // serializes the append path. We rely on explicit Sync() after batch write. f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0o644) if err != nil { return nil, fmt.Errorf("wal: open %s: %w", path, err) st, err := f.Stat() if err != nil { f.Close() return nil, fmt.Errorf("wal: stat %s: %w", path, err) w := &WAL{ f: f,
(原文较长,此处译出前 6000 字,完整内容请点「打开原文」。)
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。