BucketCache 的 L1/L2 分层策略如何配置?

解读

在国内 Kylin 生产集群中,HBase 作为 Cube 的存储底座,其读延迟直接决定上层亚秒级查询能否兑现。BucketCache 是 HBase 2.x 之后默认的读缓存实现,支持 堆内(L1)+ 堆外(L2) 两级分层,通过 BucketCache 策略(CombinedBlockCache) 把 INDEX、BLOOM 等小块放 L1,DATA 大块放 L2,实现 GC 压力与命中率双赢。面试官问“如何配置”,既考察参数细节,也考察你对国内机房常见 大内存裸金属、容器限核、SSD+HDD 混部 场景的权衡能力;答得太浅会被追问“为什么不是全堆内”,答得太深又容易陷入源码,失去节奏。

知识点

  1. 分层角色

    • L1:LRUBlockCache,JVM 堆内,默认占 -Xmx 的 0.4,存 INDEX、BLOOM、META。
    • L2:BucketCache,堆外或 SSD 文件,存 DATA Block,容量大、GC 免疫。
  2. 决定分层的阀门

    • hbase.bucketcache.combinedcache.percentage:L1 占 CombinedCache 总空间的百分比,国内 64 G 容器场景下一般设 20%–25%,既保证索引命中率,又把 75% 以上留给大对象。
    • hfile.block.index.cacheonwrite:索引写入时即进 L1,减少首次查询冷启动。
  3. 堆外 vs file 模式

    • hbase.bucketcache.ioengine:
      • offheap:走 JDK DirectByteBuffer,延时最低,但受限于 -XX:MaxDirectMemorySize,需与 -Xmx 分开规划;
      • file:/data1/hbase/bucketcache:把 SSD 盘当缓存,容量可做到百 GB 级,容灾好,但多一次 read syscall;
      • mmap:文件映射,兼顾容量与速度,在 5.10 内核 + NVMe 场景下性能逼近 offheap。
  4. 容量与分桶

    • hbase.bucketcache.size:单个 RegionServer 的 L2 总大小,国内 128 G 内存机器通常给 90 G,留 20 G 给 OS PageCache。
    • hbase.bucketcache.bucket.sizes:默认 4K,8K,16K,32K,64K,128K,256K,512K,若 Kylin 的 cuboid 宽表行较大(>200 K)需追加 1M 桶,避免频繁 split。
  5. 切换验证

    • 打开 hbase.bucketcache.stats.enabled=true,通过 RS 60030 端口 /bucketCache 指标确认 hitRatio>0.95、evictionCount 无突刺;
    • 结合 Kylin 的 Query Metrics 看 95th latency 是否从 1.2 s 降到 0.3 s 以内。

答案

在 hbase-site.xml 中按以下模板配置即可启用 L1/L2 分层:

<!-- 开启 CombinedBlockCache,启用分层 -->
<property>
  <name>hbase.bucketcache.combinedcache.enabled</name>
  <value>true</value>
</property>

<!-- L1 占比 20%,留给索引块 -->
<property>
  <name>hbase.bucketcache.combinedcache.percentage</name>
  <value>0.20</value>
</property>

<!-- L2 使用堆外,容量 90 G -->
<property>
  <name>hbase.bucketcache.ioengine</name>
  <value>offheap</value>
</property>
<property>
  <name>hbase.bucketcache.size</name>
  <value>92160</value>  <!-- 单位 MB -->
</property>

<!-- 调整桶大小,适配 Kylin 宽表 -->
<property>
  <name>hbase.bucketcache.bucket.sizes</name>
  <value>4096,8192,16384,32768,65536,131072,262144,524288,1048576</value>
</property>

同时把 JVM 参数与操作系统对齐:

-Xms32g -Xmx32g
-XX:MaxDirectMemorySize=100g

重启 RegionServer 后,在 60030 端口观察 hitRatio 与 eviction 曲线,确认分层生效且 Kylin 查询延迟稳定 <500 ms,即完成调优。

拓展思考

  1. 如果公司把 HBase 迁到 K8s,容器内存上限 32 G,且 cgroup v2 限制 MaxDirectMemorySize,如何在不改代码的情况下让 L2 仍然拿到 20 G?
    → 可以放弃 offheap,改用 emptyDir + SSD 的 file 模式,把 hbase.bucketcache.ioengine 指向 /k8s-emptydir/bucketcache,并通过 tmpfs-size 限额 保证 QoS。

  2. 当 Kylin 做 实时 Cube(Lambda 架构) 时,Kafka 流式构建会产生大量小的 HFile,L1 容易被打满,出现 index eviction 抖动,如何缓解?
    → 可临时调大 hbase.bucketcache.combinedcache.percentage 到 35%,并开启 hbase.rs.cacheindexonwrite,让索引优先留在 L1;同时调小 hbase.hregion.memstore.flush.size 减少小文件数,从根本上降低 index 块总量。