Cloudflare uses consistent hashing in its Pingora Backend Router to distribute cacheable requests across servers. Supporting weighted servers and different feature combinations required many hash rings, which consumed significant memory.
Kevin Guthrie, principal distributed systems engineer at Cloudflare, Mariia Iurchenko, senior software engineer, Zaidoon Abd Al Hadi, systems engineer, and Ivan Babrou, performance engineer, described in a company blog post how they targeted the pingora-ketama Rust library. They applied probability theory to determine the minimum number of hash points needed.
"Each step down in error margin requires (almost) an order of magnitude increase in the number of hashes per server, so adding more hashes yields less and less improvement," they wrote. The final 90,000 hashes contributed only a 0.7% improvement in distribution error, so the team reduced the total number by 90%.
The team also optimized the Rust data structures, packing hash and server index information into 6 bytes instead of 8, further reducing memory usage.
However, changing the hash ring would redirect cached content, potentially causing a surge in origin traffic. "There was one more problem: changing the hash ring changes where some cacheable requests go. Even if the new ring is better, switching the whole network at once would effectively invalidate almost all cached content. It would turn a memory optimization into an apocalyptic increase in origin traffic," they explained. The new implementation was rolled out gradually alongside the existing ring to limit cache churn.
The work attracted attention online. Hacker News user Teanut commented, "It's fun seeing what little changes at massive scales can do. Good use of math to justify the changes, too."
Cloudflare has undertaken other memory optimization efforts. In August, the company described how its DNS team reduced the memory footprint of its cache through a series of data-structure optimizations.
