MVCC 如何实现非阻塞读?
解读
在国内 MongoDB 岗位面试中,MVCC(多版本并发控制)是区分“只会调 API”与“懂存储引擎”的分水岭。
面试官真正想听的是:
- WiredTiger 如何利用 MVCC 让读写互不阻塞;
- 快照、事务 ID、全局时间戳如何协同;
- 你能否把“非阻塞”落到代码路径(如
readConcern: snapshot时的可见性判断)。
回答时务必围绕 WiredTiger 存储引擎 展开,避免泛泛而谈“数据库通用 MVCC”。
知识点
- WiredTiger 的 MVCC 基础单元
- 每条记录以 update chain(修改链表)形式存储,链上节点含 transaction ID (txnid)、start/commit timestamp、durable timestamp 与指向旧版本的指针。
- 快照(Snapshot)机制
- 读操作开始时,WiredTiger 在内存中拍一份 读事务快照,记录当前所有“正在进行”的 txnid 列表;后续版本可见性判断只依赖这份快照,无需再锁表。
- 全局时间戳(Global Timestamp)
- MongoDB 4.0+ 引入 stable timestamp、oldest timestamp,与 WiredTiger 的 durable timestamp 对齐,保证副本集节点在崩溃恢复时也能读到一致快照。
- 可见性算法(非阻塞核心)
- 遍历 update chain,找到第一个 commit timestamp ≤ 读事务快照的 read timestamp 且 txnid 不在快照“活跃列表” 的版本,即为可见版本;若找不到则返回“未找到”,整个过程只读内存,无需 latch 或锁。
- 垃圾回收(History Store)
- 旧版本默认写入 WiredTiger 的 History Store 表;当所有读事务的 read timestamp 都大于该版本的 durable timestamp 时,后台 sweep thread 异步清理,避免无限膨胀。
- 与 MongoDB 语义的映射
readConcern: local直接拿最新已提交版本;readConcern: majority拿 majority commit point 之前的版本;readConcern: snapshot在事务内绑定 snapshot timestamp,整个事务都基于同一快照,实现 可重复读 且读写互不阻塞。
答案
WiredTiger 通过 update chain + 事务快照 + 全局时间戳 三件套实现非阻塞读:
- 写操作提交时,只在链头追加新版本,并原子性更新 commit timestamp,不原地覆盖旧数据;
- 读操作启动时获取 读事务快照,记录当前活跃事务 ID 列表与自己的 read timestamp;
- 遍历 update chain,利用快照判断“该版本是否已提交且对我可见”,全程 无锁、无 latch;
- 即使其他事务并发写入,读线程仍沿着旧版本指针拿到一致数据,实现 读写互不阻塞;
- 旧版本由 History Store 异步回收,保证长期运行也不会内存爆炸。
因此,MongoDB 在 wiredTiger 引擎下,默认所有查询都是 非阻塞读,只有在显式使用 X 锁(如 $isolated 操作) 时才会退化到阻塞模式。
拓展思考
- 长事务踩坑:国内业务常因 未提交的大事务 导致 History Store 暴涨,触发 “Cache stuck” 告警;监控 txn-prepared、txn-committed 延迟可提前预警。
- ** Majority read 与脏读区别**:当 enableMajorityReadConcern=false(旧版本副本集默认关闭)时,
readConcern: majority会退化为 local,可能读到 rollback 数据;金融场景务必保持开启并关注 stable timestamp 推进。 - 与 MySQL InnoDB 差异:InnoDB 的 MVCC 依赖 undo log + read view,清理由 purge thread 负责;而 WiredTiger 把旧版本放到 独立的 History Store BTree,清理粒度更细,但对 timestamp 推进更敏感——若 oldest timestamp 被长事务卡住,会阻塞整个集群的 checkpoint,表现为 write stall。
- 性能调优:当发现 read 延迟抖动,优先检查 cache eviction 与 History Store IO;适当调大 cache_size 或降低 long-running transaction 超时阈值,可显著减少非阻塞读路径的 cache miss。