iTranslated by AI
Deconstructing Redis Keys That Grew Indefinitely Despite Having EXPIRE Set
TL; DR
Just because all keys have an Expire set doesn't mean you can let your guard down.
Be very careful about any code in your Application Code that extends the Expire of existing keys.
The safest and most comprehensive way to find infinitely growing keys is by analyzing RDB files.
Preface
This story is a work of fiction!!!!
A story from an API server development project
In a certain API server, a token with an expiration of 1 hour was issued per user ID for API requests, and this was used for authentication and authorization.
The specific token requirements were as follows:
API token requirements
- Each token has an expiration of 1 hour.
- Tokens are issued per user ID.
- Can be used multiple times within the expiration period.
- A user can hold multiple tokens simultaneously.
- If a user unsubscribes, all tokens must be immediately invalidated, even if they still have an expiration period remaining.
- It must be possible to invalidate a specific token for a specific user.
- Token validation must be completed in under 1ms.
Implementation based on requirements
- Tokens are generated as UUIDs.
- Tokens are stored in Redis as a Hash type, with the following data design:
(Hash type ) (key, field, value) = (userID, token, TTL)
They were processed with the following code:
*Pseudo-code.
Token generation
Generate a token and store it in a Redis Hash type.
At that time, the expiration of the Hash type is updated to the longest expiration of the saved token.
public String createToken(userId){
String token = UUID.randomeUUID();
long ttl = Instant.now().getEpochSecond() + 3600L;
redis.hset(userId, token, ttl);
redis.expire(userId, 3600); // Set the expiration to be the same as the latest token
return token;
}
Token validation
Get the expiration from the token stored in Redis, and return true if it can be retrieved and is within the expiration period.
public boolean validateToken(userId, token){
int ttl = redis.hget(userId, token)
long current = Instant.now().getEpochSecond();
return ttl >= current;
}
Invalidate all tokens upon user unsubscription
Delete the Hash type Key itself stored in Redis.
public void deleteTokenByUserId(userId){
redis.del(userId);
}
Invalidate a specific token for a user
Delete the Hash type (Key, Field) stored in Redis.
public void deleteToken(userId, token){
redis.hdel(userId, token);
}
What happened?
This implementation worked without issues in most cases (for over 2 years of API server operation).
Even if the expiration could be extended indefinitely, it's rare for a user to continuously access without a 1-hour break.
If access stopped for 1 hour, Redis's expiration mechanism automatically cleaned up the Key.
However, one day, a single user began accessing mechanically every minute.
Since it was every-minute access, there was no load problem, and it didn't trigger any detection mechanisms.
It also seemed that this mechanical access was generating a new token each time.
As a result, only the token storage Key for that specific user in Redis grew significantly.
However, both the HGET command for token validation and the HSET command for token generation were O(1) constant time operations, so there was no noticeable slowdown in the application.
However, this situation was extremely dangerous.
If that user unsubscribed, a DEL command (O(N) where N is the number of fields) would be issued, potentially causing the application to halt for tens of seconds.
The trigger for this was dependent on that user's behavior, making the situation uncontrollable.
And then, to a Key over 1.2GB...
Time passed without any detection.
One day, for another reason, the contents of Redis were checked.
The tool used for this was to analyze the RDB file, which is a snapshot of Redis.
sripathikrishnan/redis-rdb-tools: Parse Redis dump.rdb files, Analyze Memory, and Export Data to JSON
After sorting by size, a Key that had grown to over 1.2GB was discovered.
Data design change
The problem with the original data design was that user-level invalidation and token storage were handled by a single Key.
Therefore, the data design was changed as follows:
As a result, tokens were distributed across different Keys, which also brought benefits like easier horizontal sharding.
# Token storage
(String type ) (key, value) = (token, userId)
# User invalidation flag
(String type ) (key, value) = (revoked_userId, true)
The code was also changed as follows:
*Pseudo-code.
Token generation
Generate a token and store it in a Redis String type.
At that time, the expiration of the String type matches the token's expiration.
public String createToken(userId){
String token = UUID.randomeUUID();
redis.setex(token, userId, 3600);
return token;
}
Token validation
Retrieve the user ID from the token stored in Redis.
Also, retrieve the invalidated user ID stored in Redis.
If the token exists and the user ID is not invalidated, return true.
public boolean validateToken(userId, token){
String savedUserId = redis.get(token)
boolean revokedUserId = redis.exists("revoked_"+userId)
return ( !revokedUserId && userId == savedUserId )
}
Invalidate all tokens upon user unsubscription
Set the revoked_userId flag in Redis.
The expiration is 3600 seconds, the maximum length of a token at that time.
public void deleteTokenByUserId(userId){
redis.setex("revoked_"+userId, true, 3600);
}
Invalidate a specific token for a user
Delete the String type token stored in Redis.
public void deleteToken(userId, token){
String savedUserId = redis.get(token);
if(savedUserId == userId){
redis.del(token);
}
}
Summary
Be extremely cautious when using Hash or Set types whose element counts can continuously increase, especially when updating their expiration.
If you haven't scrutinized your Redis contents before, it would be a good idea to analyze them from an RDB file.
Discussion