Backend Development 14 min read

Cache Usage Techniques and Design Solutions: Benefits, Costs, Update Strategies, Granularity, and Optimizations

This article provides a comprehensive guide to cache usage, covering its performance benefits and costs, various update strategies, granularity control, and detailed optimizations for issues such as penetration, avalanche, hot key reconstruction, and distributed batch operations.

Top Architect
Top Architect
Top Architect
Cache Usage Techniques and Design Solutions: Benefits, Costs, Update Strategies, Granularity, and Optimizations

Cache can effectively accelerate application read/write speed and reduce backend load, making it essential for daily development. The article introduces cache usage techniques and design solutions, including benefit and cost analysis, update strategy selection, granularity control, and optimizations for penetration, avalanche, and hot key reconstruction.

1)缓存的收益和成本分析

左侧为客户端直接调用存储层的架构,右侧为典型的缓存层+存储层架构。

收益:

加速读写:缓存全内存,提升读写性能,优化用户体验。

降低后端负载:减少访问量和复杂计算,减轻后端压力。

成本:

数据不一致性:缓存层与存储层存在时间窗口的不一致。

代码维护成本:需处理缓存层和存储层的逻辑。

运维成本:如 Redis Cluster 增加运维复杂度。

使用场景:

开销大的复杂计算(如 MySQL 大量联表、分组计算)。

加速请求响应,即使查询本身很快,也可使用缓存提升并发。

2)缓存更新策略

缓存数据与真实数据存在时间窗口,需要策略更新。

LRU/LFU/FIFO 剔除 :当缓存使用量超过上限时的剔除策略,例如 Redis 的 maxmemory-policy。

超时剔除 :为缓存数据设置过期时间,过期后自动删除并重新从存储层获取。

主动更新 :数据更新后立即通知缓存更新,可使用消息系统。

建议:

低一致性业务使用最大内存和淘汰策略。

高一致性业务结合超时剔除和主动更新。

3)缓存粒度控制

需在数据通用性、空间占用、代码维护性之间取舍,常用组合为 Redis 作为缓存层、MySQL 作为存储层。

4)穿透优化

缓存穿透指查询不存在的数据,缓存层和存储层都不命中。解决方案包括缓存空对象和布隆过滤器拦截。

5)无底洞优化

在分布式缓存中,节点增多不一定提升性能,需优化批量操作。常见方案包括串行命令、串行 IO、并行 IO、hash_tag 实现。

6)雪崩优化

缓存雪崩指缓存失效导致大量请求直接冲击存储层。预防措施包括保证缓存高可用、后端限流降级、提前演练。

7)热点key重建优化

热点 key 在失效瞬间大量线程重建导致后端压力。解决方案包括互斥锁和永远不过期两种策略。

互斥锁实现示例(使用 Redis 的 setnx 命令):

永远不过期策略通过逻辑过期时间和后台线程重建缓存,确保数据一致性。

backenddistributed systemsperformanceRediscachingCache Strategies
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.