如何查看 cache 命中率?
解读
在国内一线互联网与金融企业的 MongoDB 面试中,“cache 命中率” 是衡量内存配置是否合理、是否需要扩容或优化索引的核心指标。
面试官真正想确认的是:
- 你是否知道 WiredTiger 存储引擎默认使用 “LRU 缓存”(cacheSizeGB)来缓存最近访问的页;
- 你是否能快速给出可观测指标并解释其业务含义;
- 当命中率低于 95% 时,你是否具备调优思路(扩容内存、精简索引、调整淘汰策略等)。
回答时切忌只说“看某个数字”,而要给出命令 + 指标名 + 阈值 + 调优动作的完整闭环。
知识点
- WiredTiger 缓存模型:
- 内部缓存(Internal Cache)由 cacheSizeGB 参数控制,默认占物理内存的 50%(≤4 GB 时)或 50%(>4 GB 时)。
- 读操作时,若目标页不在缓存,则触发 “page fault” 从磁盘加载,导致 latency 跳升。
- 关键指标:
- wiredTiger.cache.bytes read into cache(累计读入缓存的字节数)
- wiredTiger.cache.bytes written from cache(累计写回磁盘的字节数)
- wiredTiger.cache.internal pages evicted、modified pages evicted(淘汰页数)
命中率公式:
hit ratio ≈ 1 – (bytes read into cache / total bytes requested)
实际面试中可简化为:
hit ratio ≈ 1 – (bytes read into cache / (bytes read into cache + bytes already in cache))
- 观测工具:
- mongostat 的 faults 列:每秒 page fault 数,>50 需警惕;
- db.serverStatus() 输出中的 wiredTiger.cache 子文档;
- mongotop 可辅助定位热点表;
- Atlas 监控 或 自建 Prometheus + mongodb_exporter:指标名 mongodb_ss_wt_cache_bytes_read_into_cache。
- 国内云厂商差异:
- 阿里云 MongoDB 4.4+ 在控制台直接展示 “缓存命中率” 曲线,但面试时必须能说出底层指标来源,否则会被认为“只会看控制台”。
- 腾讯云、华为云同理,均封装了 cache.hitRatio 指标,但底层仍调用 serverStatus。
答案
步骤一:登录 mongos 或 mongod 实例,执行
mongo --host 127.0.0.1:27017 -u root -p xxx --authenticationDatabase admin
步骤二:获取缓存统计
var stat = db.serverStatus().wiredTiger.cache;
print("Bytes read into cache : " + stat["bytes read into cache"]);
print("Bytes currently in cache : " + stat["bytes currently in the cache"]);
步骤三:计算命中率
var readFromDisk = stat["bytes read into cache"];
var alreadyInMem = stat["bytes currently in the cache"];
var hitRatio = 1 - (readFromDisk / (readFromDisk + alreadyInMem));
print("Cache hit ratio : " + (hitRatio * 100).toFixed(2) + "%");
步骤四:给出阈值与动作
- ≥ 95%:健康;
- 90%–95%:观察期,检查是否近期有全表扫描或批量导入;
- < 90%:立即扩容 cacheSizeGB(滚动重启)或优化索引减少全表扫描;
- 若 modified pages evicted 持续 > 1000/s,需调大 eviction_trigger 或 eviction_dirty_target(国内 DBA 常设为 5%→10%)。
拓展思考
- 在 分片集群 场景下,mongos 不缓存数据,必须逐条登录 shard 节点计算命中率;如何批量自动化?
答:通过 ansible + mongo shell 脚本轮询每个 shard,回写 Prometheus Pushgateway,再统一 Grafana 展示。 - 当业务为 时序写入型(物联网),cacheSizeGB 已给 70% 物理内存,命中率仍 < 90%,是否继续加内存?
答:优先采用 “热温冷” 分层:最新小时数据放 MongoDB,历史数据通过 TTL + 自动归档到对象存储;减少缓存污染,而非盲目加内存。 - 面试陷阱:若面试官追问 “为什么 bytes read into cache 会大于物理内存?”
答:该指标为累计值,自实例启动后累加;需取 delta 计算区间命中率,而非绝对值。