Key design patterns in Redis - Time & Space Complexity
When using Redis key design patterns, it is important to understand how the time to access or modify keys changes as the number of keys grows.
We want to know how the operations scale when we use common patterns like namespaces or key prefixes.
Analyze the time complexity of accessing keys with a common prefix pattern.
# Set keys with a prefix
SET user:1001 "Alice"
SET user:1002 "Bob"
SET user:1003 "Carol"
# Retrieve keys by prefix
KEYS user:*
This code sets several keys with the prefix "user:" and then retrieves all keys starting with that prefix.
Look for operations that repeat or scan through data.
- Primary operation: The
KEYScommand scans all keys to find matches. - How many times: It checks every key in the database once.
As the number of keys grows, the time to run KEYS user:* grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 key checks |
| 100 | 100 key checks |
| 1000 | 1000 key checks |
Pattern observation: The number of operations grows directly with the number of keys.
Time Complexity: O(n)
This means the time to find keys with a prefix grows linearly as the total number of keys increases.
[X] Wrong: "Using key prefixes makes key searches instant regardless of database size."
[OK] Correct: The KEYS command still scans all keys, so the time depends on total keys, not just the prefix.
Understanding how key patterns affect performance helps you design efficient Redis databases and answer questions about scaling data access.
"What if we replaced KEYS with SCAN for prefix matching? How would the time complexity change?"