1.Why caching is needed, and in-memory cache
A cache stores the result of a slow operation so the next request for the same thing skips the work. An in-memory cache keeps that result inside the running process — a dict, or functools.lru_cache — so lookups cost a hash, not a database query or a computation.
Key features
- A cache trades memory (and staleness risk) for avoiding repeated slow work — a database query, an API call, or a CPU-bound computation
- An in-memory cache lives inside the running process — a plain dict, or functools.lru_cache for function results
- In-memory cache is the fastest option (no network hop) but is per-process — a second process or server has its own, empty cache
- A process restart or deploy wipes an in-memory cache entirely — nothing survives it
- lru_cache(maxsize=N) evicts the least-recently-used entry once full, bounding memory automatically
Command
from functools import lru_cache
@lru_cache(maxsize=128)
def slow_square(x):
return x * xA cache saves a slow result in a fast place; an in-memory cache is the fastest kind but lives only in the current process and vanishes on restart.