Caching

5 concepts · 10 practice questions

Cache-aside, write-through and write-behind

In cache-aside, the most common pattern, the application checks the cache, and on a miss reads the database and fills the cache itself. Write-through writes to the cache and the database together on every write, so the cache stays warm at the cost of slower writes. Write-behind writes to the cache and flushes to the database later, which makes writes fast and risks losing them if the cache fails first. Read-through is cache-aside moved into a library or the cache itself.

def get_product(product_id):
    key = f"product:{product_id}"
    cached = cache.get(key)
    if cached is not None:
        return json.loads(cached)                    # hit
    product = db.fetch_one("SELECT * FROM products WHERE id = %s", product_id)
    cache.set(key, json.dumps(product), ex=300)      # miss: fill, 5 minute TTL
    return product

Also covered

Invalidation and TTLs
Stampede protection
CDN and HTTP caching
Consistency trade-offs

Sign in to read the rest and take the 10-question test.

Sign in to continue