Кэширование (Caching)

Технология временного хранения данных для сверхбыстрого доступа к ним.

Кэширование работает на всех уровнях современных вычислений: аппаратный уровень (кэш процессора), уровень приложений (in-memory базы данных типа Redis или Memcached), сетевой уровень (CDN для кэширования статики ближе к пользователю) и уровень браузера (сохранение файлов сайтов на диске ПК).

        graph LR
  Center["Кэширование (Caching)"]:::main
  Rel_file_systems["file-systems"]:::related -.-> Center
  click Rel_file_systems "/terms/file-systems"
  Rel_cpu_cache["cpu-cache"]:::related -.-> Center
  click Rel_cpu_cache "/terms/cpu-cache"
  Rel_cache["cache"]:::related -.-> Center
  click Rel_cache "/terms/cache"
  classDef main fill:#7c3aed,stroke:#8b5cf6,stroke-width:2px,color:white,font-weight:bold,rx:5,ry:5;
  classDef pre fill:#0f172a,stroke:#3b82f6,color:#94a3b8,rx:5,ry:5;
  classDef child fill:#0f172a,stroke:#10b981,color:#94a3b8,rx:5,ry:5;
  classDef related fill:#0f172a,stroke:#8b5cf6,stroke-dasharray: 5 5,color:#94a3b8,rx:5,ry:5;
  linkStyle default stroke:#4b5563,stroke-width:2px;

      

🧒 Простыми словами

Представьте, что каждый раз, когда вы хотите позвонить маме, вам нужно идти в другую комнату и искать ее номер в толстом телефонном справочнике. Кэширование — это как записать ее номер на стикер и приклеить на монитор. Стикер маленький, весь справочник туда не влезет, но самый нужный номер всегда под рукой.

🤓 Expert Deep Dive

Аппаратное кэширование (L1/L2/L3) полагается на пространственную и временную локальность. Так как объем кэша сильно ограничен, используются алгоритмы вытеснения (Eviction Policies), такие как LRU (Least Recently Used). Известная цитата гласит, что в программировании есть только две сложные вещи: инвалидация кэша и придумывание названий. Инвалидация (Cache Invalidation) — это сложнейшая задача своевременного удаления устаревших данных из кэша при их изменении в основной базе.

❓ Частые вопросы

Why not just make the cache big enough to hold everything?

Cost and physics. Cache storage (like SRAM inside a CPU or RAM for a database) is extremely fast but very expensive per gigabyte. Primary storage (like hard drives or SSDs) is much cheaper but much slower. Caching provides the best of both worlds.

What does it mean to 'clear your cache'?

When you clear your web browser's cache, you are deleting the temporary files (images, scripts) it saved from websites you visited. This is often necessary if a website updates its design but your browser is stubbornly loading the old, cached version.

What is a 'cache miss'?

A cache miss occurs when a system looks for data in the cache but doesn't find it. It must then fetch the data from the slower primary storage, which takes longer, and then it typically copies that data into the cache for next time.

📚 Источники