Reference library

Caching & Redis

Cache-aside, TTL, invalidation, hot keys, and in-memory lookup patterns at scale.

3 matches
Caching & Redis easy

How to Invalidate a Cache in Python with lru_cache

This code demonstrates how to clear the cache of an @lru_cache decorated function in Python using cache_clear(), showing the effect on cached results.

lru_cache cache-invalidation functools
Python
from functools import lru_cache
import time

@lru_cache(maxsize=None)
def expensive_operation(key):
    return f"Computed value for {key} at {time.time():.6f}"

def invalidate_cache():
    expensive_operation.cache_clear()

if __name__ == "__main__":
    print(expensive_operation("alpha"))
    print(expensive_operatio…
13 0 Open
Caching & Redis easy

How to Use lru_cache in Python for Cache-on-Miss Population

Demonstrates lru_cache to automatically populate cache on a miss and serve subsequent calls from cache, with cache info stats.

lru_cache caching functools
Python
from functools import lru_cache

@lru_cache(maxsize=None)
def fetch_user(user_id):
    """Simulates a slow database fetch."""
    print(f"Cache miss: fetching user {user_id} from database")
    return {"id": user_id, "name": f"User {user_id}"}

if __name__ == "__main__":
    user = fetch_user(1)
    print(f"First call…
15 0 Open
Caching & Redis easy

How to memoize a function in Python with lru_cache

Use functools.lru_cache to memoize a recursive Fibonacci function, caching results for a fixed number of calls to avoid repeated computation.

lru_cache memoization functools
Python
from functools import lru_cache

@lru_cache(maxsize=128)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

if __name__ == "__main__":
    for i in range(10):
        print(f"fib({i}) = {fibonacci(i)}")
    print(f"Cache info: {fibonacci.cache_info()}")
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Caching & Redis — Python code examples

What you will find here

This page collects caching & redis snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.