In the earlier lessons, we used the KEYS * command to list all the keys in our Redis database. While this approach works fine when you are experimenting or working with a small dataset, it becomes inefficient in real-world scenarios.
Let’s now understand why that’s the case, and learn a more efficient way to check whether a specific key exists in Redis.
Why Not Use KEYS * in Production?
The KEYS * command returns all the keys stored in the Redis database. You can also use patterns like KEYS user:* to fetch only matching keys. However, this command performs a full scan of the database, which can be very slow if you have thousands or millions of keys.
Because of this, the Redis documentation clearly warns against using KEYS in production environments. It blocks the Redis server while scanning all keys, which can lead to performance degradation.
That’s why we use a more efficient alternative — the EXISTS command.
The EXISTS Command
Redis provides the EXISTS command to quickly check whether a specific key is present in the database or not.
Syntax
EXISTS key_name
Example 1: Checking a Key That Exists
Let’s assume we already have a key in our Redis store.
SET user:1 "John"
Now, we can check if this key exists:
EXISTS user:1
Output:
(integer) 1
The output 1 means that the key user:1 is present in the database.
Example 2: Checking a Key That Does Not Exist
If you check for a key that doesn’t exist:
EXISTS user:2
Output:
(integer) 0
The output 0 indicates that the key user:2 is not present.
Using EXISTS with Expiring Keys
You can also combine this command with expiration logic to validate if a key (for example, a session token or cache entry) is still active.
Example
- Let’s create a key that represents a user session and set an expiry time:
SET session:user1 "active" EXPIRE session:user1 5Here, the session key will automatically expire after 5 seconds. - Immediately after setting, check if it exists:
EXISTS session:user1Output:(integer) 1The key is still present. - Wait for a few seconds (more than 5 seconds) and check again:
EXISTS session:user1Output:(integer) 0The key no longer exists — it has expired.
This behavior is very useful in real-world applications. For example, you can use it to check if a user’s login session or authentication token is still valid before allowing further actions.
Summary
- The
KEYScommand should not be used in production because it scans the entire keyspace and can block the Redis server. - Use the
EXISTScommand to efficiently check if a specific key is present. - The command returns:
1if the key exists0if the key does not exist
- You can use it along with expiration logic to check session validity or cache status.
