Skip to content

Authentication Caching — Caching Auth Decisions for Performance

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Authentication Caching. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Authentication caching reduces latency and load on auth services while maintaining security guarantees.

// Multi-level auth cache
class AuthCache {
  constructor() {
    this.localCache = new Map();
    this.redisCache = redisClient;
    this.ttl = {
      tokenValidation: 60,  // 1 minute
      userProfile: 300,     // 5 minutes
      permissions: 60       // 1 minute
    };
  }

  async getTokenValidation(token) {
    const hash = crypto.createHash('sha256').update(token).digest('hex');
    const cacheKey = `auth:token:${hash}`;

    // L1: Local in-memory cache (fastest)
    const local = this.localCache.get(cacheKey);
    if (local && local.expires > Date.now()) return local.data;

    // L2: Redis cache
    const redis = await this.redisCache.get(cacheKey);
    if (redis) {
      const parsed = JSON.parse(redis);
      this.localCache.set(cacheKey, { data: parsed, expires: Date.now() + 30000 });
      return parsed;
    }

    // Miss: validate at auth service
    const result = await authService.validateToken(token);
    this.redisCache.setex(cacheKey, this.ttl.tokenValidation, JSON.stringify(result));
    this.localCache.set(cacheKey, { data: result, expires: Date.now() + 30000 });

    return result;
  }

  invalidateUser(userId) {
    const pattern = `auth:user:${userId}:*`;
    // Cannot scan in production Redis - use tagged keys
    this.redisCache.del(`auth:user:${userId}:permissions`);
    this.redisCache.del(`auth:user:${userId}:profile`);
    this.localCache.clear();
  }
}

// Usage in middleware
app.use('/api', async (req, res, next) => {
  const token = extractToken(req);
  const validation = await authCache.getTokenValidation(token);
  if (!validation.valid) return res.status(401).json({ error: 'Invalid token' });
  req.user = validation.user;
  next();
});

Auth caching must balance cache TTL with security requirements for timely revocation detection.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro