Hey there! Welcome back. Today we are going to learn how to scale and level up your API building skills in Node.js.
Let's talk about something that's been keeping you up at night. You've got your shiny new API up and running, but suddenly, your endpoints are getting bombarded with requests. Bots are spamming you. Your database is crying. Everything's slowing down, and you're stuck in the weeds trying to fix it.
Sound familiar? You don't want to be that developer who's constantly fighting fires. You want smooth, fast, and secure. And that's where Redis comes in.
Click here to read for free
Here's how we're going to fix this:
- Block those sneaky bots before they even make it to your server
- Cache data the right way (so your DB doesn't melt)
- Stop that one guy from spamming your /checkout route
- Use Redis to give your backend the brainpower it deserves
Why This Is a Game-Changer?
Picture this:
You launch your API into the wild. Within minutes, your /products endpoint sees 10k requests.
Your database's CPU starts overheating. Your backend is on the verge of collapse. And now you've got users leaving angry reviews.
Let's avoid that disaster with Redis, the lightweight, super-efficient solution that'll speed up your backend and help protect your server from getting steamrolled.
Step 1: Install the Libraries
Before we dive in, let's get Redis installed:
npm install redis express-rate-limit rate-limit-redis
If you don't have Redis set up yet, you can either run it locally or use a cloud service like Upstash. Either way, it's time to get Redis in your corner.
Step 2: Connect Redis to Your App
Let's create a new file called /utils/redisClient.ts and set up the Redis client:
import { createClient } from 'redis';
const redisClient = createClient({
url: process.env.REDIS_URL,
});
redisClient.on('error', (err) => console.error('Redis error:', err));
redisClient.on('connect', () => console.log('Redis connected!'));
export const connectRedis = async () => await redisClient.connect();
export const disconnectRedis = async () => await redisClient.quit();
export default redisClient;Now your app is ready to talk to Redis. Clean, simple, and efficient.
Step 3: Implement Rate Limiting
Time to block the spam. Add rate limiting to your API endpoints so that no one can flood your server with requests.
Create a new file called /middlewares/rateLimiter.ts:
import rateLimit from 'express-rate-limit';
import RedisStore from 'rate-limit-redis';
import redisClient from '../utils/redisClient';
export const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Max 100 requests per window
message: 'Too many requests, please try again later.',
store: new RedisStore({
sendCommand: (...args: string[]) => redisClient.sendCommand(args),
prefix: 'rl:ip:',
}),
});Then, just add the rate limiter to your routes:
app.use('/api', apiLimiter);Boom. Now your server isn't being bombarded by 1000 requests per second.
Step 4: Start Caching
Next up, let's cache that data. Why hit the DB every time? Redis has your back.
Create a cache helper /utils/cache.ts:
import redisClient from './redisClient';
const buildKey = (key: string) => `cache:${key}`;
export const getCache = async (key: string) => {
const data = await redisClient.get(buildKey(key));
return data ? JSON.parse(data) : null;
};
export const setCache = async (key: string, value: any, ttl = 60) => {
await redisClient.setEx(buildKey(key), ttl, JSON.stringify(value));
};
export const deleteCache = async (key: string) => {
await redisClient.del(buildKey(key));
};And use this in your controllers to cache your /products endpoint:
import { getCache, setCache, deleteCache } from '@/utils/cache';
const getAllProducts = async (req, res) => {
const cacheKey = 'products:all';
const cached = await getCache(cacheKey);
if (cached) {
console.log('Cache hit!');
return res.json(cached);
}
const products = await Product.find();
await setCache(cacheKey, products, 120); // Cache for 2 mins
res.json(products);
};Mistakes to Avoid
Now, before you go and set this all up, avoid these common mistakes:
❌ Forgetting to set TTL on your Redis keys. ❌ Not invalidating the cache when data updates. ❌ Storing sensitive data in Redis without encryption.
Ready to Scale Like a Pro?
That's it! You've got Redis in your toolkit now. Your backend is faster, more secure, and built for scale. Now go ahead and deploy without worrying about bot attacks or overwhelming traffic.