Rate Limit Module
The std/rate_limit module provides in-memory rate limiting with configurable time windows and request limits.
Import
Section titled “Import”import { rateLimit } from "std/rate_limit"Functions
Section titled “Functions”rateLimit.create(limit: int, windowMs: int): string
Section titled “rateLimit.create(limit: int, windowMs: int): string”Create a new rate limiter. Returns a limiter ID for use with other functions.
limit— maximum number of requests allowed in the windowwindowMs— time window in milliseconds
// Allow 100 requests per minuteconst limiter = rateLimit.create(100, 60000)
// Allow 10 requests per secondconst strictLimiter = rateLimit.create(10, 1000)rateLimit.check(limiterID: string, key: string): bool
Section titled “rateLimit.check(limiterID: string, key: string): bool”Check if a request is allowed for the given key. Returns true if allowed, false if rate-limited. The key is typically an IP address or user ID.
const allowed = rateLimit.check(limiter, "192.168.1.1")if (!allowed) { println("Rate limited!")}rateLimit.remaining(limiterID: string, key: string): int
Section titled “rateLimit.remaining(limiterID: string, key: string): int”Returns the number of remaining requests for the given key in the current window.
const left = rateLimit.remaining(limiter, "192.168.1.1")println("Requests remaining: " + string(left))rateLimit.reset(limiterID: string, key?: string): void
Section titled “rateLimit.reset(limiterID: string, key?: string): void”Reset the rate limiter. If a key is provided, resets only that key. Otherwise resets all keys.
rateLimit.reset(limiter, "192.168.1.1") // Reset one keyrateLimit.reset(limiter) // Reset all keysFunction Reference
Section titled “Function Reference”| Function | Description |
|---|---|
rateLimit.create(limit, windowMs) | Create a new rate limiter |
rateLimit.check(limiterID, key) | Check if request is allowed |
rateLimit.remaining(limiterID, key) | Get remaining requests for key |
rateLimit.reset(limiterID, key?) | Reset limiter for key or all keys |
Example: API Rate Limiting Middleware
Section titled “Example: API Rate Limiting Middleware”import { rateLimit } from "std/rate_limit"import { createServer, Request, Response } from "std/http"
const app = createServer()
// 100 requests per minute per IPconst limiter = rateLimit.create(100, 60000)
app.use(function(req: Request, res: Response, next: any) { const ip = req.headers["X-Forwarded-For"] const allowed = rateLimit.check(limiter, ip)
if (!allowed) { const remaining = rateLimit.remaining(limiter, ip) res.header("X-RateLimit-Remaining", string(remaining)) res.status(429).json('{"error": "Too many requests"}') return }
next()})
app.get("/api/data", function(req: Request, res: Response): Response { return res.json('{"message": "Hello"}')})
app.listen(3000)