1. What is Redis?
Redis (Remote Dictionary Server) is an in-memory key-value database.
Instead of storing data primarily on disk like PostgreSQL or MySQL, Redis keeps data in RAM, making it extremely fast (microseconds to milliseconds).
Example:
"user:1": {
name: "Akkal",
age: 22
}You store data using a key and retrieve it later.
2. Why Redis?
Suppose your application fetches a user's profile from PostgreSQL.
Without Redis:
Client
↓
Backend
↓
PostgreSQLEvery request hits the database.
With Redis:
Client
↓
Backend
↓
Redis (cache)
↓ (miss)
PostgreSQL- If data exists in Redis (cache hit), response is returned immediately.
- Otherwise (cache miss), data is fetched from PostgreSQL and stored in Redis for future requests.
This reduces:
- Database load
- Response time
- Infrastructure costs
3. Installing Redis
Docker:
services:
redis:
image: redis
ports:
- 6379:6379docker compose upVerify:
redis-cli pingOutput:
PONG3.1 Create Redis Client
npm install ioredisimport Redis from "ioredis";
const client = new Redis("redis://127.0.0.1:6379");
client.on("error", (err) => console.log("Redis Client Error:", err));4. Redis Basic Commands
4.1 SET & get
await client.set("name", "John Doe");const value = await client.get("name");
console.log('Value for "name":', value);Output:
Value for "name": John Doe4.2 DELETE
const deleteCount = await client.del("name");
console.log("Deleted keys count:", deleteCount);Output:
Deleted keys count: 14.3 MSET & MGET
await client.mset({
"user:name": "Akkal Dhami",
"user:age": "20",
"user:country": "Nepal"
});const [username, age, country] = await client.mget([
"user:name",
"user:age",
"user:country"
]);
console.log(`Name: ${username}, Age: ${age}, Country: ${country}`);Output:
Name: Akkal Dhami, Age: 20, Country: Nepal4.4 LPUSH, RPUSH, LRANGE, LINDEX, LPOP, RPOP
await client.lpush("tasks", "Task 1");
await client.lpush("tasks", ["Task 2", "Task 3"]);
await client.rpush("tasks", "Task 4");LPUSHinserts at the beginning.RPUSHinserts at the end.
1. Get all elements
const tasks = await client.lrange("tasks", 0, -1);
console.log(tasks);Output:
["Task 3", "Task 2", "Task 1", "Task 4"]
2. Get the first element
const task = await client.lindex("tasks", 0);
console.log(task);Output:
Task 3
3. Get the last element
const task = await client.lindex("tasks", -1);
console.log(task);Output:
Task 4
4. Get a range
First two items:
const task = await client.lrange("tasks", 0, 1);
console.log(task);Output:
["Task 3", "Task 2"]
5. Remove and retrieve an item
From the left:
const task = await client.lpop("tasks");
console.log(task); // Task 3From the right:
const task = await client.rpop("tasks");
console.log(task); // Task 44.5 SADD, SMEMBERS, SISMEMBER, SREM
Redis Set stores unique unordered values.
await client.sadd("fruits", "Apple");
await client.sadd("fruits", ["Banana", "Orange", "Mango"]);After these operations, the set contains:
Apple
Banana
Orange
Mango1. Get all members
const fruits = await client.smembers("fruits");
console.log("Fruits:", fruits);Output:
Fruits: [ 'Apple', 'Banana', 'Orange', 'Mango' ]
Sets are unordered, so the order may vary.
2. Check if a value exists
const isMember = await client.sismember("fruits", "Banana");
console.log("Is Banana a member of fruits set?", isMember);Output:
Is Banana a member of fruits set? 1
1 means the value exists.
0 means the value doesnot exist.
3. Remove an item
await client.srem("fruits", "Apple");const updatedFruits = await client.smembers("fruits");
console.log("Updated Fruits:", updatedFruits);Output:
Updated Fruits: [ 'Orange', 'Banana', 'Mango' ]
4.6 HSET, HGET
1. Creating a Hash
await client.hSet("user:1", {
name: "Akkal",
email: "akkal@example.com",
age: "20",
});2. Get all fields
const user = await client.hGetAll("user:1");
console.log(user);Output:
{
name: "Akkal",
email: "akkal@example.com",
age: "20"
}3. Get a single field
const name = await client.hGet("user:1", "name");
console.log(name);Output:
Akkal
4. Get multiple fields
const values = await client.hmGet(
"user:1",
["name", "email"]
);
console.log(values);Output:
[ 'Akkal', 'akkal@example.com' ]
5. Update a field
await client.hSet("user:1", "age", "23");const user = await client.hGetAll("user:1");
console.log(user);Output:
{
name: "Akkal",
email: "akkal@example.com",
age: "23"
}6. Check if a field exists
const exists = await client.hExists(
"user:1",
"email"
);
console.log(exists);Output: 1
1 means the field exists.
7. Delete a field
await client.hDel("user:1", "age");console.log(await client.hGetAll("user:1"));Output:
{
name: "Akkal",
email: "akkal@example.com"
}8. Count fields
const count = await client.hLen("user:1");
console.log(count);Output: 2
9. Get only field names
const fields = await client.hKeys("user:1");
console.log(fields);Output:
[ 'name', 'email' ]
10. Get only values
const values = await client.hVals("user:1");
console.log(values);Output:
[ 'Akkal', 'akkal@example.com' ]