0Pricing
Caching Strategies: Redis + CDN + Edge Computing · Урок

Проектирование ключей кэша и объединение запросов

Узнайте, как проектировать эффективные ключи кэша на разных уровнях и как объединение запросов предотвращает лавинообразную нагрузку на исходный сервер.

«Проектирование ключей кэша и объединение запросов» — бесплатный урок Caching Strategies: Redis + CDN + Edge Computing на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Caching Strategies: Redis + CDN + Edge Computing, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Caching Strategies: Redis + CDN + Edge Computing содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

What Is a Cache Key?

A cache key uniquely identifies a cached entry. When a request arrives, the cache computes its key and looks for a matching stored response.

  • Same key equals a cache hit
  • Different key equals a separate entry (or a miss)
  • Poor key design causes low hit ratios or wrong responses

Default Cache Keys

By default many caches key on the full URL including host and path. But query strings, headers, and cookies can also be part of the key, which dramatically affects how often you get hits.

Normalizing Query Strings

Tracking parameters like utm_source create needless cache fragmentation. Strip or ignore irrelevant query params so equivalent requests share one entry.

cache_key = url_without_params(request.url) + "?" + only_keep(request.query, ["id", "page"])

Varying on Headers

The Vary header tells caches to store separate copies per header value. Useful for content negotiation but dangerous if overused: Vary: User-Agent can explode into thousands of entries.

Vary: Accept-Encoding

Cookies and Cache Keys

Cookies often make responses uncacheable because each user has a unique cookie. Strip cookies for static assets, and only include the specific cookies that truly change the response.

Device and Geo Variants

Sometimes you intentionally vary by device class or country. Add a small, controlled dimension to the key (like a normalized device type) rather than the raw header to keep cardinality low.

  • Good: mobile vs desktop
  • Bad: full User-Agent string

The Thundering Herd Problem

When a popular item expires, many requests can simultaneously miss and hammer the origin at once. This thundering herd can overwhelm a backend during peak traffic.

Request Coalescing

Request coalescing (also called collapsed forwarding) makes the cache send only one request to the origin for a given key while other concurrent requests wait for that single fetch.

proxy_cache_lock on;
proxy_cache_lock_timeout 5s;

Stale-While-Revalidate

To smooth expiry, serve slightly stale content while a background refresh runs. This avoids both the herd and a latency spike for users.

Cache-Control: max-age=60, stale-while-revalidate=120

Multi-Layer Key Consistency

In a Redis plus CDN plus edge stack, keep cache keys consistent across layers so they agree on what is the same object. Mismatched keys cause duplicate storage and confusing invalidation.

Designing Keys: Checklist

A solid cache key strategy:

  • Strip tracking and irrelevant params
  • Vary only on headers that change the response
  • Avoid keying on raw cookies or User-Agent
  • Enable coalescing for hot keys
  • Use stale-while-revalidate to hide refresh latency

Quick Check

Test your understanding of cache keys and coalescing.

Recap

You learned how cache key design controls hit ratios: normalizing query strings, using Vary carefully, and avoiding high-cardinality dimensions. You also saw how request coalescing and stale-while-revalidate protect the origin from thundering-herd spikes across a multi-layer cache.

Часто задаваемые вопросы

Урок «Проектирование ключей кэша и объединение запросов» бесплатный?

Да — полный текст урока «Проектирование ключей кэша и объединение запросов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Caching Strategies: Redis + CDN + Edge Computing, подпишись на CoddyKit PRO. Курс Caching Strategies: Redis + CDN + Edge Computing содержит 4 уроков всего.

Чему я научусь в уроке «Проектирование ключей кэша и объединение запросов»?

Узнайте, как проектировать эффективные ключи кэша на разных уровнях и как объединение запросов предотвращает лавинообразную нагрузку на исходный сервер. Ты практикуешь Caching Strategies: Redis + CDN + Edge Computing с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Caching Strategies: Redis + CDN + Edge Computing?

Предыдущий опыт не требуется. Caching Strategies: Redis + CDN + Edge Computing на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Проектирование ключей кэша и объединение запросов»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Caching Strategies: Redis + CDN + Edge Computing?

Да. Каждый урок Caching Strategies: Redis + CDN + Edge Computing включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Объединение Redis и CDN
  2. Многоуровневая стратегия кэширования
  3. Согласованность данных между кэшами
  4. Проектирование ключей кэша и объединение запросов
← Назад к Caching Strategies: Redis + CDN + Edge Computing