今日已更新 84 条资讯 | 累计 29818 条内容
关于我们

How I Protected My Express API from Spam and High AI Costs Using Redis

Nikhil Singh 2026年08月10日 02:24 1 次阅读 来源:Dev.to

When I was building my backend API, I realized a big problem: anyone could spam my endpoints. If a user repeatedly reloads a page or hits an endpoint calling an external AI service, it can crash the server or run up high API costs. To fix this, I added Rate Limiting . Here is why I used Redis for it and how I set it up. The Problem with Simple In-Memory Limiters At first, I thought about saving request counts in a simple JavaScript object: // ❌ Simple in-memory check (Not good for production) const requestCounts = {}; app . use (( req , res , next ) => { const ip = req . ip ; requestCounts [ ip ] = ( requestCounts [ ip ] || 0 ) + 1 ; if ( requestCounts [ ip ] > 100 ) { return res . status ( 429 ). json ({ error : " Too many requests " }); } next (); }); This works locally, but has two big flaws: 1)Memory Leaks: The requestCounts object keeps growing in memory forever. 2)Breaks when Scaling: If you deploy multiple instances of your app behind a load balancer, each server keeps its own count. A user can easily bypass the limit by hitting different servers. The Solution: Centralized Redis Store Redis stores data in RAM outside our Node.js app. Because it is centralized, all server instances share the exact same count. [ Incoming Client Requests ] │ ▼ [ Cloud Load Balancer ] │ ┌───────────────┼───────────────┐ ▼ ▼ ▼ [ Express Node 1 ] [ Express Node 2 ] [ Express Node 3 ] │ │ │ └───────────────┼───────────────┘ ▼ [ Central Redis Store ] (Checks Request Limits) How I Configured It in My Project In my app, I use two levels of protection: Global Limit: 100 requests per 15 minutes for normal routes. Strict Limit: 5 requests per 10 minutes for heavy routes (like AI generation or OTP emails). 1 . Redis Connection ( config / redis . js ) import { createClient } from ' redis ' ; const redisClient = createClient ({ url : process . env . REDIS_URL || ' redis://localhost:6379 ' }); redisClient . on ( ' error ' , ( err ) => console . error ( ' Redis Error: ' , err )); redisClient .

本文内容来源于互联网,版权归原作者所有
查看原文