Caching with Redis (Performance Boost)
Caching with Redis (Performance Boost) – Express.js
Redis Caching ব্যবহার করে Express.js অ্যাপ্লিকেশনের response time কমানো, server load হ্রাস করা এবং high-performance API তৈরি করা যায়।
📌 Redis কী?
Redis হলো একটি in-memory data store, যা key-value format-এ data সংরক্ষণ করে। Database query বা heavy computation-এর result cache করে রাখার জন্য Redis ব্যাপকভাবে ব্যবহৃত হয়।
⚡ High Speed
Redis RAM-এ data রাখে, তাই response আসে মিলিসেকেন্ডের মধ্যেই।
📉 Reduced DB Load
একই query বারবার database-এ না পাঠিয়ে cache থেকে data পাওয়া যায়।
🚀 Scalability
High traffic অ্যাপ্লিকেশনের জন্য Redis caching অত্যন্ত কার্যকর।
🛠 Redis Setup (Express.js)
npm install redis
Redis client তৈরি:
const redis = require("redis");
const client = redis.createClient();
client.on("connect", () => {
console.log("Redis Connected");
});
🔄 Basic Caching Example
Database query result cache করে API response দ্রুত করা:
app.get("/users", async (req, res) => {
const cacheData = await client.get("users");
if (cacheData) {
return res.json({
source: "cache",
data: JSON.parse(cacheData)
});
}
// Suppose this is a DB query
const users = [
{ id: 1, name: "Rahim" },
{ id: 2, name: "Karim" }
];
await client.setEx("users", 60, JSON.stringify(users));
res.json({
source: "database",
data: users
});
});
⏳ Cache Expiration (TTL)
TTL (Time To Live) ব্যবহার করে নির্দিষ্ট সময় পর cache automatically expire করা যায়।
client.setEx("products", 120, JSON.stringify(products));
🧹 Cache Invalidation
Data update হলে পুরনো cache delete করা জরুরি।
await client.del("users");
🌍 Real-Life Use Cases
- API response caching
- User session storage
- Rate limiting & request throttling
- Leaderboard ও analytics data
⚡ Performance Best Practices
- সব data cache করবেন না, frequently accessed data cache করুন
- TTL ব্যবহার করে stale data এড়ান
- Cache invalidation logic পরিষ্কার রাখুন
- Redis-কে DB replacement না বানান
লোড হচ্ছে...
1. Redis কী এবং কেন এটি ব্যবহৃত হয়?
Redis একটি in-memory data store যা caching এর মাধ্যমে অ্যাপ্লিকেশনের পারফরম্যান্স অনেক দ্রুত করে।
2. Redis Cache ব্যবহার করলে কী সুবিধা পাওয়া যায়?
ডাটাবেজে বারবার query না করে Redis থেকে ডাটা পাওয়া যায়, ফলে response time কমে যায়।