Skip to main content

Scope a Django cache key to the user and input

2026-11-11 16:36:25.372143+00:00
Scope a Django cache key to the user and input

A cache key such as "account-summary" can serve one user's private result to another. Include the authorization scope and every result-changing input in the key, then decide how permission changes invalidate it.

The cache key incorporates authorization scope, permission revision and result-changing filters.

Build a stable scoped key

This function demonstrates a synthetic account-summary key. The caller must supply a user and workspace that have already passed authorization.

import hashlib
import json

def summary_key(*, user_id, workspace_id, permission_version, filters):
    inputs = {
        "user": str(user_id),
        "workspace": str(workspace_id),
        "permissions": permission_version,
        "filters": filters,
        "schema": 1,
    }
    encoded = json.dumps(
        inputs, sort_keys=True, separators=(",", ":")
    ).encode("utf-8")
    digest = hashlib.sha256(encoded).hexdigest()
    return f"account-summary:{digest}"

key = summary_key(
    user_id=12, workspace_id=3,
    permission_version=7, filters={"status": "open"},
)

Stable JSON serialization prevents dictionary insertion order from creating a different key for the same structured inputs. Normalize semantically equivalent filter values before building the key if the application treats them as identical.

Hashing controls key length. It does not make sensitive inputs anonymous in a legal or security sense, and it does not authorize the request. A cache lookup should not replace the membership check that establishes access to the workspace.

Define a cache-miss policy

Use a sentinel when None is a legitimate cached value so a miss remains distinguishable from a stored null. Set a timeout appropriate to the data and record how updates invalidate existing entries.

Use the same normalization function in readers and invalidators; two incompatible key builders can leave stale data behind. The permission_version value is useful only if the application increments or changes it when access changes. A version field that never changes gives false confidence. Depending on the product, a user-specific permission revision, explicit key deletion or a short retention period may be appropriate.

Test two users with the same filters, one user in two workspaces and the same user before and after a permission revision. Their keys should differ where their allowed results differ. Also test that equivalent filter dictionaries produce the same key.

Avoid caching a whole HTTP response without considering headers, cookies, content negotiation and user-specific fields. This example scopes one application value, which is a smaller contract.

The operational summaries in Nirogidhara provide related context. Django describes the cache API and key versioning; Python documents hashlib.