NOSSLETTER.techLIVE
back to archive

zset: sample ZRANDMEMBER large positive counts in one btree walk

Language: C+141 -44performance
concepts demonstrated
Binary treesReservoir sampling (probabilistic selection)Memory optimization by avoiding temporary allocationsPerformance benchmarking
The Issue & Context

Before this PR, requesting a large but partial random sample from a btree sorted set caused Redis to copy all members into a temporary dictionary and randomly delete entries until the desired count remained, leading to high memory use and slow responses for counts between one-third and full size.

Root Cause Analysis

The existing implementation for btree zsets in the range size/3 < count < size relied on a costly approach that duplicated the entire set into a temporary dict and then randomly removed entries, incurring per-member allocations and decoding overhead, because it lacked an efficient streaming sampling method during tree traversal.

Solution Strategy & Architectural Pattern

This PR introduces a single descending B+ tree walk with selection sampling in zrandmemberRandBelow(), where each member is kept with probability proportional to the ratio of needed samples to remaining elements, avoiding temporary dicts and decoding skipped members. This preserves unbiased sampling and returns results in descending score order, replacing the previous copy-and-delete approach for large counts on btree zsets.

Key Takeaway for Contributors

When sampling large subsets from sorted data structures, streaming selection sampling during a single traversal can drastically reduce memory allocations and decoding overhead compared to copying and pruning, especially in performance-critical code paths.