Bun API Rate Limiting
0 105
🚦 Introduction to API Rate Limiting in Bun
APIs are powerful, but if left unchecked, they can be abused. From brute-force login attacks to spamming endpoints, uncontrolled access can lead to downtime or costly overuse of resources. This is where API rate limiting steps in.
If you're building APIs with Bun, it's important to implement rate limiting to control the number of requests a user can make in a given timeframe. Let’s explore how to add this feature efficiently using Bun’s fast runtime and native features.
🔍 What Is Rate Limiting?
Rate limiting is a mechanism that restricts how many requests a client can make to your server in a specific window of time. It helps:
- Prevent abuse and spam
- Protect server resources
- Maintain fair usage policies
- Enhance overall security
🛠️ Building a Basic Bun Server
Let's start with a simple Bun server that we’ll enhance with rate limiting:
const server = Bun.serve({
port: 3000,
fetch(req) {
return new Response("Hello from Bun API!");
}
});
console.log("Server is running on http://localhost:3000");
⚙️ Implementing In-Memory Rate Limiting 🧠
Here’s a basic in-memory rate limiter using Bun’s fast event loop. We’ll allow 5 requests per IP every 60 seconds.
const RATE_LIMIT = 5;
const TIME_WINDOW = 60 * 1000; // 60 seconds
const ipRequestMap = new Map();
const server = Bun.serve({
port: 3000,
fetch(req) {
const ip = req.headers.get("x-forwarded-for") || req.headers.get("host") || "unknown";
const now = Date.now();
if (!ipRequestMap.has(ip)) {
ipRequestMap.set(ip, []);
}
const timestamps = ipRequestMap.get(ip).filter(ts => now - ts < TIME_WINDOW);
timestamps.push(now);
ipRequestMap.set(ip, timestamps);
if (timestamps.length > RATE_LIMIT) {
return new Response("🚫 Too Many Requests", { status: 429 });
}
return new Response("✅ Request OK");
}
});
This solution tracks the IP and timestamps of requests. If the count exceeds the limit, the user receives a 429 status.
📦 Using Redis for Persistent Rate Limiting
For distributed or production systems, an in-memory map won’t scale. Use Redis to persist request counts across multiple server instances:
// Pseudocode – Redis integration with Bun
import { createClient } from 'redis';
const redis = createClient();
await redis.connect();
const ip = getIpFromRequest(req);
const key = `rate:${ip}`;
const count = await redis.incr(key);
if (count === 1) {
await redis.expire(key, 60); // 60 seconds
}
if (count > 5) {
return new Response("Too Many Requests", { status: 429 });
}
This setup ensures that your rate limits are consistent even when running multiple servers.
🧪 Testing the Rate Limiter
To simulate and test your rate limiter, you can use curl
or tools like Postman:
for i in {1..10}; do curl -i http://localhost:3000; done
The first five requests should pass, and the rest should return 429 Too Many Requests
.
🔐 Best Practices for Rate Limiting
- Use headers like
X-RateLimit-Limit
andX-RateLimit-Remaining
for better UX - Apply different limits for different endpoints (e.g. login vs. homepage)
- Whitelist internal IPs or admin routes
- Log abuse attempts for analysis
🚧 Rate Limiting Headers (Optional)
You can also return metadata about rate limits to the client:
return new Response("✅ Request OK", {
headers: {
"X-RateLimit-Limit": RATE_LIMIT,
"X-RateLimit-Remaining": RATE_LIMIT - timestamps.length,
"X-RateLimit-Reset": Math.ceil((TIME_WINDOW - (now - timestamps[0])) / 1000)
}
});
📈 Conclusion: Control the Flow with Bun
With Bun's blazing performance, it’s easy to build fast APIs. But speed without control can be dangerous. Rate limiting is a must-have to keep your API stable, secure, and fair for all users.
Whether you go for in-memory or Redis-backed strategies, integrating rate limits into your Bun server is a smart move — and as you’ve seen, pretty simple too.
Protect your Bun APIs, one request at a time! 🛡️
If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!
For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!

Share:
Comments
Waiting for your comments