Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

caching-strategies

БесплатноБез исполняемых скриптовНе проверен

Design multi-tier caching architectures for web applications — cache-aside vs write-through vs write-behind, TTL design, cache invalidation, Redis patterns…

curiositechот curiositech★ 283 звезды на GitHub

Об этом скилле

Caching Strategies

Caching is the most commonly misapplied performance technique. The failure mode is not "cache too little" — it is "cache without an invalidation strategy and then discover the problem in production six months later when users complain about stale data that you cannot explain."

When to Use

✅ Use for:

  • Choosing which caching pattern fits a use case (cache-aside, write-through, write-behind)
  • Designing TTL values for different data freshness requirements
  • Implementing Redis caching patterns: sorted sets, pub/sub invalidation, Lua scripts
  • Configuring Cache-Control headers, ETags, and CDN behavior
  • Preventing cache stampedes via locking, probabilistic early expiry, or background refresh
  • Cache warming strategies for cold-start scenarios
  • Multi-tier cache design (in-memory L1, Redis L2, CDN L3)

❌ NOT for:

  • Database-internal query plan caching (handled by the database)
  • Python functools.lru_cache / JavaScript memoize utilities (pure function memoization)
  • CPU branch prediction or hardware cache tuning
  • Session storage (use dedicated session skill)

Which Caching Pattern?

flowchart TD
    Q1{Who writes to cache?} --> WA[Application writes]
    Q1 --> WC[Cache writes automatically]
    WA --> Q2{When does the cache get populated?}
    Q2 -->|On read miss| CA[Cache-Aside\n'Lazy loading']
    Q2 -->|On every write| WT[Write-Through\n'Eager write']
    WC --> Q3{Sync or async write-back?}
    Q3 -->|Sync — write completes when cache updates| WT
    Q3 -->|Async — write returns fast, flush later| WB[Write-Behind\n'Write-back']
    CA --> N1{Is stale data OK\nfor a short period?}
    N1 -->|Yes| CA_USE[Use cache-aside\nwith TTL expiry]
    N1 -->|No| INVAL[Add explicit invalidation\nor use write-through]
    WT --> NOTE2[Good for read-heavy data\nthat changes infrequently]
    WB --> NOTE3[Good for write-heavy workloads\nRisk: data loss on crash]

Multi-Tier Cache Architecture

flowchart LR
    USER[User Request] --> CDN{CDN / Edge Cache\nL3 — 100ms+ saved}
    CDN -->|Cache hit| RESP[Response]
    CDN -->|Cache miss| LB[Load Balancer]
    LB --> APP[App Server]
    APP --> L1{In-Process Cache\nL1 — ~0ms}
    L1 -->|Hit| APP
    L1 -->|Miss| REDIS{Redis\nL2 — 1-5ms}
    REDIS -->|Hit| APP
    REDIS -->|Miss| DB[(Database\n10-100ms)]
    DB --> REDIS
    REDIS --> APP
    APP --> L1
    APP --> CDN
    APP --> RESP
Tier Technology Latency Capacity Shared?
L1: In-process Node.js Map, Python dict, LRU-cache ~0ms Small (MB) No — per instance
L2: Distributed Redis, Memcached 1-5ms Large (GB) Yes — all instances
L3: Edge/CDN Cloudflare, Fastly, CloudFront 10-100ms Massive Yes — globally

Rule: Data mutates in one place first. Invalidation flows outward: DB → Redis → CDN. Never skip tiers in invalidation.


Cache-Aside Pattern (Most Common)

Application manages cache explicitly. On read: check cache, if miss fetch from DB, populate cache, return. On write: update DB, delete cache entry.

class UserCache {
  private redis: Redis;
  private readonly TTL_SECONDS = 300; // 5 minutes

  async getUser(userId: string): Promise<User> {
    const key = `user:${userId}`;

    // 1. Check cache
    const cached = await this.redis.get(key);
    if (cached) return JSON.parse(cached);

    // 2. Cache miss — fetch from source
    const user = await db.users.findById(userId);
    if (!user) throw new NotFoundError('User', userId);

    // 3. Populate cache
    await this.redis.setex(key, this.TTL_SECONDS, JSON.stringify(user));

    return user;
  }

  async updateUser(userId: string, data: Partial<User>): Promise<User> {
    const user = await db.users.update(userId, data);

    // 4. Invalidate — delete, don't update
    // Updating in cache risks race conditions; let the next read repopulate
    await this.redis.del(`user:${userId}`);

    return user;
  }
}

When invalidation deletes vs overwrites: Delete is almost always correct. Overwriting in cache after a write creates a race: another request may have fetched the old value between your DB write and your cache write. Delete forces the next reader to fetch fresh.


Write-Through Pattern

Every write goes to cache and DB synchronously. Cache is always populated. Good for data that is written once and read many times.

async function createProduct(data: CreateProductInput): Promise<Product> {
  // Write to DB first (source of truth)
  const product = await db.products.create(data);

  // Immediately populate cache — no future cache miss for this product
  const key = `product:${product.id}`;
  await redis.setex(key, 3600, JSON.stringify(product));

  // Also invalidate list caches that include this product
  await redis.del('products:list:*'); // pattern delete via SCAN, see redis-patterns.md

  return product;
}

Trade-off: Higher write latency (two writes per operation

Полный SKILL.md на GitHub

Установить caching-strategies в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Read
Write
Edit
Grep
Glob

Вложенные файлы

.claude-plugin/plugin.jsonreferences/http-caching.mdreferences/redis-patterns.md

FAQ

Что делает скилл caching-strategies?

Design multi-tier caching architectures for web applications — cache-aside vs write-through vs write-behind, TTL design, cache invalidation, Redis patterns, CDN configuration, browser caching, and stampede prevention. Use when choosing a caching pattern, designing cache invalidation strategies, implementing Redis caching, configuring Cache-Control headers, or preventing cache stampedes. Activate on "cache invalidation", "cache-aside", "write-through", "TTL", "Redis cache", "CDN caching", "cache stampede", "stale data", "browser cache". NOT for database query caching within an ORM, memoization of pure functions, or CPU-level caching.

Как установить скилл caching-strategies?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл caching-strategies запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить caching-strategies с