$npx -y skills add vibeeval/vibecosystem --skill caching-patternsRedis caching strategies, cache invalidation, write-through/write-behind, TTL management, and cache stampede protection.
| 1 | # Caching Patterns |
| 2 | |
| 3 | Redis-based caching strategies for reducing latency and database load. |
| 4 | |
| 5 | ## Cache Key Design |
| 6 | |
| 7 | ```typescript |
| 8 | // Namespace:entity:id format |
| 9 | const CacheKeys = { |
| 10 | market: (id: string) => `market:v1:${id}`, |
| 11 | marketList: (filters: string) => `market:list:${filters}`, |
| 12 | user: (id: string) => `user:v1:${id}`, |
| 13 | userMarkets: (userId: string, page: number) => `user:${userId}:markets:${page}`, |
| 14 | leaderboard: () => 'leaderboard:v1:global' |
| 15 | } |
| 16 | |
| 17 | // Version prefix allows instant cache bust on schema change: |
| 18 | // bump v1 → v2 to invalidate all market keys without scanning |
| 19 | ``` |
| 20 | |
| 21 | ## Cache-Aside (Lazy Loading) |
| 22 | |
| 23 | ```typescript |
| 24 | import Redis from 'ioredis' |
| 25 | |
| 26 | const redis = new Redis(process.env.REDIS_URL!) |
| 27 | const DEFAULT_TTL = 300 // 5 minutes |
| 28 | |
| 29 | async function getOrSet<T>( |
| 30 | key: string, |
| 31 | loader: () => Promise<T>, |
| 32 | ttl = DEFAULT_TTL |
| 33 | ): Promise<T> { |
| 34 | const cached = await redis.get(key) |
| 35 | if (cached) return JSON.parse(cached) as T |
| 36 | |
| 37 | const value = await loader() |
| 38 | await redis.setex(key, ttl, JSON.stringify(value)) |
| 39 | return value |
| 40 | } |
| 41 | |
| 42 | // Usage |
| 43 | async function getMarket(id: string): Promise<Market> { |
| 44 | return getOrSet( |
| 45 | CacheKeys.market(id), |
| 46 | () => db.market.findUniqueOrThrow({ where: { id } }), |
| 47 | 300 |
| 48 | ) |
| 49 | } |
| 50 | ``` |
| 51 | |
| 52 | ## Write-Through Pattern |
| 53 | |
| 54 | ```typescript |
| 55 | // Write to cache AND database together - cache is always fresh |
| 56 | async function updateMarket(id: string, data: UpdateMarketDto): Promise<Market> { |
| 57 | const updated = await db.market.update({ where: { id }, data }) |
| 58 | |
| 59 | // Synchronously update cache so next read is fresh |
| 60 | await redis.setex(CacheKeys.market(id), DEFAULT_TTL, JSON.stringify(updated)) |
| 61 | |
| 62 | return updated |
| 63 | } |
| 64 | |
| 65 | async function deleteMarket(id: string): Promise<void> { |
| 66 | await db.market.delete({ where: { id } }) |
| 67 | await redis.del(CacheKeys.market(id)) |
| 68 | } |
| 69 | ``` |
| 70 | |
| 71 | ## Write-Behind (Write-Back) Pattern |
| 72 | |
| 73 | ```typescript |
| 74 | // Write to cache immediately, flush to DB asynchronously (higher throughput) |
| 75 | // Risk: data loss on crash if queue not durable |
| 76 | |
| 77 | class WriteBehindCache { |
| 78 | private dirtyKeys = new Set<string>() |
| 79 | private flushInterval: NodeJS.Timeout |
| 80 | |
| 81 | constructor(private flushEveryMs = 1000) { |
| 82 | this.flushInterval = setInterval(() => this.flush(), flushEveryMs) |
| 83 | } |
| 84 | |
| 85 | async write(key: string, value: unknown, dbWriter: () => Promise<void>): Promise<void> { |
| 86 | // Instant cache update |
| 87 | await redis.setex(key, DEFAULT_TTL, JSON.stringify(value)) |
| 88 | this.dirtyKeys.add(key) |
| 89 | |
| 90 | // Schedule DB write |
| 91 | dbWriter().catch(err => { |
| 92 | console.error(`Write-behind flush failed for ${key}:`, err) |
| 93 | this.dirtyKeys.add(key) // re-queue |
| 94 | }) |
| 95 | } |
| 96 | |
| 97 | private async flush(): Promise<void> { |
| 98 | // Implementation: drain dirty keys to DB in batch |
| 99 | this.dirtyKeys.clear() |
| 100 | } |
| 101 | |
| 102 | destroy(): void { |
| 103 | clearInterval(this.flushInterval) |
| 104 | } |
| 105 | } |
| 106 | ``` |
| 107 | |
| 108 | ## Cache Stampede Protection |
| 109 | |
| 110 | ```typescript |
| 111 | // Problem: 1000 concurrent requests on cache miss → 1000 DB queries |
| 112 | // Solution: mutex lock - only first request queries DB, rest wait |
| 113 | |
| 114 | import { Mutex } from 'async-mutex' |
| 115 | |
| 116 | const mutexMap = new Map<string, Mutex>() |
| 117 | |
| 118 | function getMutex(key: string): Mutex { |
| 119 | if (!mutexMap.has(key)) { |
| 120 | mutexMap.set(key, new Mutex()) |
| 121 | // Cleanup after 30s to prevent memory leak |
| 122 | setTimeout(() => mutexMap.delete(key), 30_000) |
| 123 | } |
| 124 | return mutexMap.get(key)! |
| 125 | } |
| 126 | |
| 127 | async function getWithMutex<T>( |
| 128 | key: string, |
| 129 | loader: () => Promise<T>, |
| 130 | ttl = DEFAULT_TTL |
| 131 | ): Promise<T> { |
| 132 | const cached = await redis.get(key) |
| 133 | if (cached) return JSON.parse(cached) as T |
| 134 | |
| 135 | const mutex = getMutex(key) |
| 136 | |
| 137 | return mutex.runExclusive(async () => { |
| 138 | // Double-check after acquiring lock |
| 139 | const rechecked = await redis.get(key) |
| 140 | if (rechecked) return JSON.parse(rechecked) as T |
| 141 | |
| 142 | const value = await loader() |
| 143 | await redis.setex(key, ttl, JSON.stringify(value)) |
| 144 | return value |
| 145 | }) |
| 146 | } |
| 147 | |
| 148 | // Probabilistic Early Expiration (alternative, no lock needed) |
| 149 | async function getWithEarlyExpire<T>( |
| 150 | key: string, |
| 151 | loader: () => Promise<T>, |
| 152 | ttl = DEFAULT_TTL, |
| 153 | beta = 1 |
| 154 | ): Promise<T> { |
| 155 | const raw = await redis.get(key) |
| 156 | |
| 157 | if (raw) { |
| 158 | const { value, expires } = JSON.parse(raw) as { value: T; expires: number } |
| 159 | const ttlRemaining = (expires - Date.now()) / 1000 |
| 160 | // Probabilistically re-fetch before expiry |
| 161 | if (ttlRemaining - beta * Math.log(Math.random()) > 0) { |
| 162 | return value |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | const value = await loader() |
| 167 | const payload = { value, expires: Date.now() + ttl * 1000 } |
| 168 | await redis.setex(key, ttl, JSON.stringify(payload)) |
| 169 | return value |
| 170 | } |
| 171 | ``` |
| 172 | |
| 173 | ## Multi-Level Caching (L1 Memory + L2 Redis) |
| 174 | |
| 175 | ```typescript |
| 176 | import LRU from 'lru-cache' |
| 177 | |
| 178 | const l1 = new LRU<string, unknown>({ |
| 179 | max: 500, // max 500 items in memory |
| 180 | ttl: 30_000 // 30 seconds |
| 181 | }) |
| 182 | |
| 183 | async function getMultiLevel<T>( |
| 184 | key: string, |
| 185 | loader: () => Promise<T>, |
| 186 | l2Ttl = DEFAULT_TTL |
| 187 | ): Promise<T> { |
| 188 | // L1: in-process memory |