Back to articles
Caching Strategies: When, Where, and How to Cache

Caching Strategies: When, Where, and How to Cache

via Dev.to WebdevYoung Gao

Your API hits the database on every request. 90% of those queries return the same data. You are paying for the same computation over and over. The Cache Hierarchy Browser Cache -> CDN -> Application Cache (Redis) -> Database Cache -> Database Each layer catches requests before they hit the next. The closer to the user, the faster the response. Cache-Aside (Lazy Loading) The most common pattern. Check cache first. On miss, query database and populate cache: async function getUser ( id : string ): Promise < User > { const cached = await redis . get ( `user: ${ id } ` ); if ( cached ) return JSON . parse ( cached ); const user = await db . query ( " SELECT * FROM users WHERE id = $1 " , [ id ]); await redis . setex ( `user: ${ id } ` , 3600 , JSON . stringify ( user )); return user ; } Write-Through vs Write-Behind Write-through : Write to cache and database simultaneously. Consistent but slower writes. Write-behind : Write to cache, asynchronously sync to database. Fast writes but risk d

Continue reading on Dev.to Webdev

Opens in a new tab

Read Full Article
6 views

Related Articles