Overview
The block cache is RocksDB’s primary in-memory cache for uncompressed data blocks read from SST files. It’s critical for read performance, reducing disk I/O by caching frequently accessed blocks.Cache Implementations
Fromcache.h:46-47, RocksDB provides two main cache implementations:
LRU Cache
Fromcache.h:207-275, the traditional LRU (Least Recently Used) cache:
HyperClockCache (Recommended)
Fromcache.h:371-476, lock-free cache with better CPU efficiency:
HyperClockCache is now generally recommended over LRUCache for better performance under high concurrency.
- Much improved CPU efficiency under parallel load
- Lock-free implementation reduces contention
- Larger cache shards (less risk of thrashing)
- Only for
BlockBasedTableOptions::block_cache - Not a general-purpose Cache (fixed-size keys expected)
- Requires anonymous mmap support (Linux, Windows)
Configuration Options
Capacity
Fromcache.h:129-132:
Sharding
Fromcache.h:134-138:
Strict Capacity Limit
Fromcache.h:140-145:
true: Insert fails if cache is full and no entries can be evictedfalse: Insert always succeeds, cache may exceed capacity temporarily
Priority Levels
Fromadvanced_cache.h:61-68 and cache.h:224-246:
- HIGH: Index and filter blocks (if
cache_index_and_filter_blocks_with_high_priority) - LOW: Data blocks (default)
- BOTTOM: Blob values
Entry Roles
Fromcache.h:55-88, cache entries are classified by role:
Monitoring by Role
Fromcache.h:101-110:
Advanced Features
Secondary Cache
Fromcache.h:159-161, add a compressed secondary tier:
Tiered Cache
Fromcache.h:518-547, experimental multi-tier caching:
Metadata Charging
Fromcache.h:114-124:
kFullChargeCacheMetadata counts the cache’s internal overhead against capacity for more accurate memory accounting.Memory Allocator
Fromcache.h:147-153, use a custom allocator:
Usage Patterns
Insert
Fromadvanced_cache.h:225-266:
Lookup
Fromadvanced_cache.h:281-295:
Async Lookup
Fromadvanced_cache.h:456-543, for non-blocking reads:
Statistics
Fromstatistics.h:32-95, monitor cache performance:
Cache Management
Runtime Control
Fromadvanced_cache.h:338-356:
Eviction Callback
Fromadvanced_cache.h:545-554:
Best Practices
1. Size Appropriately
2. Use HyperClockCache
3. Cache Index and Filters
4. Monitor Hit Rate
5. Use Secondary Cache for Large Datasets
Troubleshooting
Low Hit Rate
- Increase cache size: More capacity = better hit rate
- Check working set: Cache should hold active working set
- Pin critical blocks: Use high priority for index/filters
- Monitor entry stats: Identify which block types are missing
High Memory Usage
- Enable metadata charging: Use
kFullChargeCacheMetadata - Set strict limit: Prevent cache from exceeding capacity
- Reduce capacity: Trade hit rate for memory
- Use compressed secondary: Offload to compressed tier
Contention (LRU Cache)
- Switch to HyperClockCache: Better for high concurrency
- Increase sharding: Higher
num_shard_bits - Profile mutex wait: Check
DB_MUTEX_WAIT_MICROSstatistic