Caching is one of the most effective ways to improve API performance. It reduces repeated database queries, lowers server load, and helps applications respond faster.
But there is a problem that developers sometimes overlook while implementing caching: authorization must still be enforced when a response comes from the cache.
Imagine an API that correctly checks permissions before retrieving data from a database. Everything works as expected. Then, caching is introduced to improve performance.
The first user requests a resource, and the backend stores the response in Redis. A second user requests the same resource, and the application retrieves the cached response without properly evaluating the second user's permissions.
The database was never accessed, but the response was still delivered.
This is where caching can become a security problem.
In this article, we will explore how cache-related authorization failures happen, how to design safer cache keys, and how to implement a caching strategy in FastAPI without treating a cache hit as permission to access data.
1. How a Correct API Becomes Insecure After Caching
Consider a multi-tenant application where multiple users work across different production sites.
Some users are administrators. Others are site managers or operators with limited access to certain resources.
An asset API might return the following information:
{
"asset_id": 42,
"name": "Production Machine A",
"site_id": 5,
"maintenance_cost": 85000,
"internal_notes": "Scheduled replacement"
}
The application already has an authorization system that determines which users can access an asset and which fields they are allowed to view.
Now, a developer introduces Redis caching.
The resource is stored using a key such as:
asset:42
The administrator requests the asset, and the response is cached.
Later, an operator requests the same asset. If the backend retrieves the cached response and returns it without applying the operator's permissions, restricted information may be exposed.
The problem is not Redis itself. The problem is how the application uses the cache.
A cache lookup is a data retrieval operation. It should never be treated as an authorization decision.
Even if the original request was authorized, the next request may come from a completely different user with a different permission set.
2. Understand the Difference Between Data Caching and Authorization Caching
Before designing a cache, it is important to understand what exactly is being cached.
There are two different things an application might cache:
Resource data: The actual information retrieved from a database, such as an asset, user, configuration, or production record.
Authorization decisions: The result of determining whether a particular user can perform a particular action on a resource.
These two types of caching have different security implications.
Caching resource data can be useful because the same information may be requested repeatedly. However, authorization should still be evaluated according to the application's security policy.
Caching authorization decisions is also possible, but it introduces a freshness problem. If a user's access is revoked, a cached permission decision might still allow the operation until that cache expires or is invalidated.
For example, consider the following permission changes:
| User | Previous access | Current access |
|---|
| Administrator | Edit | Edit |
| Site Manager | Edit | View |
| Operator | View | Revoked |
If permission decisions are cached without a proper invalidation strategy, the backend might continue using outdated authorization information.
For sensitive operations, permission checks should use an authoritative and sufficiently fresh source.
Caching should improve performance without weakening the application's security boundaries.
3. Design Cache Keys That Respect Security Boundaries
One of the common mistakes in caching is using a key that identifies only the resource.
For example:
cache_key = f"asset:{asset_id}"
This may be sufficient for a resource whose cached representation is identical for every authorized user, but it is not sufficient when the resource or response depends on the tenant, user permissions, or other access restrictions.
Consider a multi-tenant application where two organizations have their own assets.
Even if both organizations have an asset with the same identifier in some legacy system, the backend should never accidentally retrieve information from the wrong tenant.
A better resource cache key includes the tenant boundary:
cache_key = (
f"asset:{tenant_id}:{asset_id}"
)
This helps isolate cached resource data across tenants.
However, tenant isolation alone is not the complete solution.
Two users belonging to the same tenant may still have different permissions. One might be able to view maintenance costs, while another can only view basic asset information.
There are two common approaches:
- Cache canonical resource data and apply authorization-dependent filtering after retrieving it.
- Cache separately filtered responses using a key that accounts for the effective authorization scope and relevant policy version.
For many applications, caching canonical data and applying the current authorization policy on each request is a simpler and safer design.
The cache key should reflect the identity and scope of the cached data, not be used as a substitute for permission enforcement.
4. Implement Safe Caching in FastAPI
Let's implement a simplified FastAPI endpoint that retrieves an asset using Redis while enforcing authorization on every request.
The design will follow four steps:
- Authenticate the user.
- Check whether the user is currently authorized to access the asset.
- Retrieve the resource from Redis or the database.
- Apply field-level permissions before returning the response.
Here is a simplified implementation:
from fastapi import FastAPI, Depends, HTTPException
app = FastAPI()
@app.get("/assets/{asset_id}")
async def get_asset(
asset_id: int,
current_user=Depends(get_current_user)
):
# Check current access before returning cached data.
allowed = await policy.can_access_asset(
user_id=current_user.id,
tenant_id=current_user.tenant_id,
asset_id=asset_id
)
if not allowed:
raise HTTPException(
status_code=403,
detail="Access denied"
)
# Cache resource data within the tenant boundary.
cache_key = (
f"asset:{current_user.tenant_id}:{asset_id}"
)
asset = await redis.get(cache_key)
if asset is None:
asset = await repository.get_asset(
tenant_id=current_user.tenant_id,
asset_id=asset_id
)
if asset is None:
raise HTTPException(
status_code=404,
detail="Asset not found"
)
await redis.set(
cache_key,
serialize(asset),
ex=300
)
# Apply field-level permissions on every request.
return await policy.filter_asset_fields(
user=current_user,
asset=deserialize(asset)
)
The functions get_current_user, policy, repository, redis, serialize, and deserialize represent application components that would need to be implemented.
The important part is the execution order.
The application checks access before returning data from Redis. The cached resource is retrieved within the correct tenant boundary, and the response is filtered using the user's current permissions.
The cache improves data retrieval performance, but it does not determine whether the user is allowed to access the resource.
This separation makes the design easier to reason about and reduces the risk of accidentally bypassing authorization through caching.
5. Handle Permission Changes and Cache Invalidation
Caching introduces another challenge: data and permissions can change after something has already been cached.
For example, a site manager might lose access to a particular production site.
If the application caches fully filtered responses or authorization decisions, the old cache entry may remain valid from a technical perspective even though the user's access has changed.
There are several ways to address this.
Short-lived authorization caches
If authorization decisions are cached, use an appropriate expiration strategy. However, expiration alone does not guarantee immediate revocation.
Permission invalidation
When permissions change, invalidate related cached authorization decisions or response representations.
Policy revisions
Maintain a policy revision or access-control version that changes when relevant permissions are modified. Cache keys for permission-dependent responses can incorporate that revision.
Recheck permissions
For sensitive requests, evaluate permissions against an authoritative source before serving the response.
These strategies can be combined depending on the application's security requirements.
For example, an application might cache resource data for five minutes while evaluating permissions on every request. This allows the resource cache to remain useful even when access permissions change.
The right strategy depends on how sensitive the data is, how frequently permissions change, and how quickly access revocation must take effect.
6. Test the Security of Your Cache
Caching should be tested not only for performance but also for authorization correctness.
A cache can appear to work perfectly while introducing security problems that are difficult to detect during normal development.
Consider testing these scenarios:
- A user with full access retrieves a resource, and a restricted user requests the same resource afterward.
- A user from another tenant requests a resource that has already been cached.
- A user's permissions are revoked while cached data still exists.
- Two users with different field-level permissions request the same resource.
- A permission change occurs while several requests are being processed.
- A cached authorization decision remains available after a role change.
- A response contains sensitive fields that should not be exposed to a particular user.
These tests should verify the actual response, not just whether the cache returned a hit.
For example, an operator should not receive maintenance costs or internal notes simply because an administrator previously requested the same asset.
A useful testing approach is to run the same endpoint against both a cold cache and a warm cache. The authorization result should remain consistent regardless of whether the resource was retrieved from Redis or the database.
That is an important security property of a well-designed caching system.
Final Thoughts
Caching is a performance optimization, but it also changes how data flows through an application.
When implemented carelessly, it can bypass assumptions that were previously enforced by database queries, authorization checks, or application logic.
The safest approach is to treat caching and authorization as separate responsibilities.
Cache resource data within the correct boundaries. Evaluate permissions using the current authorization policy. Apply field-level restrictions before returning the response. And when permissions change, ensure that any cached decisions or filtered representations cannot continue granting access incorrectly.
A cache hit should never be treated as proof that a user is authorized.
Caching should optimize data retrieval, not determine who is allowed to retrieve the data.
That distinction becomes especially important when building multi-tenant SaaS platforms, administrative dashboards, IoT management systems, and applications where different users have different levels of access to the same resources.
A fast API is valuable. A fast API that respects its security boundaries on every request is what matters in production.
Tags: Python, FastAPI, Redis, API Security, Authorization, Backend Development, Software Architecture, Multi-Tenant Applications
Join the conversation! Your thoughts help the community grow.