0Pricing
Spring Security 6 & JWT Authentication · Урок

Кэширование проверки токенов для масштабирования

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

«Кэширование проверки токенов для масштабирования» — бесплатный урок Spring Security 6 & JWT Authentication на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Security 6 & JWT Authentication, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.

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

The Cost of Validation

Every request to a JWT-protected API runs signature verification and claim checks. At thousands of requests per second, repeated work, especially fetching public keys, becomes a bottleneck.

What Is Safe to Cache

Not everything should be cached. Safe to cache:

  • The public keys (JWKS) used to verify signatures
  • Expensive parsed metadata

Risky: caching a final allow decision for too long can let a revoked token slip through.

Caching the JWKS

Fetching the JWKS endpoint on every request is wasteful. Cache the key set and refresh it periodically or when an unknown kid appears.

// pseudo: refresh keys at most once per 10 minutes
if (now - keysFetchedAt > 600000) {
  keys = fetchJwks();
  keysFetchedAt = now;
}

Refresh on Unknown kid

If a token carries a kid not in the cache, the signing key may have rotated. Force a one-time refresh before rejecting, so legitimate new tokens are accepted promptly.

let key = keys[kid];
if (!key) { keys = fetchJwks(); key = keys[kid]; }
if (!key) reject('unknown key');

Local Verification Beats Introspection

Self-contained JWTs can be verified locally with the cached public key, avoiding a network call per request. This is far faster than remote token introspection.

Short-Lived Decision Cache

You may cache the parsed claims for a token's lifetime keyed by the token hash, but the cache entry's TTL must never exceed the token's own exp.

ttl = Math.min(claims.exp - now, MAX_CACHE_TTL);
cache.set(hash(token), claims, ttl);

The Revocation Tradeoff

Caching a decision means a revoked token might still be accepted until the cache entry expires. Keep this TTL short (seconds) when you support revocation, so the stale window stays tiny.

Spring's Built-In JWKS Cache

Spring's NimbusJwtDecoder already caches the JWKS internally and handles refresh, so for many apps you get caching for free just by configuring the JWK set URI.

JwtDecoder decoder = NimbusJwtDecoder
    .withJwkSetUri(jwksUri)
    .build();

Measuring the Win

Always measure before and after. Track average validation latency and JWKS fetch count. Caching that does not move your metrics adds complexity for no gain.

Cache Stampede Protection

When a cached key expires, many requests may refresh at once. Use a single-flight lock so only one thread fetches the new JWKS while others wait.

if (refreshing) await refreshPromise;
else { refreshing = true; refreshPromise = fetchJwks(); }

Distributed Caches

In a multi-instance deployment, a shared cache like Redis avoids each node refetching keys independently and keeps a consistent view of revocation state.

Quick Check

Test your understanding of caching token validation.

Recap

You learned to scale JWT validation with caching:

  • Cache the JWKS public keys; refresh on unknown kid
  • Local verification avoids per-request network calls
  • Decision caches must respect the token's exp and stay short when revocation matters
  • Use single-flight refresh and distributed caches at scale

Smart caching cuts latency while keeping security intact.

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

Урок «Кэширование проверки токенов для масштабирования» бесплатный?

Да — полный текст урока «Кэширование проверки токенов для масштабирования» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Security 6 & JWT Authentication, подпишись на CoddyKit PRO. Курс Spring Security 6 & JWT Authentication содержит 4 уроков всего.

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

Узнайте, как снизить нагрузку от проверки JWT при высоком трафике, кэшируя ключи JWKS и результаты проверки без ущерба для безопасности Ты практикуешь Spring Security 6 & JWT Authentication с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Spring Security 6 & JWT Authentication?

Предыдущий опыт не требуется. Spring Security 6 & JWT Authentication на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Кэширование проверки токенов для масштабирования»?

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

Можно ли писать и запускать код в этом уроке Spring Security 6 & JWT Authentication?

Да. Каждый урок Spring Security 6 & JWT Authentication включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

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

  1. JWT с коротким сроком действия и цикл обновления
  2. Чёрные и белые списки JWT
  3. Особенности производительности JWT
  4. Кэширование проверки токенов для масштабирования
← Назад к Spring Security 6 & JWT Authentication