Redis with Node.js (ioredis) - Time & Space Complexity
When using Redis with Node.js through ioredis, it's important to understand how the time to run commands grows as data size increases.
We want to know how the number of operations changes when we run commands like fetching or setting many keys.
Analyze the time complexity of the following Redis commands using ioredis.
const Redis = require('ioredis');
const redis = new Redis();
async function getMultipleKeys(keys) {
const pipeline = redis.pipeline();
keys.forEach(key => pipeline.get(key));
const results = await pipeline.exec();
return results.map(result => result[1]);
}
This code fetches multiple keys from Redis using a pipeline to send all requests at once.
Look for repeated actions that affect time.
- Primary operation: Sending a GET command for each key in the list.
- How many times: Once for each key in the input array.
As the number of keys grows, the number of GET commands grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 GET commands sent |
| 100 | 100 GET commands sent |
| 1000 | 1000 GET commands sent |
Pattern observation: The number of operations grows directly with the number of keys.
Time Complexity: O(n)
This means the time to get all keys grows in a straight line as you add more keys.
[X] Wrong: "Using pipeline makes the time constant no matter how many keys we get."
[OK] Correct: Pipeline reduces network delays but still sends one command per key, so time grows with the number of keys.
Understanding how Redis commands scale helps you explain your choices clearly and shows you know how to handle data efficiently in real projects.
"What if we replaced pipeline with individual get calls without batching? How would the time complexity change?"
Practice
set method do in ioredis when used with Node.js?Solution
Step 1: Understand the purpose of
Thesetin Redissetmethod is used to store data by assigning a value to a key in Redis.Step 2: Differentiate from other methods
getretrieves data,deldeletes data, and connection is handled separately.Final Answer:
Stores a value with a specified key in Redis -> Option AQuick Check:
setstores data [OK]
- Confusing set with get
- Thinking set deletes data
- Assuming set connects to Redis
Solution
Step 1: Recognize async nature of ioredis commands
ioredis commands return promises, soawaitis needed to get the resolved value.Step 2: Identify correct method and usage
getretrieves the value;setstores data;getSyncdoes not exist.Final Answer:
const value = await redis.get('name'); -> Option DQuick Check:
Useawaitwithget[OK]
- Omitting await causing unresolved promises
- Using non-existent getSync method
- Using set instead of get to read data
const Redis = require('ioredis');
const redis = new Redis();
async function test() {
await redis.set('color', 'blue');
const val = await redis.get('color');
console.log(val);
}
test();Solution
Step 1: Analyze the set command
The code stores the string 'blue' with key 'color' in Redis asynchronously.Step 2: Analyze the get command and console output
The code retrieves the value for 'color' and logs it, which should be 'blue'.Final Answer:
blue -> Option CQuick Check:
set then get returns stored value [OK]
- Forgetting await causing undefined output
- Assuming get returns null if key exists
- Syntax errors from missing async
const Redis = require('ioredis');
const redis = new Redis();
function getValue() {
const value = redis.get('key');
console.log(value);
}
getValue();Solution
Step 1: Understand async nature of redis.get
Thegetmethod returns a Promise, so withoutawait,valueis a Promise object.Step 2: Identify missing await and its effect
Loggingvalueprints a Promise, not the actual stored value.Final Answer:
Missing await causing value to be a Promise -> Option AQuick Check:
Always await async Redis calls [OK]
- Ignoring async/await causing Promise logs
- Thinking Redis import is wrong
- Assuming console.log inside function is invalid
Solution
Step 1: Understand Redis stores strings
Redis stores strings, so objects must be converted to strings before storing.Step 2: Use JSON methods to store and retrieve objects
UseJSON.stringifyto convert object to string before storing, andJSON.parseto convert back after retrieving.Final Answer:
Useset('session', JSON.stringify(session))to store andJSON.parse(await get('session'))to retrieve -> Option BQuick Check:
Stringify before set, parse after get [OK]
- Trying to store objects directly without stringifying
- Using hash commands without proper structure
- Splitting session into multiple keys unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
