We are designing an authorization cache for a multi-tenant system.
Requirements:
- Cache should store authorization data (like user permissions, roles, etc.) for each tenant.
- We need to handle invalidation (when permissions change, we must invalidate the cache for that tenant/user).
- Prevent cache stampede (many requests hitting the database when a cache key expires).
- Ensure correctness (we must not serve stale or incorrect authorization data).
Let's break down:
-
Cache Key Design:
- We have multi-tenant, so we must include tenant ID in the key.
- Also, we might cache per user (or per user-role, etc.). Let's assume we cache by user within a tenant.
- Example key:
auth:tenant:{tenant_id}:user:{user_id}
-
Invalidation:
- When an authorization change occurs (e.g., role assigned, permission revoked) for a user in a tenant, we must invalidate that user's cache.
- We might have multiple users per tenant, so we cannot invalidate the entire tenant cache if only one user changed (unless we want to, but that might be inefficient).
- We need a way to invalidate specific keys. We can delete the key from the cache when we know there's a change.
-
Stampede Prevention:
- When a cache key expires, multiple requests might try to load the data from the database at the same time.
- We can use a locking mechanism (like a mutex) so that only one request rebuilds the cache and others wait and then use the rebuilt cache.
- Alternatively, we can use a "soft" expiration (keep the expired value for a short time and let one request rebuild) and then update.
-
Correctness:
- We must ensure that the cache is invalidated properly and that we don't serve data that is no longer valid.
- Also, we must handle the case where the cache is being rebuilt and multiple requests are waiting. They must get the same fresh data.
Implementation Ideas:
-
We can use a distributed cache (like Redis) that supports atomic operations and expirations.
-
For stampede prevention, we can use a lock (with a timeout) around the cache rebuild. Steps:
a. Try to get the cache. If found and not expired, return.
b. If not found or expired, try to acquire a lock for that key (with a short timeout, e.g., 10 seconds).
c. If lock acquired, then rebuild the cache (from DB) and set it with an expiration, then release the lock.
d. If lock not acquired, wait for a short random time and then retry getting the cache (up to a few times).
-
Alternatively, we can use a "stale-while-revalidate" approach: if the cache is expired, we return the stale value (if available) and asynchronously update the cache. But this might not be acceptable for authorization if we must have the latest. So we must be cautious.
-
Since authorization is critical, we might not want to serve stale data. So we must block until the cache is rebuilt? But that could cause delays. Alternatively, we can rebuild the cache in the request that first notices the expiration, and then let subsequent requests wait for the rebuild? That's the lock approach.
-
Another idea: use a double-checked locking pattern with a version number? Not sure.
-
We also have to consider that the cache rebuild might fail (DB down, etc.). We should handle that and maybe return an error or use a stale cache for a short time? But again, correctness is key.
-
Invalidation: we must delete the key when we know there's a change. But note: if we are using the lock-based rebuild, and at the same time an invalidation happens, we must be careful.
Let's think about the sequence:
Request1: cache miss (expired) -> acquires lock -> rebuilds and sets cache.
Meanwhile, an invalidation event occurs for the same key -> the event tries to delete the key, but the key is being rebuilt?
We must ensure that the invalidation event either:
- Waits for the lock to be released and then deletes the key? But the lock is held by Request1 and then released after setting the new cache.
- Or, the invalidation event could set a flag in the cache (like a version) and then the rebuild would check? That might be complex.
Alternatively, we can design the invalidation to be idempotent and safe:
When we invalidate, we delete the key. But if the key is being rebuilt (lock held), then after the rebuild the new cache is set and then the invalidation might delete it again? That would be bad if the invalidation happened before the rebuild.
We need a way to ensure that if an invalidation happens during a rebuild, the rebuild does not set a stale value.
Idea: when rebuilding, we can check if the key still exists? But if the invalidation deleted it, then we are rebuilding a new one and then set it. That's okay because we are rebuilding from the current DB state. But what if the invalidation happened because of a change that we are about to read? Then the rebuild will read the updated DB and set the correct cache. So that's okay.
However, the problem is: what if the invalidation happens after the rebuild but before the lock is released? Then the invalidation deletes the key, and then the lock is released. Then the next request will rebuild again. That's acceptable, but we might do extra work.
But note: the invalidation event should be triggered after the change is committed in the DB. So if the rebuild reads the DB after the change, it will get the new data. Then the invalidation deletes the key? That doesn't make sense because we just set the new correct data. We don't want to delete the new correct data.
So the invalidation should not delete the key if it was set after the change? How can we know?
Alternatively, we can change the invalidation mechanism: instead of deleting the key, we can set a version or a timestamp in a separate key? Or use a cache pattern that includes a version.
Another approach: use a write-through cache? But we are reading more than writing.
Let's re-think:
We have two operations:
- Read: get authorization for a user (from cache or DB)
- Write: change authorization (which must invalidate the cache for that user)
We want to avoid the following race:
Time0: Request1: cache miss (expired) -> acquires lock -> reads DB (at time1) -> sets cache at time2.
Time0: Change happens (invalidates) at time3 (between time1 and time2?).
If the change happens after the DB read (time1) but before setting the cache (time2), then the cache set at time2 will be stale (because it was read before the change). Then the invalidation event (which happens at time3) might delete the key, but if the invalidation happens after the cache set, then we are okay? Not exactly.
Actually, if the change happens after the DB read (time1) and then the invalidation event deletes the key (at time3) and then the cache set (at time2) happens, then the key is set with stale data and then immediately deleted? That's okay because the next read will rebuild with fresh data.
But what if the invalidation event happens between time1 and time2? Then the invalidation deletes the key (which was already expired, so maybe not present) and then the cache set (at time2) sets the stale data? That's bad because we set stale data and then the invalidation event did not delete it because it happened before the set?
Wait, the invalidation event at time3 happens after time1 and before time2. The invalidation event deletes the key (which was expired and not present in cache? or was it present? It was expired so might have been already deleted by the cache? We don't know).
Actually, the cache key was expired, so Request1 found it expired and decided to rebuild. The invalidation event deletes the key (which is already expired, so maybe it's not in the cache? But if the cache is Redis, deleting a non-existing key is safe). Then Request1 sets the key with the stale data (because the DB read was before the change). Then the cache now has stale data.
So we have a problem: the rebuild happened with stale data because the change occurred after the DB read but before the cache set, and the invalidation event did not prevent the stale data from being set because the key was already expired and the invalidation deleted it (but it was already expired).
How to solve?
We need to ensure that when we rebuild the cache, we are reading the DB at a time that is after any invalidation that might have happened. But that's not possible because we don't know about the invalidation until it happens.
Alternatively, we can use a version number or a timestamp that is included in the cache key?
Idea: when we invalidate, we increment a version for that tenant (or for that user). Then the cache key includes that version. So:
key = `auth:tenant:{tenant_id}:user:{user_id}:v{version}`
Then, when we invalidate, we increment the version and delete the old key? Actually, we don't need to delete the old key because the key changes. But then we have to store the version somewhere? We can store the version in a separate key per user? That would be two keys per user.
Alternatively, we can use a tenant-wide version? Then we would have to invalidate all users in the tenant when one user changes? That might be too broad.
We want per-user invalidation, so we need a per-user version.
How about:
We store two keys:
- The cache key for the user's authorization (with a version in the key, but we don't want to have to know the version when reading?).
Actually, when we read, we need to know which version to use. So we can have:
- A key that stores the current version for the user: `auth:tenant:{tenant_id}:user:{user_id}:version`
- Then the cache key is: `auth:tenant:{tenant_id}:user:{user_id}:v{version}`
Steps for read:
1. Get the current version for the user (from a separate key, which we can cache too?).
2. Then try to get the cache with that version.
3. If not found, then rebuild:
a. Acquire lock (for that user?).
b. Read the current version again (to make sure it hasn't changed while we were waiting for the lock?).
c. Read the authorization data from DB.
d. Set the cache with the current version.
e. Release lock.
Invalidation:
When a change occurs for a user:
a. Increment the version for that user (set a new version number).
b. We don't delete the old cache keys because they are now with an old version and won't be accessed again.
This way, if a rebuild happens with an old version (because the version changed after we read the version but before we set the cache) then the cache we set will be with an old version and then the next read will use the new version and rebuild again. But that's acceptable because it might cause an extra rebuild, but we avoid serving stale data? Not exactly.
Let's see:
Request1: reads version=1, then acquires lock, then while waiting, the version is incremented to 2.
Then Request1 reads the DB (with version=1 in mind, but the DB change already happened so the data is actually for version=2? No, the data in the DB is the current state. The version is just a number we increment on change. So reading the DB after the change will get the current state (which corresponds to version=2). But Request1 is going to set the cache with version=1? That would be wrong.
So we must read the version again after acquiring the lock, and then use that version to form the key.
Revised read:
Step1: Get the current version (v1) for the user.
Step2: Try to get cache with key using v1.
Step3: If miss, then acquire lock (for the user).
Step4: After acquiring lock, get the current version again (v2). If v2 != v1, then we know that the version changed while we were waiting. Then we should:
- Release the lock.
- Retry the whole process (go to step1) because the cache we were about to rebuild is for the old version.
Step5: If v2 == v1, then we read the DB (which now has the state for version v1? Actually, the version is just a counter. The DB state is the current state. The version is incremented on every change. So if we read the DB now, we get the state that corresponds to version v2 (which is v1). But note: the change that incremented the version also changed the DB. So if the version is v1, then the DB state is for v1. But wait, the version is incremented on change, so if we have version v1, that means the last change was when we set version to v1. So reading the DB now should give the state for v1.
However, there is a race: what if after we read the version (v1) and before we acquire the lock, a change happens (version becomes v2) and then we acquire the lock? Then we read the version again (v2) and then we read the DB (which is now for v2). But we are going to set the cache with version v2? That's correct.
But note: the initial version we read (v1) might be old. So we must use the version we read after the lock.
So the steps:
function get_auth(tenant_id, user_id):
version = get_version(tenant_id, user_id) // from a fast cache, but we can also read from the same cache system?
key = make_key(tenant_id, user_id, version)
data = cache.get(key)
if data is not None:
return data
// cache miss
lock = acquire_lock(tenant_id, user_id) // lock per user
try:
// Double check: after acquiring lock, check version again
current_version = get_version(tenant_id, user_id)
if current_version != version:
// version changed, so the cache we were about to rebuild is for old version.
// We must retry? But note: the current_version might have a cache set by someone else?
// We can try to get the cache again with the new version.
data = cache.get(make_key(tenant_id, user_id, current_version))
if data is not None:
return data
else:
// still miss, so we need to rebuild with current_version
version = current_version
// and then proceed to rebuild (without releasing the lock)
// Now version is the current version and we have the lock.
// Read from DB (with the current version? but the version is just a number, we read the current state)
data = read_from_db(tenant_id, user_id)
// Set the cache with the current version
cache.set(make_key(tenant_id, user_id, version), data, expiration)
return data
finally:
release_lock(lock)
This seems to handle the version change.
But note: the get_version must be fast. We can cache the version? But then we have the same problem for the version key? We can set a long expiration for the version key? Or we can store the version in the same cache with a different key pattern.
We can store the version in a key: `auth:tenant:{tenant_id}:user:{user_id}:version` and set it without expiration? But then if we update the version, we set it to the new number. And when we read, we get the current version.
However, if we cache the version, we might have the same stampede problem for the version key? But the version key is just a number and we update it on every change. We can set the version key with a long expiration? But then if the version key expires, we might get an old version? That would be bad.
Alternatively, we can store the version in the same cache as the data? But then we don't have a separate key.
Another idea: we can use a cache that supports atomic increments? Then we can have a per-user version counter in Redis that we increment on invalidation.
Steps for invalidation:
When a change occurs for user X in tenant Y:
new_version = redis.incr(`auth:tenant:{tenant_id}:user:{user_id}:version`)
// We don't delete the old cache keys because they are with old versions and won't be accessed.
Then, when reading:
version = redis.get(`auth:tenant:{tenant_id}:user:{user_id}:version`)
if version is None:
// first time? Then set version=0 and then proceed to rebuild? But we need to set the version first?
// We can do: if the version key doesn't exist, we set it to 0 and then proceed.
But note: the version key must exist. We can initialize it when the user is first created.
However, the version key might expire? We don't want it to expire. So we set it without expiration? Then we never delete it? That's okay, it's just a number.
But then we have a key for every user that ever existed? That might be a lot. We can set a long expiration? But if it expires, then we lose the version and we might get the wrong cache.
Alternatively, we can store the version in the same key as the cache? But then we cannot change the version without deleting the cache?
Let me think of another approach: we can use a cache pattern with a "generation" number that is stored in the cache value? Then we don't need a separate version key.
But then we have to read the cache to know the version? That's circular.
So the separate version key seems necessary.
We can set the version key with a very long expiration (like a year) and then we never have to worry about it expiring? But if we have millions of users, that's millions of keys. But Redis can handle that? It depends.
Alternatively, we can use a hash in Redis: for each tenant, we have a hash that maps user_id to version? Then we have one key per tenant. Then we can store:
key: `auth:tenant:{tenant_id}:versions` -> hash field: user_id -> version
Then when we invalidate, we hincrby on that hash. And when reading, we hget.
This reduces the number of keys.
But then we have to update the hash on every invalidation, and read the hash on every cache miss. That's acceptable.
So:
Version storage:
key: `auth:tenant:{tenant_id}:versions` (a Redis hash)
field: user_id, value: version (integer)
Cache key: `auth:tenant:{tenant_id}:user:{user_id}:v{version}`
Steps for read:
version = redis.hget(`auth:tenant:{tenant_id}:versions`, user_id)
if version is None:
// first time? Then we need to initialize the version for this user?
// We can set it to 0? But then we have to be careful because multiple processes might try to initialize.
// We can use a lock for initializing? Or we can use a set with nx?
// Actually, we can do: if the field doesn't exist, we set it to 0 and then proceed? But we need to do it atomically.
Alternatively, we can have a separate initialization step when a user is first created. But we might have existing users.
We can do:
version = redis.hget(`auth:tenant:{tenant_id}:versions`, user_id)
if version is None:
// Use a lock to initialize?
lock = acquire_lock(`init_version:tenant:{tenant_id}:user:{user_id}`)
try:
version = redis.hget(`auth:tenant:{tenant_id}:versions`, user_id)
if version is None:
version = 0
redis.hset(`auth:tenant:{tenant_id}:versions`, user_id, version)
finally:
release_lock(lock)
Then we proceed with the version.
But note: the version hash key is for a tenant, and we are updating it on every invalidation. That might cause a hotspot if many invalidations for the same tenant? But the hash is per tenant, so updates to different users in the same tenant are on the same key? That might be a problem.
Alternatively, we can have a separate key per user for the version? Then we have:
key: `auth:tenant:{tenant_id}:user:{user_id}:version`
And we set it with a long expiration? But then we have many keys.
Given that we are already having a cache key per user, having an additional key per user might be acceptable? But if we have millions of users, that's millions of keys.
We can try to keep the version in the same cache key? But then we cannot change the version without changing the key.
Given the trade-offs, I think the hash per tenant is acceptable because:
- We have one key per tenant for versions.
- We update it on every invalidation (which is not too frequent?).
- We read it on every cache miss (which is more frequent).
But if we have a lot of tenants, that's one key per tenant. And if we have a lot of invalidations for the same tenant, we are updating the same key. That might be a bottleneck.
Alternatively, we can use a different pattern: we can store the version in the cache value? Then we don't need a separate version key. But then we have to read the cache to get the version? That's circular.
Let me think of a different approach: we can use a cache that supports tagging? Then we can invalidate by tag? But then we have to tag by user? And then we invalidate the tag for that user? That's similar to having a key per user.
Given the complexity, maybe we stick with the per-user version key? But then we have two keys per user: one for the version and one for the data. And we have to set the version key with a long expiration? But if the version key expires, then we might get an old version? We can set the version key without expiration? Then we accumulate keys.
Alternatively, we can store the version in the cache value and also store a timestamp? Then when we read, we check the timestamp? But then we have to read the cache to know if it's fresh? That doesn't help.
After careful thought, the version hash per tenant seems the best because:
- We have one key per tenant for versions.
- We can set the version hash to have no expiration? Or we can set it to expire after a long time? But then we lose the versions for old users? That's okay because if the version key is missing, we treat it as version 0? But then if we have a cache key for that user with an old version, we might use it? That would be bad.
We must ensure that the version key exists for every user that has a cache key. So we must initialize the version when we first cache the user. And we must not let the version key expire.
So we set the version hash key without expiration? Then we never delete it? But when a user is deleted, we can remove the field from the hash? Or leave it? It's just a number, so leaving it is okay.
However, if we have a lot of users, the hash can become large. But Redis hashes are efficient up to a point.
Alternatively, we can use a separate key per user for the version and set it with a long expiration (like 1 year) and then we don't have a huge hash. But then we have many keys.
Given that we are already storing the cache per user (which is the big data), the version key is small. So having two keys per user might be acceptable.
Let me decide:
Option 1: Per-tenant version hash.
Pros: one key per tenant.
Cons: the hash can become large, and updates to the same tenant are on the same key (possible contention).
Option 2: Per-user version key.
Pros: no large hash, updates are on different keys for different users (less contention).
Cons: more keys.
I think for multi-tenant, we might have many users per tenant, so the hash for a tenant can have many fields. But Redis hashes are implemented as hash tables and can handle many fields. However, if we have a very active tenant with many invalidations, we are updating the same hash key, which might cause contention.
But note: the version update is just an increment, which is atomic in Redis. So it's safe. But if we have many processes trying to update the same hash key, it might be a bottleneck.
Alternatively, we can use a separate key per user for the version and then we don't have that bottleneck.
Given that, I choose per-user version key.
So:
Version key: `auth:tenant:{tenant_id}:user:{user_id}:version` (with no expiration? or long expiration? We want it to persist as long as the user exists.)
How do we handle user deletion? We can delete the version key when the user is deleted? But if we don't, it's just a small key.
We can set the version key with an expiration? But then we might lose the version and then we might get an old cache? So we don't set expiration.
Steps:
Read:
version_key = `auth:tenant:{tenant_id}:user:{user_id}:version`
version = redis.get(version_key)
if version is None:
// first time? Initialize to 0? But we need to do it atomically.
// Use a lock for this user?
lock = acquire_lock(`init_version:{tenant_id}:{user_id}`)
try:
version = redis.get(version_key)
if version is None:
version = 0
redis.set(version_key, version) // no expiration
finally:
release_lock(lock)
Then proceed with the cache key as before.
Invalidation:
new_version = redis.incr(version_key)
Now, the cache key is `auth:tenant:{tenant_id}:user:{user_id}:v{version}`.
When we invalidate, we increment the version and then we don't delete the old cache keys. They become orphaned. We can have a background job to clean up old cache keys? Or we can set a short expiration on the cache keys? Then they will expire naturally.
We set the cache key with an expiration (like 5 minutes). Then even if we don't delete them, they will expire. And because we change the version, we will not access the old ones.
So the cache keys are temporary and will expire.
Now, the stampede prevention lock:
We need a lock per user (for the cache rebuild). We can use the same key for the lock? But we already have a version key. We can use a separate lock key: `lock:auth:tenant:{tenant_id}:user:{user_id}`.
Steps for read (with lock and version):
function get_auth(tenant_id, user_id):
version_key = ...
version = redis.get(version_key)
if version is None:
// initialize version (with lock)
cache_key = make_key(tenant_id, user_id, version)
data = redis.get(cache_key)
if data is not None:
return data
// cache miss
lock_key = `lock:auth:tenant:{tenant_id}:user:{user_id}`
lock = acquire_lock(lock_key, timeout=10) // timeout for the lock, in case the rebuild fails
try:
// After acquiring the lock, check the version again? Because the version might have changed while we were waiting for the lock.
current_version = redis.get(version_key)
if current_version != version:
// The version changed, so the cache we were about to rebuild is for an old version.
// Try to get the cache with the new version.
new_cache_key = make_key(tenant_id, user_id, current_version)
data = redis.get(new_cache_key)
if data is not None:
return data
else:
// Still missing, so we need to rebuild with the current_version.
version = current_version
cache_key = new_cache_key
// Now we have the lock and the version is current.
data = read_from_db(tenant_id, user_id)
redis.set(cache_key, data, expiration=300) // 5 minutes
return data
finally:
release_lock(lock)
This should handle:
- Multiple requests for the same user: only one will rebuild, others will wait and then get the rebuilt cache.
- Version change during the process: if the version changes after we first read the version but before we acquire the lock, then after acquiring the lock we check the version again and if it changed, we try to get the new cache. If the new cache is already set by someone else (who rebuilt with the new version) then we return it. Otherwise, we rebuild with the new version.
But note: what if the version changes after we acquire the lock and before we read the version again? Then we read the new version and rebuild with the new version. That's correct.
However, there is a gap: between reading the version (first time) and acquiring the lock, the version might change. Then we acquire the lock and read the version again and see the change. Then we try to get the new cache. But what if the new cache is being rebuilt by someone else? Then we might wait for the lock? But we already hold the lock?
Actually, we are holding the lock, so no one else is rebuilding. So if the version changed and the new cache is not set, then we must rebuild with the new version.
But note: the version change (invalidation) might have happened after the old cache was set? Then the new version might have a cache set by the invalidation? No, the invalidation only increments the version and does not set the cache. So the new version's cache is likely not set. So we will rebuild.
This seems correct.
Now, what about the initialization of the version key? We have a lock for that too. We use a different lock key for initializing the version? Yes, we used `init_version:{tenant_id}:{user_id}`.
But note: the version key and the cache key are independent.
Also, we must handle the case where the version key is deleted? We assume it's not deleted until the user is deleted.
Correctness:
- We are using a version to ensure that we never serve a cache with an old version.
- We are using a lock to prevent stampede.
However, there is a subtlety: what if the rebuild fails (DB error)? Then we release the lock and the request returns an error? And the cache is not set. Then the next request will try again. That's acceptable.
But what if the rebuild takes a long time? The lock has a timeout (10 seconds). If the rebuild takes longer, then the lock might be released by Redis (if we set an expiration on the lock) and then another request can acquire the lock and rebuild? That might cause two rebuilds. But that's acceptable because we are using the version to avoid setting stale data?
Actually, if the rebuild takes longer than the lock timeout, then the lock is released and another request can acquire the lock and rebuild. Then the first request might set the cache after the second request already set it? Then we have two rebuilds and two sets? But the second one might set the cache with the same version (if the version didn't change) and then the first one sets again? That's a race.
We must ensure that the lock is held until the cache is set. So the lock timeout must be longer than the maximum expected rebuild time. We can set the lock timeout to, say, 30 seconds and make sure the rebuild doesn't take that long.
Alternatively, we can use a lock that is automatically released when the process finishes? We can use a lock that we release explicitly and set a timeout in case we crash. So we set the lock with an expiration (like 30 seconds) and then we release it when done. If we crash, the lock will be released after 30 seconds.
So we set the lock key with an expiration of 30 seconds and then release it when done.
Implementation of acquire_lock and release_lock:
acquire_lock(lock_key, timeout=30):
// Use SET with NX and EX
result = redis.set(lock_key, "1", ex=timeout, nx=True)
return result // True if acquired, False otherwise
release_lock(lock_key):
// We must only release if we own the lock? But we are the one who set it? We can use a simple del? But if the lock timed out and then we try to release, we might delete someone else's lock?
// We can use a Lua script to check the value? But if we are the one who set it, we know the value? We set it to "1". But what if the lock was set by someone else and then expired? Then the key might not exist or might be set to "1" by someone else?
Actually, we can use a atomic release: we delete the key only if it exists and the value is the one we set? But we don't have a unique value.
Alternatively, we can use a random token:
token = random_string()
redis.set(lock_key, token, ex=timeout, nx=True)
Then release:
script = """
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
"""
redis.eval(script, 1, lock_key, token)
But then we have to store the token.
Alternatively, we can use the Redlock algorithm? But that's for distributed locks.
Given that we are in a single Redis instance, we can use the simple SET NX with expiration and then delete without checking? That's unsafe because if the lock timed out and then we delete, we might delete a lock that was reacquired by someone else.
So we must use a token.
Alternatively, we can use the version change to break the lock? Not really.
So we use a token for the lock.
Steps for lock:
token = generate_random_string()
acquired = redis.set(lock_key, token, ex=lock_timeout, nx=True)
if acquired:
return token
else:
return None
release_lock(lock_key, token):
use Lua script to delete only if the value matches.
Now, we have to store the token in the request context.
Alternatively, we can use the existing Redis lock libraries.
But for simplicity, we can assume we have a lock implementation that uses a token.
Now, what about the version key initialization lock? We can use the same pattern.
Summary:
Data structures:
Version key: `auth:tenant:{tenant_id}:user:{user_id}:version` (string, integer, no expiration)
Cache key: `auth:tenant:{tenant_id}:user:{user_id}:v{version}` (string, with expiration, e.g., 300 seconds)
Lock key: `lock:auth:tenant:{tenant_id}:user:{user_id}` (string, with expiration, e.g., 30 seconds)
Steps for get_auth(tenant_id, user_id):
version_key = ...
lock_key = ...
// Get or initialize version
version = redis.get(version_key)
if version is None:
// Initialize with a lock
init_lock_key = `init_lock:auth:tenant:{tenant_id}:user:{user_id}`
token = acquire_lock(init_lock_key, timeout=10)
if token is None:
// wait and retry? or fail? We can wait a bit and then retry getting the version?
// But we don't want to block too long. We can do:
sleep(random(10, 50) ms)
version = redis.get(version_key)
if version is None:
// fail? or try again? We can try a few times?
// Alternatively, we can set the version with a lock that we hold? But we are already in a lock for the cache?
// We can do: if we cannot get the init lock, then we try to get the version again? But if the version is still None, then we fail?
// We can set the version with a default? But we need to be careful.
Actually, we can do:
for i in range(3):
version = redis.get(version_key)
if version is not None:
break
token = acquire_lock(init_lock_key, timeout=10)
if token is not None:
try:
version = redis.get(version_key)
if version is None:
version = 0
redis.set(version_key, version)
break
finally:
release_lock(init_lock_key, token)
else:
sleep(0.01 * (2**i)) // exponential backoff
if version is None:
// We tried and failed, maybe throw an exception?
else:
try:
version = redis.get(version_key)
if version is None:
version = 0
redis.set(version_key, version)
finally:
release_lock(init_lock_key, token)
// Now we have version.
cache_key = make_key(tenant_id, user_id, version)
data = redis.get(cache_key)
if data is not None:
return data
// Cache miss: acquire lock for rebuilding
token = acquire_lock(lock_key, timeout=30)
if token is None:
// Wait and retry? We can do a short sleep and then retry getting the cache?
// But note: another request might be rebuilding. We can wait for the cache to be set?
// We can do:
for i in range(5):
sleep(0.01 * (2**i))
data = redis.get(cache_key)
if data is not None:
return data
// After retries, still miss? Then we try to acquire the lock again? Or fail?
// We can try to acquire the lock again? But we might be in a stampede?
// Alternatively, we can wait until the lock is released? We can do a blocking wait?
// But we don't want to wait too long.
// Let's try to acquire the lock again? But we might be in a situation where the lock is held by a long rebuild? Then we wait again.
// We can do:
token = acquire_lock(lock_key, timeout=30)
if token is None:
// Give up and fail? Or wait more?
// We can wait for the cache to appear? But if the rebuild fails, then we might wait forever.
// We can set a maximum wait time.
// Alternatively, we can return an error if we cannot get the lock after a few tries.
// But note: the lock might be held by a request that is rebuilding. We don't want to overload the system.
// We can do:
wait_time = 0
while wait_time < 1000: // 1 second max wait?
token = acquire_lock(lock_key, timeout=30)
if token is not None:
break
sleep(0.01)
wait_time += 0.01
if token is None:
// failed to acquire lock, return error or try to get the cache one more time?
data = redis.get(cache_key)
if data is not None:
return data
else:
throw new Exception("Could not acquire lock and cache missing")
// Now we have the lock (token)
try:
// Check version again
current_version = redis.get(version_key)
if current_version != version:
// Version changed, try to get the new cache
new_cache_key = make_key(tenant_id, user_id, current_version)
data = redis.get(new_cache_key)
if data is not None:
return data
else:
// Rebuild with current_version
version = current_version
cache_key = new_cache_key
// Read from DB
data = read_from_db(tenant_id, user_id)
redis.set(cache_key, data, ex=300)
return data
finally:
release_lock(lock_key, token)
This is getting complex.
We can simplify:
We always try to get the cache first (with the current version). If miss, then we try to acquire the lock. If we get the lock, then we double-check the version and rebuild if necessary.
If we don't get the lock, we wait a bit and retry getting the cache (up to a few times). If still miss, then we try to acquire the lock again? Or we can fail?
Alternatively, we can use a "lock" that is actually a semaphore? But the above is standard.
Given the complexity, we might want to use a library for caching with stampede protection? But we are designing.
Let's try to write a cleaner version:
def get_auth(tenant_id, user_id):
version = get_version(tenant_id, user_id) # this function handles the version initialization with its own lock
key = make_key(tenant_id, user_id, version)
data = cache.get(key)
if data is not None:
return data
# cache miss
lock_token = lock.acquire(lock_key(tenant_id, user_id), timeout=30)
if not lock_token:
# Could not acquire lock, wait and retry getting the cache
for i in range(5):
time.sleep(0.01 * (2**i))
data = cache.get(key)
if data is not None:
return data
# After waiting, still miss? Then try to acquire lock again? Or fail?
# Let's try to acquire lock one more time?
lock_token = lock.acquire(lock_key(tenant_id, user_id), timeout=30)
if not lock_token:
# Still cannot acquire, then we try to read from DB and set cache without lock?
# But then we might have multiple processes doing that? That's the stampede.
# So we should not do that. We should fail or wait more?
# We can wait for the cache to be set by the other process? But we already waited.
# We can return an error? Or we can read from DB and set cache? But then we might have multiple processes reading from DB.
# Since we have the version, if we read from DB and set the cache, it might be stale if the version changed?
# But we are using the current version (the one we read at the beginning). If the version changed, then the cache we set will be with an old version and then the next request will use the new version and rebuild? That's acceptable?
# But note: if the version changed, then the data we read from DB is the current data (which is for the new version) but we are setting it with the old version? That's wrong.
# So we must check the version again before reading the DB? But we don't have the lock, so the version might change while we read.
# So without the lock, we cannot safely rebuild.
# Therefore, we must either wait for the lock or fail.
# We can wait a bit more? But we don't want to wait too long.
# Alternatively, we can use a "try" pattern: if we cannot get the lock, we return an error (or use a stale cache? but we don't have a stale cache because it's a miss).
# Since this is authorization, we might want to be correct rather than fast. So we can wait a bit more? But if the lock is held by a long rebuild, we might wait for seconds? That's not acceptable.
# We can set a maximum wait time (like 100ms) and then fail.
# So:
if we cannot get the lock after waiting, we throw an exception.
try:
# Now we have the lock
current_version = get_version(tenant_id, user_id)
if current_version != version:
# The version changed, try to get the new cache
new_key = make_key(tenant_id, user_id, current_version)
data = cache.get(new_key)
if data is not None:
return data
else:
# Rebuild with current_version
version = current_version
key = new_key
data = read_from_db(tenant_id, user_id)
cache.set(key, data, ex=300)
return data
finally:
lock.release(lock_key(tenant_id, user_id), lock_token)
This seems reasonable.
However, note that the get_version function might also use a cache? We can cache the version? But the version is just a number and we read it on every cache miss. We can cache the version in the same Redis? But we are already using Redis for the version key. So we are reading two keys: the version key and the cache key.
We can cache the version in the local process? But then we have to invalidate it? That's another cache.
Given that the version is a single integer and we are using Redis, it's fast. We can read it every time.
But we are already doing:
version = redis.get(version_key)
Then:
cache_key = ...
data = redis.get(cache_key)
That's two Redis calls. We can combine? Not really because the cache key depends on the version.
We can use a pipeline? But we need the version to form the cache key.
So we do:
version = redis.get(version_key)
if version is None: ... (initialize)
then cache.get(cache_key)
That's two round trips? We can do:
pipeline = redis.pipeline()
pipeline.get(version_key)
pipeline.get(cache_key) # but we don't know the cache key until we get the version? So we cannot pipeline.
So we have to do two separate calls.
Alternatively, we can store the version in the cache key? But then we don't know the version.
So we leave it as two calls.
Now, what about the version initialization? We have a lock for that. But note: the version key might be set by another process? We are using a lock to set it to 0 if it doesn't exist.
But what if the version key is set to 0 by one process and then another process tries to initialize? Then the second process will see it's set and not set again. That's fine.
However, the lock for version initialization is per user. We use a separate lock key for that.
Now, let's consider the entire flow:
User first request:
version_key doesn't exist.
We acquire the init lock (for that user) and set version to 0.
Then we try to get the cache (which doesn't exist) and then we acquire the rebuild lock (another lock) and then read from DB and set the cache with version 0.
Then, when a change happens:
We increment the version key (now it's 1).
Next request for the same user:
version = 1
cache_key with v1 doesn't exist (because we set v0) -> cache miss.
Then acquire rebuild lock, double-check version (still 1), read DB (new data), set cache with v1.
This works.
But note: the version key is set to 0 initially and then incremented. So the first cache is with v0. Then when we change, we set to v1 and then the next request rebuilds with v1.
What if the first request is slow and the change happens before the first request sets the cache?
Request1: gets version=0 (after initializing), then cache miss, then acquires rebuild lock.
Meanwhile, change happens: version becomes 1.
Request1: after acquiring lock, checks version: current_version=1 != 0 -> then tries to get cache for v1 (which doesn't exist) -> then rebuilds with version=1 and sets cache for v1.
Then Request1 returns.
But what about the cache for v0? It was never set? That's okay.
So it works.
Now, we must also consider that the version key might be incremented multiple times between two requests for the same user. Then the second request will see the latest version and rebuild with that version. The old versions' cache keys are orphaned and will expire.
We set the cache keys with an expiration (5 minutes). So they will be cleaned up.
This design seems to meet the requirements.
Let's write the code structure:
class AuthCache:
def __init__(self, redis_client):
self.redis = redis_client
def get_version_key(self, tenant_id, user_id):
return f"auth:tenant:{tenant_id}:user:{user_id}:version"
def get_cache_key(self, tenant_id, user_id, version):
return f"auth:tenant:{tenant_id}:user:{user_id}:v{version}"
def get_lock_key(self, tenant_id, user_id):
return f"lock:auth:tenant:{tenant_id}:user:{user_id}"
def get_init_lock_key(self, tenant_id, user_id):
return f"init_lock:auth:tenant:{tenant_id}:user:{user_id}"
def get_version(self, tenant_id, user_id):
version_key = self.get_version_key(tenant_id, user_id)
version = self.redis.get(version_key)
if version is not None:
return int(version)
# Initialize version
init_lock_key = self.get_init_lock_key(tenant_id, user_id)
token = self.acquire_lock(init_lock_key, timeout=10)
if token is None:
# Wait and retry
for i in range(3):
time.sleep(0.01 * (2**i))
version = self.redis.get(version_key)
if version is not None:
return int(version)
# Failed to initialize version
raise Exception("Could not initialize version")
try:
version = self.redis.get(version_key)
if version is None:
version = 0
self.redis.set(version_key, version)
return int(version)
finally:
self.release_lock(init_lock_key, token)
def get_auth(self, tenant_id, user_id):
version = self.get_version(tenant_id, user_id)
cache_key = self.get_cache_key(tenant_id, user_id, version)
data = self.redis.get(cache_key)
if data is not None:
return data
# Cache miss
lock_key = self.get_lock_key(tenant_id, user_id)
token = self.acquire_lock(lock_key, timeout=30)
if token is None:
# Wait and retry getting the cache
for i in range(5):
time.sleep(0.01 * (2**i))
data = self.redis.get(cache_key)
if data is not None:
return data
# Try to acquire lock again?
token = self.acquire_lock(lock_key, timeout=30)
if token is None:
# Still cannot acquire, fail
raise Exception("Could not acquire lock for cache rebuild")
try:
# Double check version
current_version = self.get_version(tenant_id, user_id)
if current_version != version:
new_cache_key = self.get_cache_key(tenant_id, user_id, current_version)
data = self.redis.get(new_cache_key)
if data is not None:
return data
else:
version = current_version
cache_key = new_cache_key
# Read from DB (assuming we have a method for that)
data = self.read_auth_from_db(tenant_id, user_id)
self.redis.set(cache_key, data, ex=300)
return data
finally:
self.release_lock(lock_key, token)
def invalidate(self, tenant_id, user_id):
version_key = self.get_version_key(tenant_id, user_id)
self.redis.incr(version_key)
We need to implement acquire_lock and release_lock with a token.
We can do:
def acquire_lock(self, lock_key, timeout=30):
token = str(uuid.uuid4())
acquired = self.redis.set(lock_key, token, ex=timeout, nx=True)
if acquired:
return token
else:
return None
def release_lock(self, lock_key, token):
# Lua script to release only if the token matches
script = """
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
"""
self.redis.eval(script, 1, lock_key, token)
This should work.
However, note that the lock for version initialization and the lock for cache rebuild are separate. That's okay.
But what if the version initialization lock and the cache rebuild lock are the same? They are not. We use different keys.
Also, note that the version initialization lock is only used when the version key doesn't exist. Once the version key exists, we don't need that lock.
This design should handle:
- Multi-tenant: by including tenant_id in all keys.
- Invalidation: by incrementing the version, which changes the cache key.
- Stampede prevention: by using a lock for rebuild.
- Correctness: by using version to avoid stale cache and by checking version again after acquiring the lock.
Potential issues:
- The version key might grow without bound? We set it without expiration. But we can set an expiration on the version key? But then if it expires, we lose the version and then we might use an old cache? So we don't set expiration.
- The orphaned cache keys: we set them with expiration (5 minutes) so they will be cleaned up.
- The lock keys: we set them with expiration (30 seconds) so they will be cleaned up if we crash.
- The init lock keys: we set them with expiration (10 seconds) so they will be cleaned up.
We must be cautious about the number of keys. But Redis can handle many keys.
Another issue: what if the version key is deleted? Then we reinitialize to 0 and then we might use old cache? But if the version key is deleted, then the next request will set it to 0 and then try to get the cache for v0. But if there is a cache key for v1 (from a previous version) then we will not use it because we are looking for v0. And then we will rebuild and set v0. That's acceptable? But note: the change that deleted the version key might have been because the user was deleted? Then we shouldn't be caching anyway.
But if the version key is deleted by mistake, then we reset to 0 and then we might serve stale data? Actually, if the version key is deleted, then the next request will set it to 0 and then look for cache v0. If there is no v0, it will rebuild and set v0. But if there is an old v1 cache, we ignore it. So we might rebuild and set the current state as v0. Then if the version key was deleted because of a mistake and then restored with a higher version? That's unlikely.
We can set the version key with a long expiration? But then we have to renew it? That's complex.
Alternatively, we can store the version in a more persistent way? But that's a separate problem.
Given that the version key is critical, we must ensure it's not deleted. We can set it without expiration and then have a backup? That's operational.
For the cache, we set an expiration so that even if the version key is lost, the cache will eventually expire and then we will rebuild with a new version (starting from 0). But note: if the version key is lost and then we set it to 0, and then a change happens (increment to 1) and then we have a cache for v0 and v1? Then the next request will use v1 (because the version is 1) and then if the cache for v1 exists, we use it. But the cache for v1 might be stale if the change happened after the cache for v1 was set? That's the same as normal.
Actually, if the version key is lost and then reinitialized to 0, then we lose the version history. But the cache keys are versioned, so we will not use the old ones (v1, v2, etc.) because the version is now 0. So we will rebuild and set v0. Then when a change happens, we increment to 1 and then set v1. So we have a gap: we lost the fact that we had v1 and v2 before? But that's okay because we are rebuilding from the current DB state.
So it's acceptable.
However, if the version key is lost and then we reinitialize to 0, but there are still cache keys for higher versions, then we will not use them and they will expire. So we might have extra cache keys that are orphaned and will expire.
That's acceptable.
Therefore, the design seems robust.
Let's write the code accordingly.
Note: We are using Redis. We assume the Redis client has the methods: get, set, incr, eval (for Lua script).
We also need to handle the DB read. That's outside the cache.
We must also consider that the cache might be set to a value that is not serializable? We assume we store serialized data.
This is a high-level design. We must adjust for the actual programming language and Redis client.
Also, we must consider that the version might be incremented by multiple processes. We use `incr` which is atomic.
Finally, we must test this design thoroughly.
I think this covers the requirements.</think>
Here's a comprehensive design for a multi-tenant authorization cache addressing invalidation, stampede prevention, and correctness:
1. Cache Key Design
# Include tenant context in all keys
cache_key = f"authz:tenant:{tenant_id}:user:{user_id}:resource:{resource}:action:{action}"
# Optional: Role-based aggregation
role_key = f"authz:tenant:{tenant_id}:role:{role_id}:perms"
2. Invalidation Strategies
A. Event-Driven Invalidation (Preferred)
B. Time-Based Fallback (TTL)
- Set conservative TTL (e.g., 5–15 minutes) as safety net.
- Warning: Risk of stale data between invalidations.
C. Hybrid Approach
- Primary: Event-driven invalidation.
- Secondary: Short TTL (e.g., 5 min) to auto-heal missed events.
3. Stampede Prevention
A. Request Coalescing (Locking)
def get_perms(tenant_id, user_id, resource):
key = f"authz:tenant:{tenant_id}:user:{user_id}:{resource}"
data = cache.get(key)
if data:
return data
lock_key = f"lock:{key}"
lock_token = acquire_lock(lock_key, timeout=10) # Redis SET NX EX
if lock_token:
try:
# Double-check after lock acquisition
data = cache.get(key)
if data:
return data
# Load from DB (with tenant isolation!)
data = db.query("""
SELECT p.permission
FROM permissions p
JOIN user_roles ur ON p.role_id = ur.role_id
WHERE ur.tenant_id = %s AND ur.user_id = %s
AND p.resource = %s
""", (tenant_id, user_id, resource))
cache.setex(key, 300, data) # 5-min TTL
return data
finally:
release_lock(lock_key, lock_token)
else:
# Wait and retry (with backoff)
sleep(random.uniform(0.01, 0.1))
return get_perms(tenant_id, user_id, resource) # Recursive retry (max 3x)
B. Early Expiration + Background Refresh
C. Probabilistic Early Expiration
# Add jitter to TTL to avoid synchronized expirations
ttl = 300 + random.randint(-30, 30)
cache.setex(key, ttl, data)
4. Correctness Guarantees
A. Tenant Isolation
- All keys must include
tenant_id.
- DB queries must always filter by
tenant_id (defense-in-depth).
- Redis logical separation: Use separate DBs or key prefixes per tenant if compliance requires (e.g.,
redis://localhost/1 for tenant A).
B. Cache-Aside with Write-Through (Optional)
C. Version Vectors (Advanced)
- Embed a
version or updated_at timestamp in cached values.
- On read, compare with DB version if suspiciously stale.
- Use case: Audit scenarios requiring strict consistency.
5. Multi-Tenant Scaling Considerations
A. Key Namespace Hygiene
B. Memory Management
- Per-tenant limits: Use
redis-maxmemory-policy with volatile-lru or allkeys-lru.
- Eviction tracking: Monitor
evicted_keys metric per tenant.
C. Monitoring & Alerts
metrics:
- cache_hit_rate: per_tenant
- stampede_locks_acquired
- invalidation_latency
- cache_memory_per_tenant
alerts:
- if stampede_rate > 5%: warn
- if tenant_cache_hit_rate < 80%: investigate
6. Failure Modes & Mitigations
| Scenario | Risk | Mitigation |
|---|
| Redis failover | Stale data | Use Redis Cluster with replicas; fallback to DB on cache errors |
| Invalidation lost | Stale data indefinitely | TTL safety net; periodic full-tenant revalidation job |
| Lock held too long | Denial-of-service | Lock timeout (10–30 sec); circuit breaker after N failures |
| Tenant data bleed | Security breach | Enforce tenant_id in every query; key prefix audits |
7. Example Implementation (Python-like Pseudocode)
class MultiTenantAuthCache:
def __init__(self, redis_client, db_pool):
self.redis = redis_client
self.db = db_pool
self.default_ttl = 300 # 5 minutes
def _key(self, tenant_id, user_id, resource, action):
return f"authz:t:{tenant_id}:u:{user_id}:r:{resource}:a:{action}"
def get_permission(self, tenant_id, user_id, resource, action):
key = self._key(tenant_id, user_id, resource, action)
# 1. Try cache
cached = self.redis.get(key)
if cached:
return deserialize(cached)
# 2. Stampede prevention
lock_key = f"lock:{key}"
token = self._acquire_lock(lock_key, timeout=10)
if not token:
return self._with_backoff(lambda: self.get_permission(tenant_id, user_id, resource, action))
try:
# 3. Double-check after lock
cached = self.redis.get(key)
if cached:
return deserialize(cached)
# 4. Load from DB (tenant-scoped!)
perms = self.db.execute("""
SELECT permission FROM permissions
WHERE tenant_id = %s
AND user_id = %s
AND resource = %s
AND action = %s
""", (tenant_id, user_id, resource, action)).fetchall()
# 5. Cache with jittered TTL
ttl = self.default_ttl + random.randint(-30, 30)
self.redis.setex(key, ttl, serialize(perms))
return perms
finally:
self._release_lock(lock_key, token)
def invalidate_user(self, tenant_id, user_id):
pattern = f"authz:t:{tenant_id}:u:{user_id}:*"
keys = self.redis.keys(pattern)
if keys:
self.redis.delete(*keys)
# Optional: Increment tenant-wide version
self.redis.incr(f"authz:version:tenant:{tenant_id}")
8. Recommended Stack
- Cache: Redis Cluster (with ACLs for tenant isolation).
- Locking: Redlock algorithm (if multi-region) or simple
SET NX EX.
- Monitoring: Redis
INFO, custom metrics via Prometheus.
- Invalidation: Message queue (Kafka/RabbitMQ) for async event propagation.
9. Key Trade-offs
| Concern | Option | Trade-off |
|---|
| Consistency vs Performance | Short TTL vs event-driven | Event-driven gives strong consistency but adds complexity |
| Memory vs Speed | Cache all vs cache hot | Full cache uses more memory but faster |
| Complexity vs Safety | Version vectors vs simple invalidation | Version vectors safer but harder to implement |
10. Testing Checklist
This design balances safety (no cross-tenant leaks), performance (stampede prevention), and freshness (event-driven invalidation). Adjust TTLs and locking timeouts based on your volatility (how often permissions change) and latency requirements.