authx-extra package provides a Redis-based caching system designed to work seamlessly with FastAPI applications.
How HTTP caching works
HTTP caching occurs when the browser stores local copies of web resources for faster retrieval the next time the resource is required. As your application serves resources, it can attach cache headers to the response specifying the desired cache behavior. When an item is fully cached, the browser may choose to not contact the server at all and simply use its own cached copy.HTTP cache headers
There are two primary cache headers that control caching behavior:Cache-Control
TheCache-Control header is the most important header to set as it effectively “switches on” caching in the browser. With this header in place and set with a value that enables caching, the browser will cache the file for as long as specified. Without this header, the browser will re-request the file on each subsequent request.
Expires
When accompanying theCache-Control header, Expires simply sets a date from which the cached resource should no longer be considered valid. From this date forward, the browser will request a fresh copy of the resource.
For more details about HTTP caching, see the MDN HTTP Caching Guide.
Initialize the cache
First, set up the Redis connection and initialize the HTTP cache:The
tz attribute is important when the cache decorator relies on the expire_end_of_day and expire_end_of_week attributes to expire cache keys based on timezone-aware dates.Cache your endpoints
Use the@cache decorator to cache endpoint responses. The ttl_in_seconds parameter sets the cache expiration time:
Build dynamic cache keys
While you can explicitly pass keys to thekey attribute, you can also build keys dynamically based on parameters received by the controller method:
user. The key becomes b.logged_in.112358 if user.id returns 112358.
Invalidate cached data
Use the@invalidate_cache decorator to clear cached data when it becomes stale:
Invalidate multiple keys
You can invalidate multiple cache keys in a single call:Dynamic TTL with callables
You can compute the TTL dynamically using a callable function:The
ttl_func is always assumed to be an async method.Cache non-controller methods
HTTP cache works exactly the same way with regular methods outside of FastAPI controllers:Next steps
Prometheus metrics
Add monitoring to track cache performance
Profiling
Profile your application to optimize cache usage