Caching in Python
Caching, is a concept that was gifted to software world from the hardware world, A temporary storage for fast and easy access of data.
Caching, is a concept that was gifted to software world from the hardware world. A cache is a temporary storage area that stores the used items for easy access. To put it in layman’s terms, it is the chair we all have.
This blog covers the basics of
- What are Caches?
- Caching Operations
- Cache Eviction Policies
- Implementation of Cache Eviction Policies
- Distributed Caching
- Caching In Python: functools, cachetools and Flask-Caching
Conventional Caches
In the world of computer science, Caches are the hardware components that store the result of computation for easy and fast access. The major factor that contributes to the speed is its memory size and its location. The memory size of the cache is way less than an RAM. This reduces the number of scans to retrieve data. Caches are located closer to the consumer (CPU) hence the less latency.
Caching Operations
There are two broad types of caches operation. Cache such as Browser caches, server caches, Proxy Caches, Hardware caches works under the principle of read and write caches.
When dealing with caches we always have a huge chunk of memory which is time consuming to read and write to, DB, hard disk, etc., Cache is a piece of software/hardware sitting on top of it making the job faster.
Read Cache
A read cache is a storage that stores the accessed items. Every time the client requests data from storage, the request hits the cache associated with the storage.
- If the requested data is available on the cache, then it is a cache hit.
- if not it is a Cache miss.
- Now when accessing a data from cache some other process changes the data at this point you need to reload the cache with the newly changed data this it is a Cache invalidation
Write Cache
Write caches as the name suggests enables fast writes. Imagine a write-heavy system and we all know that writing to a DB is costly. Caches come handy and handle the DB write load which is later updated to the DB in batches. It is important to notice that, the data between the DB and the cache should always be synchronized. There are 3 ways one can implement a write cache.
- Write Through
- Write Back
- Write Around
Write Through
The write to the DB happens through the cache. Every time a new data is written in the cache it gets updated in the DB.
Advantages - There won’t be a mismatch of data between the cache and the storage
Disadvantage - Both the cache and the storage needs to be updated creating an overhead instead of increasing the performance
Write Back
Write back is when the cache asynchronously updates the values to the DB at set intervals.
This method swaps the advantage and disadvantage of Write through. Though writing to a cache is faster of Data loss and inconsistency
Write Around
Write the data directly to the storage and load the cache only when the data is read.
- Advantages
- A cache is not overloaded with data that is not read immediately after a write
- Reduces the latency of the write-through method
- Disadvantages
- Reading recently written data will cause a cache miss and is not suitable for such use-cases.
Cache Eviction Policies
Caches make the reads and write fast. Then it would only make sense to read and write all data to and from caches instead of using DBs. But, remember the speed comes only because caches are small. Larger the cache, longer it will take to search through it.
So it is important that we optimize with space. Once a cache is full, We can make space for new data only by removing the ones are already in the cache. Again, it cannot be a guessing game, we need to maximize the utilization to optimize the output.
The algorithms used to arrive at a decision of which data needs to be discarded from a cache is a cache eviction policy
- LRU - Least Recently Used
- LFU - Least Frequently Used
- MRU - Most Recently Used
- FIFO - First In First Out
LRU - Least Recently Used
As the name suggest when a cache runs out of space remove the least recently used element. It is simple and easy to implement and sounds fair but for caching frequency of usage has more weight than when it was last accessed which brings us to the next algorithm.
LFU - Least Frequently Used
LFU takes both the age and frequency of data into account. But the problem here is frequently used data stagnates in the cache for a long time
MRU - Most Recently Used
Why on earth will someone use an MRU algorithm after talking about the frequency of usage? Won’t we always re-read the data we just read? Not necessarily. Imaging the image gallery app, the images of an album gets cached and loaded when you swipe right. What about going back to the previous photo? Yes, the probability of that happening is less.
FIFO - First In First Out
When caches start working like queues, you will have an FIFO cache. This fits well for cases involving pipelines of data sequentially read and processed.
LRU Implementation
Caches are basically a hash table. Every data that goes inside it is hashed and stored making it accessible at O(1).
Now how do we kick out the least recently used item, we by far only have a hash function and it’s data. We need to store the order of access in some fashion.
One thing we can do is have an array where we enter the element as and when it is accessed. But calculating frequency in this approach becomes an overkill. We can’t go for another Hash table it is not an access problem.
A doubly linked list might fit the purpose. Add an item to the linked list every time it is accessed and maintain it’s a reference in a hash table enabling us to access it at O(1).
When the element is already present, remove it from its current position and add it to the end of the linked list.
Where to Place the Caches?
The closer the caches are to its consumer faster it is. Which might implicitly mean to place caches along with the webserver in case of a web application. But there are a couple of problems
- When a server goes down, we lose all the data associated with the server’s cache
- When there is a need to increase the size of the cache it would invade the memory allocated for the server.
The most viable solution is to maintain a cache outside the server. Though it incorporates additional latency, it is worth for the reliability of caches.
Distributed Caching is the concept of hosting a cache outside the server and scaling it independently.
When to Implement Caches?
Finding the technologies to implement caches is the easiest of all steps. Caches promises high speed APIs and it might feel stupid not to incorporate them, but if you do it for wrong reasons, it just adds additional overhead to the system. So before implementing caches make sure
- The hit to your data store is high
- You have done everything you can to improve the speed at DB level.
- You have learnt and researched on various caching methodologies and systems and found what fits your purpose.
Implementation In Python
To understand caching we need to understand the data we are dealing with. In the original version of this post I used a MongoDB schema of User and Event collections. For this rewrite I wanted every snippet to run on your laptop without a database, so the “database” below is a dictionary, and where I need it to feel slow I add a 10 ms time.sleep(). The caching code doesn’t care which one it wraps.
Everything on this page was run on Python 3.13.18 (x86_64 Linux, 2 cores, Intel Xeon @ 2.30GHz). The @functools.cache decorator needs Python 3.9 or newer, and the current Flask-Caching (2.5.x) needs 3.11 or newer.
Python’s built-in caching: functools
The standard library gives you two decorators. @functools.lru_cache keeps the maxsize most recent calls, with a default of 128. @functools.cache (added in Python 3.9) is the same thing with maxsize=None. The docs describe it as a “simple lightweight unbounded function cache” that’s “smaller and faster than @lru_cache with a size limit” because it never has to evict anything.
from functools import cache, lru_cache
@lru_cache(maxsize=2)
def square(n):
print(f" computing {n}")
return n * n
for n in (1, 2, 1, 3, 1): # maxsize=2, so 3 evicts the least recently used entry
print(n, "->", square(n))
print(square.cache_info())
square.cache_clear()
print(square.cache_info())
@cache # same as lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80))
print(fib.cache_info())
computing 1
1 -> 1
computing 2
2 -> 4
1 -> 1
computing 3
3 -> 9
1 -> 1
CacheInfo(hits=2, misses=3, maxsize=2, currsize=2)
CacheInfo(hits=0, misses=0, maxsize=2, currsize=0)
23416728348467685
CacheInfo(hits=78, misses=81, maxsize=None, currsize=81)
Read the 1 -> 1 lines against the “computing” lines. Asking for 3 pushed out 2, the least recently used entry, because 1 had just been touched. That’s the LRU policy from earlier in this post, in about three lines of code. cache_info() is how you check it’s working: hits=2, misses=3 means five calls and only three real computations. cache_clear() is the manual invalidation button.
Two things to remember about functools caching:
-
Arguments must be hashable. The cache is a dictionary keyed on your arguments, so a list can’t be one. This is the first error everybody hits:
@lru_cache def total(items): return sum(items) print(total((1, 2, 3))) try: total([1, 2, 3]) except TypeError as e: print("TypeError:", e)6 TypeError: unhashable type: 'list'Pass a tuple instead (
total(tuple(my_list))), or cache a function that takes an ID and loads the list itself. -
There’s no expiry. An entry stays until it’s evicted or you call
cache_clear(). The docs also note that the cache keeps references to your arguments and return values, and that it isn’t meant for functions with side effects or impure ones liketime()orrandom(). That’s the “cache timeout is not implicit” disadvantage from the list I wrote in 2022, and it’s what the next section fixes.
Expiry with cachetools
cachetools (pip install cachetools) gives you cache objects with other policies, including TTLCache, which expires entries after a time-to-live in seconds, and an @cached decorator that works with any of them. Passing info=True gives the wrapped function a cache_info() just like lru_cache.
import time
from cachetools import TTLCache, cached
calls = 0
@cached(cache=TTLCache(maxsize=100, ttl=1), info=True)
def get_user(uid):
global calls
calls += 1
return {"id": uid, "name": f"user-{uid}"}
get_user(1); get_user(1)
print("calls after 2 lookups:", calls)
time.sleep(1.2) # let the entry expire
get_user(1)
print("calls after waiting past the ttl:", calls)
print(get_user.cache_info())
calls after 2 lookups: 1
calls after waiting past the ttl: 2
CacheInfo(hits=1, misses=2, maxsize=100, currsize=1)
The second lookup was served from the cache. After the one-second ttl the entry had expired, so the third lookup called the function again. One more thing from the docs: the lock argument of @cached only guards access to the cache object. If several threads share the function, the function itself still has to be thread-safe.
How much faster is it, really?
I timed these with timeit (best of five repeats), on the machine described above. The 10 ms lookup is a time.sleep(0.01) standing in for a database query.
import time, timeit
from functools import cache, lru_cache
from cachetools import TTLCache, cached
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
@cache
def fib_cached(n):
return n if n < 2 else fib_cached(n - 1) + fib_cached(n - 2)
def slow_lookup(uid):
time.sleep(0.01) # pretend this is a 10 ms DB query
return {"id": uid}
@lru_cache(maxsize=128)
def slow_lookup_lru(uid):
return slow_lookup(uid)
@cached(cache=TTLCache(maxsize=128, ttl=60))
def slow_lookup_ttl(uid):
return slow_lookup(uid)
def best(stmt, number, repeat=5, **g):
return min(timeit.repeat(stmt, number=number, repeat=repeat, globals=g)) / number
fib_cached(25) # warm
slow_lookup_lru(1); slow_lookup_ttl(1)
rows = [
("fib(25), no cache", best("fib(25)", 5, fib=fib)),
("fib(25), @cache, warm", best("fib_cached(25)", 100000, fib_cached=fib_cached)),
("10 ms lookup, no cache", best("slow_lookup(1)", 50, repeat=3, slow_lookup=slow_lookup)),
("10 ms lookup, @lru_cache hit", best("f(1)", 200000, f=slow_lookup_lru)),
("10 ms lookup, TTLCache hit", best("f(1)", 200000, f=slow_lookup_ttl)),
]
for name, secs in rows:
print(f"{name:32s} {secs*1e6:12.3f} us")
| Call | No cache | Cache hit |
|---|---|---|
fib(25), @cache | 6,329 µs | 0.024 µs |
10 ms lookup, @lru_cache(maxsize=128) | 10,115 µs | 0.027 µs |
10 ms lookup, cachetools TTLCache | 10,115 µs | 0.357 µs |
Two things to read out of that table. A hit is a dictionary lookup, which is why it’s so cheap compared with real work. And the TTLCache hit is about 13 times slower than the lru_cache hit (0.357 µs against 0.027 µs), because it also has to check whether the entry has expired. That’s a fair price for expiry, but it’s a price. I ran the whole script twice and the numbers moved by only a few percent.
Caching isn’t free for cheap functions. Here is the list-versus-tuple gotcha again, but measured. Summing a list of 1,000 integers is already quick, and to use lru_cache we have to turn the list into a hashable tuple on every call, and Python then hashes all 1,000 elements to build the key.
sum over 1,000 ints | Time per call |
|---|---|
sum(list), no cache | 4.4 µs |
tuple(list) then cached sum | 3.3 µs |
cached sum, tuple built once up front | 2.1 µs |
The cache wins, but only by a little, because hashing the key costs about as much as the work we’re trying to skip. Caching pays off when the work behind the call is slow (a query, an HTTP call, a recursive computation). It isn’t worth it for something that already takes microseconds. That’s the “when to implement caches” advice from earlier in this post, with numbers behind it.
Caching In Python Flask
functools caches live inside one Python process. That’s fine for a script, but a web app usually runs several worker processes, and each would have its own private cache. To share a cache between them, or to keep it in Redis or Memcached, you want a cache extension.
The old post used Flask-Cache for this. That project’s last release on PyPI is version 0.13.1 from April 2014, so don’t start anything new with it. Its fork, Flask-Caching, is the one that’s maintained (the README describes it as “a fork of the Flask-Cache extension”). Install it with pip install Flask-Caching.
I ran this minimal app with the in-memory SimpleCache, using Flask’s test client so there’s no server to start:
import time
from flask import Flask, jsonify
from flask_caching import Cache
config = {
"CACHE_TYPE": "SimpleCache", # in-memory; swap for "RedisCache" in production
"CACHE_DEFAULT_TIMEOUT": 30,
}
app = Flask(__name__)
app.config.from_mapping(config)
cache = Cache(app)
USERS = {"1": "Ada", "2": "Grace"}
db_hits = 0
def read_user(uid):
global db_hits
db_hits += 1 # count how often we really reach the "DB"
return {"id": uid, "name": USERS[uid]}
@app.route("/user/<uid>")
@cache.cached(timeout=2) # whole response, keyed on the request path
def get_user(uid):
try:
return jsonify(read_user(uid))
except KeyError:
return jsonify({"status": "error", "message": f"no user {uid}"}), 404
if __name__ == "__main__":
client = app.test_client()
for _ in range(3):
print(client.get("/user/1").get_json())
print("db hits after 3 requests:", db_hits)
time.sleep(2.1)
client.get("/user/1")
print("db hits after the timeout expired:", db_hits)
{'id': '1', 'name': 'Ada'}
{'id': '1', 'name': 'Ada'}
{'id': '1', 'name': 'Ada'}
db hits after 3 requests: 1
db hits after the timeout expired: 2
Three requests, one trip to the “database”. After the two-second timeout the next request goes through again. Note that the decorator order matters: @app.route goes on the outside and @cache.cached sits directly above the function.
Moving it to Redis. The config is the only thing that changes. The Flask-Caching configuration docs list the backends by class name (SimpleCache, FileSystemCache, RedisCache, MemcachedCache and more), so the lowercase 'redis' and 'memcache' values from the old Flask-Cache snippet are gone:
config = {
"CACHE_TYPE": "RedisCache",
"CACHE_REDIS_URL": "redis://localhost:6379/0",
"CACHE_DEFAULT_TIMEOUT": 30, # seconds; the default is 300
}
I ran the same app against a local Redis 7.0.15 server (started on port 6390, with "CACHE_REDIS_URL": "redis://localhost:6390/0"). The output was identical, and redis-cli keys '*' afterwards showed one key, flask_cache_view//user/1. The flask_cache_ part is the default CACHE_KEY_PREFIX. If you set CACHE_REDIS_URL, it overrides the separate host and port settings.
Caching the function instead of the view. @cache.cached stores the whole HTTP response. When you’d rather cache a function’s result for specific arguments, there’s @cache.memoize, which takes the arguments into account in the cache key, and cache.delete_memoized to invalidate it. That’s the “cache invalidation” step from the top of this post:
@cache.memoize(timeout=60)
def read_user(uid):
...
USERS["1"] = "Ada Lovelace" # the row changes in the database
read_user("1") # still returns the old name from the cache
cache.delete_memoized(read_user, "1") # invalidate
read_user("1") # now returns "Ada Lovelace"
When I ran this, the second call returned {'id': '1', 'name': 'Ada'} (stale), and the call after delete_memoized returned {'id': '1', 'name': 'Ada Lovelace'} and bumped the database hit count from 1 to 2.
With that, we have covered what caches are, when to use one, and how to implement it in plain Python (functools, cachetools) and in Flask.