Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(api): rate limit every API request

spacesdrive623aec382e2e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b872807..b2a8e79 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,11 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
### Added
+**API rate limiting**
+- Every API request is rate limited: per network before sign-in is checked, per user after it, and tighter on actions that use YouTube, Instagram or Reddit quota (adding accounts, refreshing, the scheduler trigger) and on Instagram publishing
+- Token bucket, leaking bucket, fixed window, sliding window log and sliding window counter algorithms, counted atomically in Redis with Lua scripts and per server instance in memory when Redis is not configured or not reachable
+- Requests over a limit get `429` with `Retry-After` and a message that says when to try again; every response carries `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset`
+
**Issue tracking for every change**
- Every task is tracked by a GitHub issue that is opened before work starts and closed when it is complete; commits reference it with `Refs #N` or `Closes #N`
- Issue templates, a pull request template and `docs/workflows/ISSUES.md` describe the lifecycle, labels and `gh` commands
diff --git a/DECISIONS.md b/DECISIONS.md
index a776062..2ec545c 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -607,3 +607,20 @@ Records every significant architectural decision, the alternatives considered, a
- Shared packages are hoisted to the root `node_modules`, so a script can resolve a package its own workspace does not declare. Declaring dependencies in the workspace that uses them stays a review rule, not something npm enforces.
- Prettier is configured but the existing code was not reformatted in bulk, to keep history readable; nothing enforces formatting until someone runs `npm run format` in its own commit.
- Tests import source through longer relative paths (`../../services/...`) in exchange for a source tree that holds only code that ships.
+
+---
+
+## ADR-029: Rate limiting in the Worker with Redis Lua scripts and an in-memory fallback
+
+**Date:** 2026-10-14
+**Status:** Accepted
+
+**Decision:** Every `/api` request passes Hono middleware (`backend/middleware/rateLimit.ts`) that applies named rules from `backend/lib/rateLimit/rules.ts`: per client IP before authentication (sliding window counter, 300 per minute), per user after it (token bucket, bursts of 120, 2 per second), per user on routes that spend platform API quota (sliding window log, 30 per 10 minutes), per user on Instagram publishing (leaking bucket, 50 deep, 1 per 15 seconds), and per IP on the public OAuth callback (fixed window, 10 per 10 minutes). Each of the five algorithms is a pure TypeScript function and an equivalent Lua script. With Upstash Redis the script runs atomically (`EVALSHA`, falling back to `EVAL`), with the clock passed in as an argument. Without Redis, or after a Redis failure, the TypeScript function runs against a per-isolate memory store. Limited responses return `429` with `Retry-After`, `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset`, and CORS exposes those headers.
+
+**Context:** Nothing limited the API. Cloudflare's WAF rate limiting rules need a zone the owner controls, which a `workers.dev` Worker does not have, and the Workers rate limiting binding counts per location, only supports 10 or 60 second periods and needs Wrangler 4. One client could spend the shared YouTube quota, hit Instagram's limits for every account, or flood Supabase Auth with invalid tokens. `@upstash/ratelimit` would add a runtime dependency to the Worker, which the project avoids.
+
+**Trade-offs:**
+- Each protected request makes two Redis script calls. A per-isolate deny cache answers clients that are already over their limit without Redis, and the limiter uses its own Upstash client with no retries and a 1 second timeout, then skips Redis for 30 seconds in that isolate after a failure, so a Redis outage cannot slow the API.
+- Without Redis the limits are per isolate, which is looser than a global count. Rate limiting is still on, not off.
+- The Lua scripts and the TypeScript functions must change together. Bucket levels are rounded to a millionth so the two agree exactly; they were checked against each other in a Lua VM on 110,000 random requests.
+- Behind a shared IP (an office or a carrier NAT), many users share the `ip` rule. Its limit is high for that reason, and IPv6 is keyed per /64.
diff --git a/backend/lib/rateLimit/algorithms.ts b/backend/lib/rateLimit/algorithms.ts
new file mode 100644
index 0000000..5254ff4
--- /dev/null
+++ b/backend/lib/rateLimit/algorithms.ts
@@ -0,0 +1,218 @@
+// The in-memory twin of the Lua scripts in scripts.ts: same state, same decisions, same numbers.
+
+export type Algorithm =
+ | 'tokenBucket'
+ | 'leakingBucket'
+ | 'fixedWindow'
+ | 'slidingWindowLog'
+ | 'slidingWindowCounter';
+
+export interface TokenBucketConfig {
+ algorithm: 'tokenBucket';
+ capacity: number;
+ refillPerSecond: number;
+}
+
+// a leaking bucket used as a meter: the Worker cannot queue requests, so a full bucket rejects
+export interface LeakingBucketConfig {
+ algorithm: 'leakingBucket';
+ capacity: number;
+ leakPerSecond: number;
+}
+
+export interface FixedWindowConfig {
+ algorithm: 'fixedWindow';
+ limit: number;
+ windowMs: number;
+}
+
+export interface SlidingWindowLogConfig {
+ algorithm: 'slidingWindowLog';
+ limit: number;
+ windowMs: number;
+}
+
+export interface SlidingWindowCounterConfig {
+ algorithm: 'slidingWindowCounter';
+ limit: number;
+ windowMs: number;
+}
+
+export type LimitConfig =
+ | TokenBucketConfig
+ | LeakingBucketConfig
+ | FixedWindowConfig
+ | SlidingWindowLogConfig
+ | SlidingWindowCounterConfig;
+
+export interface Decision {
+ allowed: boolean;
+ limit: number;
+ remaining: number;
+ // until the limiter is back to its full allowance
+ resetMs: number;
+ // until the next request would be allowed; 0 when this one was
+ retryAfterMs: number;
+}
+
+export interface BucketState {
+ level: number;
+ updatedAt: number;
+}
+
+export interface FixedWindowState {
+ window: number;
+ count: number;
+}
+
+export interface SlidingLogState {
+ timestamps: number[];
+}
+
+export interface SlidingCounterState {
+ window: number;
+ current: number;
+ previous: number;
+}
+
+export type LimiterState = BucketState | FixedWindowState | SlidingLogState | SlidingCounterState;
+
+export interface Step<S extends LimiterState> {
+ state: S;
+ decision: Decision;
+ // how long the state must be kept for the next decision to be correct
+ ttlMs: number;
+}
+
+// Bucket levels are rounded to a millionth after every step. Redis stores them as text, and a
+// rounded value survives that round trip exactly, so this file and the Lua scripts never disagree.
+export function roundLevel(level: number): number {
+ return Math.floor(level * 1e6 + 0.5) / 1e6;
+}
+
+export function limitOf(config: LimitConfig): number {
+ return config.algorithm === 'tokenBucket' || config.algorithm === 'leakingBucket' ? config.capacity : config.limit;
+}
+
+// level counts tokens left
+export function tokenBucket(state: BucketState | undefined, now: number, config: TokenBucketConfig): Step<BucketState> {
+ const { capacity, refillPerSecond } = config;
+ const ratePerMs = refillPerSecond / 1000;
+ const previous = state ?? { level: capacity, updatedAt: now };
+ let tokens = roundLevel(Math.min(capacity, previous.level + Math.max(0, now - previous.updatedAt) * ratePerMs));
+ const allowed = tokens >= 1;
+ if (allowed) tokens = roundLevel(tokens - 1);
+ const retryAfterMs = allowed ? 0 : Math.ceil((1 - tokens) / ratePerMs);
+ const resetMs = Math.ceil((capacity - tokens) / ratePerMs);
+ return {
+ state: { level: tokens, updatedAt: now },
+ decision: { allowed, limit: capacity, remaining: Math.floor(tokens), resetMs, retryAfterMs },
+ ttlMs: Math.max(resetMs, 1000),
+ };
+}
+
+// level counts requests still draining out
+export function leakingBucket(state: BucketState | undefined, now: number, config: LeakingBucketConfig): Step<BucketState> {
+ const { capacity, leakPerSecond } = config;
+ const ratePerMs = leakPerSecond / 1000;
+ const previous = state ?? { level: 0, updatedAt: now };
+ let level = roundLevel(Math.max(0, previous.level - Math.max(0, now - previous.updatedAt) * ratePerMs));
+ const allowed = level + 1 <= capacity;
+ if (allowed) level = roundLevel(level + 1);
+ const retryAfterMs = allowed ? 0 : Math.ceil((level + 1 - capacity) / ratePerMs);
+ const resetMs = Math.ceil(level / ratePerMs);
+ return {
+ state: { level, updatedAt: now },
+ decision: { allowed, limit: capacity, remaining: Math.floor(capacity - level), resetMs, retryAfterMs },
+ ttlMs: Math.max(resetMs, 1000),
+ };
+}
+
+export function fixedWindow(state: FixedWindowState | undefined, now: number, config: FixedWindowConfig): Step<FixedWindowState> {
+ const { limit, windowMs } = config;
+ const window = Math.floor(now / windowMs);
+ const count = (state && state.window === window ? state.count : 0) + 1;
+ const allowed = count <= limit;
+ const resetMs = (window + 1) * windowMs - now;
+ return {
+ state: { window, count },
+ decision: { allowed, limit, remaining: Math.max(0, limit - count), resetMs, retryAfterMs: allowed ? 0 : resetMs },
+ ttlMs: resetMs,
+ };
+}
+
+// only accepted requests are logged, so the log never holds more than `limit` entries
+export function slidingWindowLog(state: SlidingLogState | undefined, now: number, config: SlidingWindowLogConfig): Step<SlidingLogState> {
+ const { limit, windowMs } = config;
+ const timestamps = (state?.timestamps ?? []).filter(timestamp => timestamp > now - windowMs);
+ const allowed = timestamps.length < limit;
+ if (allowed) timestamps.push(now);
+ // clocks differ slightly between isolates, so the log is not always in insertion order
+ const oldest = timestamps.length ? Math.min(...timestamps) : now;
+ const newest = timestamps.length ? Math.max(...timestamps) : now;
+ return {
+ state: { timestamps },
+ decision: {
+ allowed,
+ limit,
+ remaining: limit - timestamps.length,
+ resetMs: newest + windowMs - now,
+ retryAfterMs: allowed ? 0 : oldest + windowMs - now,
+ },
+ ttlMs: windowMs,
+ };
+}
+
+// estimate = previous window weighted by its overlap with the sliding window, plus the current window
+export function slidingWindowCounter(state: SlidingCounterState | undefined, now: number, config: SlidingWindowCounterConfig): Step<SlidingCounterState> {
+ const { limit, windowMs } = config;
+ const window = Math.floor(now / windowMs);
+ let current = 0;
+ let previous = 0;
+ if (state && state.window === window) {
+ current = state.current;
+ previous = state.previous;
+ } else if (state && state.window === window - 1) {
+ previous = state.current;
+ }
+ const elapsed = now - window * windowMs;
+ const weight = (windowMs - elapsed) / windowMs;
+ const estimate = previous * weight + current;
+ const allowed = estimate + 1 <= limit;
+ if (allowed) current += 1;
+ const used = previous * weight + current;
+ return {
+ state: { window, current, previous },
+ decision: {
+ allowed,
+ limit,
+ remaining: Math.max(0, Math.floor(limit - used)),
+ resetMs: 2 * windowMs - elapsed,
+ retryAfterMs: allowed ? 0 : slidingCounterRetryMs(previous, current, limit, windowMs, elapsed),
+ },
+ ttlMs: 2 * windowMs,
+ };
+}
+
+// time until previous * (windowMs - t) / windowMs + current drops to limit - 1
+function slidingCounterRetryMs(previous: number, current: number, limit: number, windowMs: number, elapsed: number): number {
+ const untilNextWindow = windowMs - elapsed;
+ if (current + 1 > limit || previous <= 0) return untilNextWindow;
+ const target = windowMs * (1 - (limit - 1 - current) / previous);
+ return Math.min(untilNextWindow, Math.max(1, Math.ceil(target - elapsed)));
+}
+
+export function decide(state: LimiterState | undefined, now: number, config: LimitConfig): Step<LimiterState> {
+ switch (config.algorithm) {
+ case 'tokenBucket':
+ return tokenBucket(state as BucketState | undefined, now, config);
+ case 'leakingBucket':
+ return leakingBucket(state as BucketState | undefined, now, config);
+ case 'fixedWindow':
+ return fixedWindow(state as FixedWindowState | undefined, now, config);
+ case 'slidingWindowLog':
+ return slidingWindowLog(state as SlidingLogState | undefined, now, config);
+ case 'slidingWindowCounter':
+ return slidingWindowCounter(state as SlidingCounterState | undefined, now, config);
+ }
+}
diff --git a/backend/lib/rateLimit/limiter.ts b/backend/lib/rateLimit/limiter.ts
new file mode 100644
index 0000000..656a65f
--- /dev/null
+++ b/backend/lib/rateLimit/limiter.ts
@@ -0,0 +1,83 @@
+import type { Redis } from '@upstash/redis';
+import { limitOf } from './algorithms.ts';
+import type { Decision, LimitConfig } from './algorithms.ts';
+import { MemoryStore, RedisStore } from './stores.ts';
+
+export interface RateLimitRule {
+ name: string;
+ config: LimitConfig;
+ // what the 429 message says was limited
+ label: string;
+}
+
+const MAX_DENIED_KEYS = 10_000;
+
+// Module state lives as long as the isolate. Both maps are best-effort accelerators: losing them
+// only means the next check goes to Redis (or starts a fresh in-memory count).
+const memoryStore = new MemoryStore();
+const deniedUntil = new Map<string, number>();
+
+// after a Redis failure this isolate counts in memory for a while instead of paying the timeout again
+const REDIS_RETRY_AFTER_MS = 30_000;
+let redisDownUntil = 0;
+
+export function rateLimitKey(rule: RateLimitRule, identifier: string): string {
+ return `ratelimit:${rule.name}:${identifier}`;
+}
+
+// A client that is already over the limit is answered from the isolate until its retry time, so a
+// flood of rejected requests costs no Redis commands.
+function cachedDenial(key: string, rule: RateLimitRule, now: number): Decision | null {
+ const until = deniedUntil.get(key);
+ if (until === undefined) return null;
+ if (until <= now) {
+ deniedUntil.delete(key);
+ return null;
+ }
+ return { allowed: false, limit: limitOf(rule.config), remaining: 0, resetMs: until - now, retryAfterMs: until - now };
+}
+
+function rememberDenial(key: string, decision: Decision, now: number): void {
+ if (decision.allowed || decision.retryAfterMs <= 0) return;
+ if (deniedUntil.size >= MAX_DENIED_KEYS) {
+ for (const [deniedKey, until] of deniedUntil) {
+ if (until <= now || deniedUntil.size >= MAX_DENIED_KEYS) deniedUntil.delete(deniedKey);
+ }
+ }
+ deniedUntil.set(key, now + decision.retryAfterMs);
+}
+
+// Redis gives one count across every isolate and location; without it, or when it fails, the
+// same algorithm runs in memory so the API is still limited per isolate instead of not at all.
+export async function checkRateLimit(
+ redis: Redis | null,
+ rule: RateLimitRule,
+ identifier: string,
+ now = Date.now(),
+): Promise<Decision> {
+ const key = rateLimitKey(rule, identifier);
+ const cached = cachedDenial(key, rule, now);
+ if (cached) return cached;
+
+ let decision: Decision;
+ if (redis && now >= redisDownUntil) {
+ try {
+ decision = await new RedisStore(redis).check(key, rule.config, now);
+ } catch (err) {
+ redisDownUntil = now + REDIS_RETRY_AFTER_MS;
+ console.error(`Rate limit ${rule.name}: Redis check failed, counting in memory for 30 seconds:`, (err as Error).message);
+ decision = await memoryStore.check(key, rule.config, now);
+ }
+ } else {
+ decision = await memoryStore.check(key, rule.config, now);
+ }
+
+ rememberDenial(key, decision, now);
+ return decision;
+}
+
+export function resetRateLimitState(): void {
+ deniedUntil.clear();
+ memoryStore.clear();
+ redisDownUntil = 0;
+}
diff --git a/backend/lib/rateLimit/rules.ts b/backend/lib/rateLimit/rules.ts
new file mode 100644
index 0000000..aedb88e
--- /dev/null
+++ b/backend/lib/rateLimit/rules.ts
@@ -0,0 +1,62 @@
+import type { RateLimitRule } from './limiter.ts';
+
+const MINUTE_MS = 60 * 1000;
+
+// Limits are sized for a dashboard: an Overview load fires about 20 requests and Instagram container
+// polling one every 3 seconds. See docs/architecture/backend/RATE_LIMITING.md before changing them.
+export const RATE_LIMIT_RULES = {
+ // before authentication, so invalid tokens cannot flood Supabase auth; counter, not log, to stay O(1)
+ ip: {
+ name: 'ip',
+ label: 'Too many requests from your network',
+ config: { algorithm: 'slidingWindowCounter', limit: 300, windowMs: MINUTE_MS },
+ },
+ // bursts for page loads, then a steady two requests a second
+ user: {
+ name: 'user',
+ label: 'Too many requests',
+ config: { algorithm: 'tokenBucket', capacity: 120, refillPerSecond: 2 },
+ },
+ // these spend the shared YouTube quota and Instagram and Reddit API calls, so the count is exact
+ quota: {
+ name: 'quota',
+ label: 'Too many account changes and refreshes',
+ config: { algorithm: 'slidingWindowLog', limit: 30, windowMs: 10 * MINUTE_MS },
+ },
+ // paces Instagram container and publish calls; Instagram itself allows 100 posts a day
+ publish: {
+ name: 'publish',
+ label: 'Too many publishing requests',
+ config: { algorithm: 'leakingBucket', capacity: 50, leakPerSecond: 1 / 15 },
+ },
+ // the public OAuth callback, per IP
+ oauth: {
+ name: 'oauth',
+ label: 'Too many Instagram sign-in attempts',
+ config: { algorithm: 'fixedWindow', limit: 10, windowMs: 10 * MINUTE_MS },
+ },
+} as const satisfies Record<string, RateLimitRule>;
+
+interface RouteMatcher {
+ methods: readonly string[];
+ path: RegExp;
+}
+
+// paths are matched on the full request path, after the /api prefix
+export const QUOTA_ROUTES: readonly RouteMatcher[] = [
+ { methods: ['POST'], path: /^\/api\/accounts$/ },
+ { methods: ['POST'], path: /^\/api\/accounts\/(reddit|instagram|refresh-all)$/ },
+ { methods: ['POST'], path: /^\/api\/accounts\/[^/]+\/(refresh|refresh-ig-token)$/ },
+ { methods: ['POST'], path: /^\/api\/resolve-channel$/ },
+ { methods: ['POST'], path: /^\/api\/tracked-content$/ },
+ { methods: ['POST'], path: /^\/api\/tracked-content\/[^/]+\/refresh$/ },
+ { methods: ['GET', 'POST'], path: /^\/api\/process-scheduled$/ },
+];
+
+export const PUBLISH_ROUTES: readonly RouteMatcher[] = [
+ { methods: ['POST'], path: /^\/api\/accounts\/[^/]+\/(ig-publish|ig-media-publish)$/ },
+];
+
+export function matchesRoute(routes: readonly RouteMatcher[], method: string, path: string): boolean {
+ return routes.some(route => route.methods.includes(method) && route.path.test(path));
+}
diff --git a/backend/lib/rateLimit/scripts.ts b/backend/lib/rateLimit/scripts.ts
new file mode 100644
index 0000000..ca9ea63
--- /dev/null
+++ b/backend/lib/rateLimit/scripts.ts
@@ -0,0 +1,155 @@
+import type { Algorithm } from './algorithms.ts';
+
+// Each script runs atomically in Redis, so concurrent isolates cannot read the same count and both pass.
+// The caller passes the clock in ARGV[1] (scripts must be deterministic) and gets back
+// { allowed (1 or 0), remaining, resetMs, retryAfterMs }. Logic mirrors algorithms.ts line for line.
+// Lua 5.1 syntax only; every key the script touches is KEYS[1].
+
+// levels are rounded to a millionth, matching roundLevel() in algorithms.ts
+const ROUND_LEVEL = `
+local function roundLevel(level)
+ return math.floor(level * 1e6 + 0.5) / 1e6
+end
+`;
+
+const TOKEN_BUCKET = `${ROUND_LEVEL}
+local now = tonumber(ARGV[1])
+local capacity = tonumber(ARGV[2])
+local rate = tonumber(ARGV[3]) / 1000
+local saved = redis.call('HMGET', KEYS[1], 'level', 'updatedAt')
+local tokens = capacity
+local updatedAt = now
+if saved[1] then
+ tokens = tonumber(saved[1])
+ updatedAt = tonumber(saved[2])
+end
+tokens = roundLevel(math.min(capacity, tokens + math.max(0, now - updatedAt) * rate))
+local allowed = 0
+if tokens >= 1 then
+ tokens = roundLevel(tokens - 1)
+ allowed = 1
+end
+local retryAfter = 0
+if allowed == 0 then retryAfter = math.ceil((1 - tokens) / rate) end
+local reset = math.ceil((capacity - tokens) / rate)
+redis.call('HSET', KEYS[1], 'level', tostring(tokens), 'updatedAt', tostring(now))
+redis.call('PEXPIRE', KEYS[1], math.max(reset, 1000))
+return { allowed, math.floor(tokens), reset, retryAfter }
+`;
+
+const LEAKING_BUCKET = `${ROUND_LEVEL}
+local now = tonumber(ARGV[1])
+local capacity = tonumber(ARGV[2])
+local rate = tonumber(ARGV[3]) / 1000
+local saved = redis.call('HMGET', KEYS[1], 'level', 'updatedAt')
+local level = 0
+local updatedAt = now
+if saved[1] then
+ level = tonumber(saved[1])
+ updatedAt = tonumber(saved[2])
+end
+level = roundLevel(math.max(0, level - math.max(0, now - updatedAt) * rate))
+local allowed = 0
+if level + 1 <= capacity then
+ level = roundLevel(level + 1)
+ allowed = 1
+end
+local retryAfter = 0
+if allowed == 0 then retryAfter = math.ceil((level + 1 - capacity) / rate) end
+local reset = math.ceil(level / rate)
+redis.call('HSET', KEYS[1], 'level', tostring(level), 'updatedAt', tostring(now))
+redis.call('PEXPIRE', KEYS[1], math.max(reset, 1000))
+return { allowed, math.floor(capacity - level), reset, retryAfter }
+`;
+
+const FIXED_WINDOW = `
+local now = tonumber(ARGV[1])
+local limit = tonumber(ARGV[2])
+local windowMs = tonumber(ARGV[3])
+local window = math.floor(now / windowMs)
+local saved = redis.call('HMGET', KEYS[1], 'window', 'count')
+local count = 1
+if saved[1] and tonumber(saved[1]) == window then count = tonumber(saved[2]) + 1 end
+local allowed = 0
+if count <= limit then allowed = 1 end
+local reset = (window + 1) * windowMs - now
+local retryAfter = 0
+if allowed == 0 then retryAfter = reset end
+redis.call('HSET', KEYS[1], 'window', tostring(window), 'count', tostring(count))
+redis.call('PEXPIRE', KEYS[1], reset)
+return { allowed, math.max(0, limit - count), reset, retryAfter }
+`;
+
+// ARGV[4] is a unique member so two requests in the same millisecond are both logged
+const SLIDING_WINDOW_LOG = `
+local now = tonumber(ARGV[1])
+local limit = tonumber(ARGV[2])
+local windowMs = tonumber(ARGV[3])
+redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now - windowMs)
+local count = redis.call('ZCARD', KEYS[1])
+local allowed = 0
+if count < limit then
+ redis.call('ZADD', KEYS[1], now, ARGV[4])
+ count = count + 1
+ allowed = 1
+end
+local oldest = now
+local newest = now
+local first = redis.call('ZRANGE', KEYS[1], 0, 0, 'WITHSCORES')
+local last = redis.call('ZRANGE', KEYS[1], -1, -1, 'WITHSCORES')
+if first[2] then oldest = tonumber(first[2]) end
+if last[2] then newest = tonumber(last[2]) end
+local retryAfter = 0
+if allowed == 0 then retryAfter = oldest + windowMs - now end
+redis.call('PEXPIRE', KEYS[1], windowMs)
+return { allowed, limit - count, newest + windowMs - now, retryAfter }
+`;
+
+const SLIDING_WINDOW_COUNTER = `
+local now = tonumber(ARGV[1])
+local limit = tonumber(ARGV[2])
+local windowMs = tonumber(ARGV[3])
+local window = math.floor(now / windowMs)
+local saved = redis.call('HMGET', KEYS[1], 'window', 'current', 'previous')
+local current = 0
+local previous = 0
+if saved[1] then
+ local savedWindow = tonumber(saved[1])
+ if savedWindow == window then
+ current = tonumber(saved[2])
+ previous = tonumber(saved[3])
+ elseif savedWindow == window - 1 then
+ previous = tonumber(saved[2])
+ end
+end
+local elapsed = now - window * windowMs
+local weight = (windowMs - elapsed) / windowMs
+local estimate = previous * weight + current
+local allowed = 0
+if estimate + 1 <= limit then
+ current = current + 1
+ allowed = 1
+end
+local used = previous * weight + current
+local retryAfter = 0
+if allowed == 0 then
+ local untilNextWindow = windowMs - elapsed
+ if current + 1 > limit or previous <= 0 then
+ retryAfter = untilNextWindow
+ else
+ local target = windowMs * (1 - (limit - 1 - current) / previous)
+ retryAfter = math.min(untilNextWindow, math.max(1, math.ceil(target - elapsed)))
+ end
+end
+redis.call('HSET', KEYS[1], 'window', tostring(window), 'current', tostring(current), 'previous', tostring(previous))
+redis.call('PEXPIRE', KEYS[1], 2 * windowMs)
+return { allowed, math.max(0, math.floor(limit - used)), 2 * windowMs - elapsed, retryAfter }
+`;
+
+export const LUA_SCRIPTS: Record<Algorithm, string> = {
+ tokenBucket: TOKEN_BUCKET,
+ leakingBucket: LEAKING_BUCKET,
+ fixedWindow: FIXED_WINDOW,
+ slidingWindowLog: SLIDING_WINDOW_LOG,
+ slidingWindowCounter: SLIDING_WINDOW_COUNTER,
+};
diff --git a/backend/lib/rateLimit/stores.ts b/backend/lib/rateLimit/stores.ts
new file mode 100644
index 0000000..8042b23
--- /dev/null
+++ b/backend/lib/rateLimit/stores.ts
@@ -0,0 +1,85 @@
+import type { Redis } from '@upstash/redis';
+import { decide, limitOf } from './algorithms.ts';
+import type { Decision, LimitConfig, LimiterState } from './algorithms.ts';
+import { LUA_SCRIPTS } from './scripts.ts';
+
+export interface RateLimitStore {
+ check(key: string, config: LimitConfig, now: number): Promise<Decision>;
+}
+
+interface MemoryEntry {
+ state: LimiterState;
+ expiresAt: number;
+}
+
+const DEFAULT_MAX_ENTRIES = 10_000;
+
+// Per isolate: Cloudflare runs many isolates, so these counts are local, not global.
+export class MemoryStore implements RateLimitStore {
+ private readonly entries = new Map<string, MemoryEntry>();
+ private readonly maxEntries: number;
+
+ constructor(maxEntries = DEFAULT_MAX_ENTRIES) {
+ this.maxEntries = maxEntries;
+ }
+
+ async check(key: string, config: LimitConfig, now: number): Promise<Decision> {
+ const entry = this.entries.get(key);
+ const previous = entry && entry.expiresAt > now ? entry.state : undefined;
+ const { state, decision, ttlMs } = decide(previous, now, config);
+ this.entries.delete(key);
+ this.entries.set(key, { state, expiresAt: now + ttlMs });
+ this.evict(now);
+ return decision;
+ }
+
+ get size(): number {
+ return this.entries.size;
+ }
+
+ clear(): void {
+ this.entries.clear();
+ }
+
+ // expired entries go first, then the least recently used (Map keeps insertion order)
+ private evict(now: number): void {
+ if (this.entries.size <= this.maxEntries) return;
+ for (const [key, entry] of this.entries) {
+ if (entry.expiresAt <= now) this.entries.delete(key);
+ }
+ for (const key of this.entries.keys()) {
+ if (this.entries.size <= this.maxEntries) break;
+ this.entries.delete(key);
+ }
+ }
+}
+
+type ScriptResult = [number, number, number, number];
+
+export class RedisStore implements RateLimitStore {
+ private readonly redis: Redis;
+
+ constructor(redis: Redis) {
+ this.redis = redis;
+ }
+
+ async check(key: string, config: LimitConfig, now: number): Promise<Decision> {
+ const script = this.redis.createScript<ScriptResult>(LUA_SCRIPTS[config.algorithm]);
+ const [allowed, remaining, resetMs, retryAfterMs] = await script.exec([key], scriptArgs(config, now));
+ return { allowed: allowed === 1, limit: limitOf(config), remaining, resetMs, retryAfterMs };
+ }
+}
+
+export function scriptArgs(config: LimitConfig, now: number): string[] {
+ switch (config.algorithm) {
+ case 'tokenBucket':
+ return [String(now), String(config.capacity), String(config.refillPerSecond)];
+ case 'leakingBucket':
+ return [String(now), String(config.capacity), String(config.leakPerSecond)];
+ case 'slidingWindowLog':
+ return [String(now), String(config.limit), String(config.windowMs), `${now}-${crypto.randomUUID()}`];
+ case 'fixedWindow':
+ case 'slidingWindowCounter':
+ return [String(now), String(config.limit), String(config.windowMs)];
+ }
+}
diff --git a/backend/lib/redis.ts b/backend/lib/redis.ts
index d808f43..d13d64c 100644
--- a/backend/lib/redis.ts
+++ b/backend/lib/redis.ts
@@ -1,9 +1,24 @@
import { Redis } from '@upstash/redis';
import type { Env } from '../types/env.ts';
-export function getRedis(env: Env): Redis | null {
+const RATE_LIMIT_TIMEOUT_MS = 1000;
+
+function credentials(env: Env): { url: string; token: string } | null {
const url = env.UPSTASH_REDIS_REST_URL?.replace(/^\uFEFF/, '').trim();
const token = env.UPSTASH_REDIS_REST_TOKEN?.replace(/^\uFEFF/, '').trim();
if (!url || !token) return null;
- return new Redis({ url, token });
+ return { url, token };
+}
+
+export function getRedis(env: Env): Redis | null {
+ const config = credentials(env);
+ return config ? new Redis(config) : null;
+}
+
+// Every request waits on the rate limit check, so it fails fast instead of using the
+// default five retries (about 4 seconds); the limiter then counts in memory.
+export function getRateLimitRedis(env: Env): Redis | null {
+ const config = credentials(env);
+ if (!config) return null;
+ return new Redis({ ...config, retry: false, signal: () => AbortSignal.timeout(RATE_LIMIT_TIMEOUT_MS) });
}
diff --git a/backend/middleware/rateLimit.ts b/backend/middleware/rateLimit.ts
new file mode 100644
index 0000000..5e9f948
--- /dev/null
+++ b/backend/middleware/rateLimit.ts
@@ -0,0 +1,82 @@
+import type { MiddlewareHandler } from 'hono';
+import { checkRateLimit } from '../lib/rateLimit/limiter.ts';
+import type { RateLimitRule } from '../lib/rateLimit/limiter.ts';
+import type { Decision } from '../lib/rateLimit/algorithms.ts';
+import type { AppContext, AppEnv } from '../types/app.ts';
+
+export const RATE_LIMIT_HEADERS = ['RateLimit-Limit', 'RateLimit-Remaining', 'RateLimit-Reset', 'Retry-After'];
+
+type Identify = (c: AppContext) => string | null;
+
+// Cloudflare sets CF-Connecting-IP on every request. IPv6 clients usually own a whole /64, so the
+// limit applies to the /64 rather than to one address they can rotate within it.
+export function clientIp(c: AppContext): string | null {
+ const ip = c.req.header('CF-Connecting-IP')?.trim();
+ if (!ip) return null;
+ // an IPv4-mapped IPv6 address (::ffff:203.0.113.7) is limited as the IPv4 address it carries
+ if (ip.includes('.')) return ip.slice(ip.lastIndexOf(':') + 1);
+ return ip.includes(':') ? ipv6Prefix(ip) : ip;
+}
+
+function ipv6Prefix(ip: string): string {
+ const [head, tail = ''] = ip.split('::');
+ const headGroups = head ? head.split(':') : [];
+ const tailGroups = ip.includes('::') && tail ? tail.split(':') : [];
+ const missing = Math.max(0, 8 - headGroups.length - tailGroups.length);
+ const groups = [...headGroups, ...Array<string>(missing).fill('0'), ...tailGroups];
+ return `${groups.slice(0, 4).map(group => group.toLowerCase().replace(/^0+(?=.)/, '')).join(':')}::/64`;
+}
+
+export function userKey(c: AppContext): string | null {
+ return c.get('userId') ?? null;
+}
+
+function seconds(ms: number): number {
+ return Math.max(1, Math.ceil(ms / 1000));
+}
+
+function retryWording(ms: number): string {
+ const secs = seconds(ms);
+ if (secs < 90) return `${secs} second${secs === 1 ? '' : 's'}`;
+ const minutes = Math.ceil(secs / 60);
+ return `${minutes} minute${minutes === 1 ? '' : 's'}`;
+}
+
+function setHeaders(headers: Headers, decision: Decision): void {
+ headers.set('RateLimit-Limit', String(decision.limit));
+ headers.set('RateLimit-Remaining', String(decision.remaining));
+ headers.set('RateLimit-Reset', String(seconds(decision.resetMs)));
+}
+
+// several rules can apply to one request; the response reports whichever has the least left
+function isTighter(headers: Headers, decision: Decision): boolean {
+ const current = headers.get('RateLimit-Remaining');
+ return current === null || decision.remaining < Number(current);
+}
+
+export function rateLimit(rule: RateLimitRule, identify: Identify, applies?: (c: AppContext) => boolean): MiddlewareHandler<AppEnv> {
+ return async (c, next) => {
+ if (applies && !applies(c)) return next();
+ const identifier = identify(c);
+ if (!identifier) return next();
+
+ const decision = await checkRateLimit(c.get('rateLimitRedis'), rule, identifier);
+ if (!decision.allowed) {
+ const response = c.json({
+ success: false,
+ error: `${rule.label} - try again in ${retryWording(decision.retryAfterMs)}.`,
+ retryAfter: seconds(decision.retryAfterMs),
+ }, 429);
+ setHeaders(response.headers, decision);
+ response.headers.set('Retry-After', String(seconds(decision.retryAfterMs)));
+ return response;
+ }
+
+ await next();
+ try {
+ if (isTighter(c.res.headers, decision)) setHeaders(c.res.headers, decision);
+ } catch {
+ // a response with immutable headers is sent without the rate limit headers
+ }
+ };
+}
diff --git a/backend/server.ts b/backend/server.ts
index 7055e10..85cb510 100644
--- a/backend/server.ts
+++ b/backend/server.ts
@@ -1,8 +1,10 @@
import { Hono } from 'hono';
import { cors } from 'hono/cors';
import { getSupabase } from './lib/supabase.ts';
-import { getRedis } from './lib/redis.ts';
+import { getRedis, getRateLimitRedis } from './lib/redis.ts';
import { requireAuth } from './middleware/auth.ts';
+import { rateLimit, clientIp, userKey, RATE_LIMIT_HEADERS } from './middleware/rateLimit.ts';
+import { RATE_LIMIT_RULES, QUOTA_ROUTES, PUBLISH_ROUTES, matchesRoute } from './lib/rateLimit/rules.ts';
import keysRouter from './routes/keys.ts';
import accountsRouter from './routes/accounts.ts';
import analyticsRouter from './routes/analytics.ts';
@@ -26,22 +28,30 @@ app.onError((err, c) => {
return c.json({ error: 'Internal server error' }, 500);
});
-app.use('*', cors());
+// the browser may only read the rate limit headers when CORS exposes them
+app.use('*', cors({ exposeHeaders: RATE_LIMIT_HEADERS }));
// both clients are stateless http clients, so creating them per request is safe
app.use('*', async (c, next) => {
c.set('supabase', getSupabase(c.env));
c.set('redis', getRedis(c.env));
+ c.set('rateLimitRedis', getRateLimitRedis(c.env));
await next();
});
+// before authentication, so a flood of bad tokens never reaches Supabase auth
+app.use('/api/*', rateLimit(RATE_LIMIT_RULES.ip, clientIp));
+
app.get('/api/health', (c) => c.json({ status: 'ok', timestamp: new Date().toISOString() }));
// public: the oauth redirect has no jwt; the signed hmac state names the user
-app.get('/api/auth/instagram/callback', callbackHandler);
+app.get('/api/auth/instagram/callback', rateLimit(RATE_LIMIT_RULES.oauth, clientIp), callbackHandler);
const api = new Hono<AppEnv>();
api.use('*', requireAuth);
+api.use('*', rateLimit(RATE_LIMIT_RULES.user, userKey));
+api.use('*', rateLimit(RATE_LIMIT_RULES.quota, userKey, c => matchesRoute(QUOTA_ROUTES, c.req.method, c.req.path)));
+api.use('*', rateLimit(RATE_LIMIT_RULES.publish, userKey, c => matchesRoute(PUBLISH_ROUTES, c.req.method, c.req.path)));
api.route('/', keysRouter);
api.route('/', accountsRouter);
diff --git a/backend/tests/lib/rateLimit/algorithms.test.ts b/backend/tests/lib/rateLimit/algorithms.test.ts
new file mode 100644
index 0000000..3da629e
--- /dev/null
+++ b/backend/tests/lib/rateLimit/algorithms.test.ts
@@ -0,0 +1,145 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import {
+ tokenBucket, leakingBucket, fixedWindow, slidingWindowLog, slidingWindowCounter, decide,
+} from '../../../lib/rateLimit/algorithms.ts';
+import type {
+ BucketState, Decision, FixedWindowState, LimitConfig, LimiterState, SlidingCounterState, SlidingLogState,
+} from '../../../lib/rateLimit/algorithms.ts';
+
+// runs requests at the given times through one algorithm, threading state like a store does
+function run(config: LimitConfig, times: number[]): Decision[] {
+ let state: LimiterState | undefined;
+ return times.map(now => {
+ const step = decide(state, now, config);
+ state = step.state;
+ return step.decision;
+ });
+}
+
+const allowedFlags = (decisions: Decision[]) => decisions.map(decision => decision.allowed);
+
+test('token bucket allows a burst up to capacity, then refills at the set rate', () => {
+ const config = { algorithm: 'tokenBucket', capacity: 3, refillPerSecond: 1 } as const;
+ const decisions = run(config, [0, 0, 0, 0, 999, 1000, 1000]);
+ assert.deepEqual(allowedFlags(decisions), [true, true, true, false, false, true, false]);
+ assert.deepEqual(decisions.map(decision => decision.remaining), [2, 1, 0, 0, 0, 0, 0]);
+ assert.equal(decisions[3].retryAfterMs, 1000);
+ // 0.999 tokens leave about 1ms; floating point can round that up to 2
+ assert.ok(decisions[4].retryAfterMs >= 1 && decisions[4].retryAfterMs <= 2);
+ assert.equal(decisions[0].resetMs, 1000);
+});
+
+test('token bucket never holds more than its capacity after a long idle period', () => {
+ const config = { algorithm: 'tokenBucket', capacity: 2, refillPerSecond: 10 } as const;
+ const step = tokenBucket({ level: 0, updatedAt: 0 }, 1_000_000, config);
+ assert.equal(step.state.level, 1);
+ assert.equal(step.decision.remaining, 1);
+});
+
+test('token bucket treats a clock that moved backwards as no time passed', () => {
+ const config = { algorithm: 'tokenBucket', capacity: 5, refillPerSecond: 1 } as const;
+ const step = tokenBucket({ level: 2, updatedAt: 10_000 }, 9_000, config);
+ assert.equal(step.state.level, 1);
+});
+
+test('leaking bucket accepts until full, then one request per leak interval', () => {
+ const config = { algorithm: 'leakingBucket', capacity: 2, leakPerSecond: 0.5 } as const;
+ const decisions = run(config, [0, 0, 0, 1999, 2000, 2000]);
+ assert.deepEqual(allowedFlags(decisions), [true, true, false, false, true, false]);
+ assert.equal(decisions[2].retryAfterMs, 2000);
+ assert.equal(decisions[1].resetMs, 4000);
+ assert.deepEqual(decisions.map(decision => decision.remaining), [1, 0, 0, 0, 0, 0]);
+});
+
+test('leaking bucket empties completely after level / rate', () => {
+ const config = { algorithm: 'leakingBucket', capacity: 3, leakPerSecond: 1 } as const;
+ const step = leakingBucket({ level: 3, updatedAt: 0 }, 3000, config);
+ assert.equal(step.decision.allowed, true);
+ assert.equal(step.state.level, 1);
+});
+
+test('fixed window counts per aligned window and resets at the boundary', () => {
+ const config = { algorithm: 'fixedWindow', limit: 2, windowMs: 1000 } as const;
+ const decisions = run(config, [100, 200, 300, 999, 1000, 1001, 1500]);
+ assert.deepEqual(allowedFlags(decisions), [true, true, false, false, true, true, false]);
+ assert.equal(decisions[2].retryAfterMs, 700);
+ assert.equal(decisions[2].resetMs, 700);
+ assert.equal(decisions[6].remaining, 0);
+});
+
+test('fixed window lets a burst straddle the boundary (the known weakness)', () => {
+ const config = { algorithm: 'fixedWindow', limit: 3, windowMs: 1000 } as const;
+ const decisions = run(config, [997, 998, 999, 1000, 1001, 1002]);
+ assert.equal(allowedFlags(decisions).filter(Boolean).length, 6);
+});
+
+test('sliding window log never allows more than the limit in any rolling window', () => {
+ const config = { algorithm: 'slidingWindowLog', limit: 3, windowMs: 1000 } as const;
+ const decisions = run(config, [997, 998, 999, 1000, 1001, 1002, 1997, 1998]);
+ assert.deepEqual(allowedFlags(decisions), [true, true, true, false, false, false, true, true]);
+ assert.equal(decisions[3].retryAfterMs, 997);
+ assert.equal(decisions[2].resetMs, 1000);
+});
+
+test('sliding window log only stores accepted requests', () => {
+ const config = { algorithm: 'slidingWindowLog', limit: 2, windowMs: 1000 } as const;
+ let state: SlidingLogState | undefined;
+ for (let now = 0; now < 50; now++) state = slidingWindowLog(state, now, config).state;
+ assert.deepEqual(state?.timestamps, [0, 1]);
+});
+
+test('sliding window counter weights the previous window by its overlap', () => {
+ const config = { algorithm: 'slidingWindowCounter', limit: 10, windowMs: 1000 } as const;
+ // 8 requests in the previous window, now 25% into the current one: estimate = 8 * 0.75 = 6
+ const previous: SlidingCounterState = { window: 0, current: 8, previous: 0 };
+ const step = slidingWindowCounter(previous, 1250, config);
+ assert.equal(step.decision.allowed, true);
+ assert.deepEqual(step.state, { window: 1, current: 1, previous: 8 });
+ assert.equal(step.decision.remaining, 3);
+});
+
+test('sliding window counter rejects when the estimate is at the limit and says when it frees up', () => {
+ const config = { algorithm: 'slidingWindowCounter', limit: 10, windowMs: 1000 } as const;
+ // estimate at 500ms: 10 * 0.5 + 5 = 10, so the next request waits until 10 * (1 - t) + 5 <= 9
+ const step = slidingWindowCounter({ window: 1, current: 5, previous: 10 }, 1500, config);
+ assert.equal(step.decision.allowed, false);
+ assert.equal(step.decision.retryAfterMs, 100);
+ const later = slidingWindowCounter(step.state, 1600, config);
+ assert.equal(later.decision.allowed, true);
+});
+
+test('sliding window counter forgets windows older than the previous one', () => {
+ const config = { algorithm: 'slidingWindowCounter', limit: 2, windowMs: 1000 } as const;
+ const step = slidingWindowCounter({ window: 0, current: 2, previous: 2 }, 2100, config);
+ assert.deepEqual(step.state, { window: 2, current: 1, previous: 0 });
+});
+
+test('sliding window counter waits for the next window when the current one alone is full', () => {
+ const config = { algorithm: 'slidingWindowCounter', limit: 2, windowMs: 1000 } as const;
+ const step = slidingWindowCounter({ window: 1, current: 2, previous: 0 }, 1300, config);
+ assert.equal(step.decision.allowed, false);
+ assert.equal(step.decision.retryAfterMs, 700);
+});
+
+test('every algorithm keeps state at least until its decision could change', () => {
+ const configs: LimitConfig[] = [
+ { algorithm: 'tokenBucket', capacity: 5, refillPerSecond: 1 },
+ { algorithm: 'leakingBucket', capacity: 5, leakPerSecond: 1 },
+ { algorithm: 'fixedWindow', limit: 5, windowMs: 1000 },
+ { algorithm: 'slidingWindowLog', limit: 5, windowMs: 1000 },
+ { algorithm: 'slidingWindowCounter', limit: 5, windowMs: 1000 },
+ ];
+ for (const config of configs) {
+ const step = decide(undefined, 400, config);
+ assert.ok(step.ttlMs >= step.decision.resetMs, `${config.algorithm} ttl ${step.ttlMs} < reset ${step.decision.resetMs}`);
+ assert.ok(step.ttlMs > 0);
+ }
+});
+
+test('the helpers return the state type each store saves', () => {
+ const bucket: BucketState = tokenBucket(undefined, 0, { algorithm: 'tokenBucket', capacity: 1, refillPerSecond: 1 }).state;
+ const window: FixedWindowState = fixedWindow(undefined, 0, { algorithm: 'fixedWindow', limit: 1, windowMs: 10 }).state;
+ assert.deepEqual(bucket, { level: 0, updatedAt: 0 });
+ assert.deepEqual(window, { window: 0, count: 1 });
+});
diff --git a/backend/tests/lib/rateLimit/limiter.test.ts b/backend/tests/lib/rateLimit/limiter.test.ts
new file mode 100644
index 0000000..5431593
--- /dev/null
+++ b/backend/tests/lib/rateLimit/limiter.test.ts
@@ -0,0 +1,130 @@
+import { test, beforeEach } from 'node:test';
+import assert from 'node:assert/strict';
+import type { Redis } from '@upstash/redis';
+import { checkRateLimit, rateLimitKey, resetRateLimitState } from '../../../lib/rateLimit/limiter.ts';
+import type { RateLimitRule } from '../../../lib/rateLimit/limiter.ts';
+import { MemoryStore, scriptArgs } from '../../../lib/rateLimit/stores.ts';
+import { LUA_SCRIPTS } from '../../../lib/rateLimit/scripts.ts';
+
+const rule: RateLimitRule = {
+ name: 'test',
+ label: 'Too many test requests',
+ config: { algorithm: 'fixedWindow', limit: 2, windowMs: 1000 },
+};
+
+interface ScriptCall {
+ script: string;
+ keys: string[];
+ args: string[];
+}
+
+// a Redis double that records script calls and answers with a scripted result or error
+function scriptedRedis(answer: (call: ScriptCall) => [number, number, number, number]): { redis: Redis; calls: ScriptCall[] } {
+ const calls: ScriptCall[] = [];
+ const redis = {
+ createScript(script: string) {
+ return {
+ async exec(keys: string[], args: string[]) {
+ const call = { script, keys, args };
+ calls.push(call);
+ return answer(call);
+ },
+ };
+ },
+ };
+ return { redis: redis as unknown as Redis, calls };
+}
+
+beforeEach(() => resetRateLimitState());
+
+test('keys are namespaced by rule and identifier', () => {
+ assert.equal(rateLimitKey(rule, 'user-1'), 'ratelimit:test:user-1');
+});
+
+test('without Redis the limit is counted in memory', async () => {
+ const results = [];
+ for (let i = 0; i < 3; i++) results.push(await checkRateLimit(null, rule, 'a', 100));
+ assert.deepEqual(results.map(result => result.allowed), [true, true, false]);
+ assert.equal(results[2].retryAfterMs, 900);
+});
+
+test('identifiers are counted separately', async () => {
+ await checkRateLimit(null, rule, 'a', 100);
+ await checkRateLimit(null, rule, 'a', 100);
+ const other = await checkRateLimit(null, rule, 'b', 100);
+ assert.equal(other.allowed, true);
+});
+
+test('with Redis the decision comes from the algorithm script for that rule', async () => {
+ const { redis, calls } = scriptedRedis(() => [1, 1, 900, 0]);
+ const decision = await checkRateLimit(redis, rule, 'user-1', 100);
+ assert.deepEqual(decision, { allowed: true, limit: 2, remaining: 1, resetMs: 900, retryAfterMs: 0 });
+ assert.equal(calls.length, 1);
+ assert.equal(calls[0].script, LUA_SCRIPTS.fixedWindow);
+ assert.deepEqual(calls[0].keys, ['ratelimit:test:user-1']);
+ assert.deepEqual(calls[0].args, ['100', '2', '1000']);
+});
+
+test('a client that is over the limit is answered from the isolate until its retry time', async () => {
+ const { redis, calls } = scriptedRedis(() => [0, 0, 900, 900]);
+ const first = await checkRateLimit(redis, rule, 'user-1', 100);
+ const cached = await checkRateLimit(redis, rule, 'user-1', 500);
+ assert.equal(first.allowed, false);
+ assert.equal(cached.allowed, false);
+ assert.equal(cached.retryAfterMs, 500);
+ assert.equal(calls.length, 1);
+
+ await checkRateLimit(redis, rule, 'user-1', 1000);
+ assert.equal(calls.length, 2);
+});
+
+test('a Redis failure falls back to counting in memory instead of failing the request', async () => {
+ const { redis, calls } = scriptedRedis(() => { throw new Error('connection refused'); });
+ const originalError = console.error;
+ const logged: unknown[][] = [];
+ console.error = (...args: unknown[]) => { logged.push(args); };
+ try {
+ const results = [];
+ for (let i = 0; i < 3; i++) results.push(await checkRateLimit(redis, rule, 'user-1', 100));
+ assert.deepEqual(results.map(result => result.allowed), [true, true, false]);
+ // one failure opens the circuit, so the next checks skip Redis instead of waiting on it again
+ assert.equal(calls.length, 1);
+ assert.equal(logged.length, 1);
+ assert.match(String(logged[0][0]), /Rate limit test: Redis check failed/);
+
+ await checkRateLimit(redis, rule, 'user-2', 100 + 30_000);
+ assert.equal(calls.length, 2);
+ } finally {
+ console.error = originalError;
+ }
+});
+
+test('script arguments carry the clock and each algorithm parameter', () => {
+ assert.deepEqual(scriptArgs({ algorithm: 'tokenBucket', capacity: 10, refillPerSecond: 0.5 }, 7), ['7', '10', '0.5']);
+ assert.deepEqual(scriptArgs({ algorithm: 'leakingBucket', capacity: 4, leakPerSecond: 2 }, 7), ['7', '4', '2']);
+ assert.deepEqual(scriptArgs({ algorithm: 'slidingWindowCounter', limit: 3, windowMs: 60000 }, 7), ['7', '3', '60000']);
+ const logArgs = scriptArgs({ algorithm: 'slidingWindowLog', limit: 3, windowMs: 60000 }, 7);
+ assert.deepEqual(logArgs.slice(0, 3), ['7', '3', '60000']);
+ assert.match(logArgs[3], /^7-[0-9a-f-]{36}$/);
+});
+
+test('the memory store forgets expired entries and stays within its size cap', async () => {
+ const store = new MemoryStore(3);
+ const config = { algorithm: 'fixedWindow', limit: 1, windowMs: 1000 } as const;
+ for (let i = 0; i < 5; i++) await store.check(`key-${i}`, config, 0);
+ assert.equal(store.size, 3);
+
+ // key-4 was used most recently, so it survived; its window has ended by t=1000
+ const afterWindow = await store.check('key-4', config, 1000);
+ assert.equal(afterWindow.allowed, true);
+});
+
+test('the memory store evicts the least recently used key first', async () => {
+ const store = new MemoryStore(2);
+ const config = { algorithm: 'fixedWindow', limit: 1, windowMs: 10_000 } as const;
+ await store.check('old', config, 0);
+ await store.check('kept', config, 1);
+ await store.check('new', config, 2);
+ assert.equal((await store.check('kept', config, 3)).allowed, false);
+ assert.equal((await store.check('old', config, 4)).allowed, true);
+});
diff --git a/backend/tests/middleware/rateLimit.test.ts b/backend/tests/middleware/rateLimit.test.ts
new file mode 100644
index 0000000..8c7e154
--- /dev/null
+++ b/backend/tests/middleware/rateLimit.test.ts
@@ -0,0 +1,144 @@
+import { test, beforeEach } from 'node:test';
+import assert from 'node:assert/strict';
+import { Hono } from 'hono';
+import { rateLimit, clientIp, userKey } from '../../middleware/rateLimit.ts';
+import { resetRateLimitState } from '../../lib/rateLimit/limiter.ts';
+import type { RateLimitRule } from '../../lib/rateLimit/limiter.ts';
+import { RATE_LIMIT_RULES, QUOTA_ROUTES, PUBLISH_ROUTES, matchesRoute } from '../../lib/rateLimit/rules.ts';
+import type { AppContext, AppEnv } from '../../types/app.ts';
+
+const tightRule: RateLimitRule = {
+ name: 'tight',
+ label: 'Too many requests',
+ config: { algorithm: 'fixedWindow', limit: 2, windowMs: 60_000 },
+};
+
+const looseRule: RateLimitRule = {
+ name: 'loose',
+ label: 'Too many requests from your network',
+ config: { algorithm: 'fixedWindow', limit: 100, windowMs: 60_000 },
+};
+
+function appWith(register: (app: Hono<AppEnv>) => void, userId?: string): Hono<AppEnv> {
+ const app = new Hono<AppEnv>();
+ app.use('*', async (c, next) => {
+ c.set('redis', null);
+ c.set('rateLimitRedis', null);
+ if (userId) c.set('userId', userId);
+ await next();
+ });
+ register(app);
+ app.get('/api/thing', c => c.json({ ok: true }));
+ app.post('/api/thing', c => c.json({ ok: true }));
+ return app;
+}
+
+const fromIp = (ip: string) => ({ headers: { 'CF-Connecting-IP': ip } });
+
+beforeEach(() => resetRateLimitState());
+
+test('allowed responses carry the limit, remaining and reset headers', async () => {
+ const app = appWith(app => app.use('/api/*', rateLimit(tightRule, clientIp)));
+ const response = await app.request('/api/thing', fromIp('203.0.113.7'));
+ assert.equal(response.status, 200);
+ assert.equal(response.headers.get('RateLimit-Limit'), '2');
+ assert.equal(response.headers.get('RateLimit-Remaining'), '1');
+ assert.ok(Number(response.headers.get('RateLimit-Reset')) >= 1);
+ assert.equal(response.headers.get('Retry-After'), null);
+});
+
+test('a request over the limit gets 429, Retry-After and a message that says when to retry', async () => {
+ const app = appWith(app => app.use('/api/*', rateLimit(tightRule, clientIp)));
+ await app.request('/api/thing', fromIp('203.0.113.7'));
+ await app.request('/api/thing', fromIp('203.0.113.7'));
+ const response = await app.request('/api/thing', fromIp('203.0.113.7'));
+ assert.equal(response.status, 429);
+ const retryAfter = Number(response.headers.get('Retry-After'));
+ assert.ok(retryAfter >= 1 && retryAfter <= 60);
+ assert.equal(response.headers.get('RateLimit-Remaining'), '0');
+ const body = await response.json() as { success: boolean; error: string; retryAfter: number };
+ assert.equal(body.success, false);
+ assert.equal(body.retryAfter, retryAfter);
+ assert.match(body.error, /^Too many requests - try again in \d+ seconds?\.$/);
+});
+
+test('different clients have separate limits', async () => {
+ const app = appWith(app => app.use('/api/*', rateLimit(tightRule, clientIp)));
+ await app.request('/api/thing', fromIp('203.0.113.7'));
+ await app.request('/api/thing', fromIp('203.0.113.7'));
+ const other = await app.request('/api/thing', fromIp('198.51.100.1'));
+ assert.equal(other.status, 200);
+});
+
+test('requests without an identifier are not limited', async () => {
+ const app = appWith(app => app.use('/api/*', rateLimit(tightRule, clientIp)));
+ for (let i = 0; i < 5; i++) assert.equal((await app.request('/api/thing')).status, 200);
+});
+
+test('the response reports whichever applied rule has the least left', async () => {
+ const app = appWith(app => {
+ app.use('/api/*', rateLimit(looseRule, clientIp));
+ app.use('/api/*', rateLimit(tightRule, userKey));
+ }, 'user-1');
+ const response = await app.request('/api/thing', fromIp('203.0.113.7'));
+ assert.equal(response.headers.get('RateLimit-Limit'), '2');
+ assert.equal(response.headers.get('RateLimit-Remaining'), '1');
+});
+
+test('a rule with a route filter only counts the routes it names', async () => {
+ const onlyPost = (c: AppContext) => c.req.method === 'POST';
+ const app = appWith(app => app.use('/api/*', rateLimit(tightRule, userKey, onlyPost)), 'user-1');
+ for (let i = 0; i < 4; i++) assert.equal((await app.request('/api/thing')).status, 200);
+ await app.request('/api/thing', { method: 'POST' });
+ await app.request('/api/thing', { method: 'POST' });
+ assert.equal((await app.request('/api/thing', { method: 'POST' })).status, 429);
+ assert.equal((await app.request('/api/thing')).status, 200);
+});
+
+test('IPv6 clients are limited per /64 and IPv4-mapped addresses as IPv4', async () => {
+ const seen: (string | null)[] = [];
+ const app = new Hono<AppEnv>();
+ app.get('/ip', c => {
+ seen.push(clientIp(c));
+ return c.text('ok');
+ });
+ for (const ip of ['2001:db8:abcd:12:1::5', '2001:0DB8:ABCD:0012:ffff::1', '::1', '::ffff:203.0.113.7', '198.51.100.1', '2001:db8::']) {
+ await app.request('/ip', fromIp(ip));
+ }
+ assert.deepEqual(seen, [
+ '2001:db8:abcd:12::/64',
+ '2001:db8:abcd:12::/64',
+ '0:0:0:0::/64',
+ '203.0.113.7',
+ '198.51.100.1',
+ '2001:db8:0:0::/64',
+ ]);
+});
+
+test('quota and publish routes match the endpoints that spend platform API calls', () => {
+ const quota = (method: string, path: string) => matchesRoute(QUOTA_ROUTES, method, path);
+ assert.equal(quota('POST', '/api/accounts'), true);
+ assert.equal(quota('GET', '/api/accounts'), false);
+ assert.equal(quota('POST', '/api/accounts/reddit'), true);
+ assert.equal(quota('POST', '/api/accounts/instagram'), true);
+ assert.equal(quota('POST', '/api/accounts/refresh-all'), true);
+ assert.equal(quota('POST', '/api/accounts/abc123/refresh'), true);
+ assert.equal(quota('POST', '/api/accounts/abc123/refresh-ig-token'), true);
+ assert.equal(quota('POST', '/api/resolve-channel'), true);
+ assert.equal(quota('POST', '/api/tracked-content'), true);
+ assert.equal(quota('PUT', '/api/tracked-content/abc'), false);
+ assert.equal(quota('POST', '/api/tracked-content/abc/refresh'), true);
+ assert.equal(quota('GET', '/api/process-scheduled'), true);
+ assert.equal(quota('GET', '/api/accounts/abc123/analytics'), false);
+
+ const publish = (method: string, path: string) => matchesRoute(PUBLISH_ROUTES, method, path);
+ assert.equal(publish('POST', '/api/accounts/abc/ig-publish'), true);
+ assert.equal(publish('POST', '/api/accounts/abc/ig-media-publish'), true);
+ assert.equal(publish('GET', '/api/accounts/abc/ig-publishing-limit'), false);
+});
+
+test('every rule uses a different algorithm and a positive limit', () => {
+ const rules = Object.values(RATE_LIMIT_RULES);
+ assert.equal(new Set(rules.map(rule => rule.config.algorithm)).size, 5);
+ assert.equal(new Set(rules.map(rule => rule.name)).size, rules.length);
+});
diff --git a/backend/types/app.ts b/backend/types/app.ts
index 6f32a62..bad2c9c 100644
--- a/backend/types/app.ts
+++ b/backend/types/app.ts
@@ -9,6 +9,8 @@ export type { SupabaseClient, Redis };
export interface AppVariables {
supabase: SupabaseClient;
redis: Redis | null;
+ // a separate client that fails fast; see getRateLimitRedis()
+ rateLimitRedis: Redis | null;
userId: string;
userEmail: string | undefined;
}
diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.md
index 260dc93..c1551a2 100644
--- a/docs/architecture/OVERVIEW.md
+++ b/docs/architecture/OVERVIEW.md
@@ -15,9 +15,9 @@
│ https://twiligent.ujjwalkrai.workers.dev/api │
│ │
│ Hono v4 app │
-│ ├── Global middleware: CORS, Supabase client, Redis client │
+│ ├── Global middleware: CORS, clients, per-IP rate limit │
│ ├── Public: GET /api/health, GET /api/auth/instagram/callback │
-│ └── Protected (/api/*): requireAuth -> routes │
+│ └── Protected (/api/*): requireAuth -> rate limits -> routes │
│ │
│ Cron handlers (wrangler.toml triggers): │
│ ├── */15 * * * * -> processScheduledPosts() │
@@ -61,10 +61,12 @@ Browser
Cloudflare Worker edge node (nearest to user)
-> CORS middleware (checks origin)
-> Client injection middleware (creates Supabase + Redis clients from env)
+ -> rateLimit(ip) middleware (per client IP; 429 when over the limit)
-> requireAuth middleware
-> extracts Bearer token from Authorization header
-> supabaseAuth.auth.getUser(token) -> Supabase validates JWT
-> sets c.userId, c.userEmail on Hono context
+ -> rateLimit(user), and rateLimit(quota) or rateLimit(publish) on the routes they cover
-> route handler (e.g., accounts router)
-> db.getAccounts(supabase, userId) [lib/db.js]
-> supabase.from('accounts').select(...).eq('user_id', userId)
@@ -115,7 +117,7 @@ The SPA also serves public documentation at `/docs` (no sign-in, no API calls).
1. **The Worker never receives binary file uploads.** Cloudinary handles file ingestion directly from the browser. The Worker only receives Cloudinary URLs.
-2. **Redis is always optional.** Every cache call is wrapped in try/catch and falls back to live APIs. Removing Upstash credentials degrades performance but never breaks functionality.
+2. **Redis is always optional.** Every cache call is wrapped in try/catch and falls back to live APIs, and rate limits fall back to per-isolate memory. Removing Upstash credentials degrades performance and loosens rate limits but never breaks functionality.
3. **The service-role key is never used on the frontend.** The frontend uses only the anon key (for Supabase Auth client-side). The service-role key is a Worker secret.
@@ -123,4 +125,6 @@ The SPA also serves public documentation at `/docs` (no sign-in, no API calls).
5. **`db.js` is the only file that contains Supabase queries.** Route handlers import and call db functions - they never call `supabase.from()` directly.
-6. **`api.js` is the only file that calls `fetch()` in the frontend.** Components call `api.methodName()` - they never construct fetch calls.
+6. **Every `/api` request is rate limited.** Per IP before authentication, per user after it, and tighter on routes that spend platform API quota. See `docs/architecture/backend/RATE_LIMITING.md`.
+
+7. **`api.js` is the only file that calls `fetch()` in the frontend.** Components call `api.methodName()` - they never construct fetch calls.
diff --git a/docs/architecture/backend/CACHING.md b/docs/architecture/backend/CACHING.md
index 1e073c7..ae892de 100644
--- a/docs/architecture/backend/CACHING.md
+++ b/docs/architecture/backend/CACHING.md
@@ -26,6 +26,8 @@ export async function getVideosCache(redis, userId, accountId) {
| `ig:{userId}:{accountId}` | `{ media, fetchedAt, version }` - normalized Instagram media (see `normalizeInstagramMedia()`) | `GET /api/accounts/:id/ig-analytics` or `ig-media` succeeds, or the Overview warms it | `DELETE /api/accounts/:id`, or a `version` mismatch |
| `reddit:{userId}:{accountId}` | Object `{ profile, analytics, posts }` for Reddit account | `GET /api/accounts/:id/reddit-analytics` succeeds | `DELETE /api/accounts/:id` |
+Rate limit state also lives in Redis under `ratelimit:{rule}:{identifier}` keys (hashes or sorted sets, each with its own expiry). They are written only by the Lua scripts in `lib/rateLimit/scripts.ts` through a separate fast-fail client; see `RATE_LIMITING.md`.
+
**Note:** Instagram OAuth state is an HMAC-signed token and does not use Redis. The unused Redis-backed `oauth_ig:` helpers were removed.
## Cache Versioning
diff --git a/docs/architecture/backend/HONO.md b/docs/architecture/backend/HONO.md
index 97e1dcb..78509d3 100644
--- a/docs/architecture/backend/HONO.md
+++ b/docs/architecture/backend/HONO.md
@@ -47,6 +47,7 @@ These are set on the Hono context (`c`) and available in all route handlers:
|---|---|---|---|
| `supabase` | Supabase client (service-role) | global middleware | All routes |
| `redis` | Upstash Redis client \| null | global middleware | All routes |
+| `rateLimitRedis` | Upstash Redis client \| null (no retries, 1 second timeout) | global middleware | All routes; used only by `rateLimit` |
| `userId` | string (UUID) | `requireAuth` | Protected routes only |
| `userEmail` | string | `requireAuth` | Protected routes only |
diff --git a/docs/architecture/backend/MIDDLEWARE.md b/docs/architecture/backend/MIDDLEWARE.md
index fe19e54..d5b50fb 100644
--- a/docs/architecture/backend/MIDDLEWARE.md
+++ b/docs/architecture/backend/MIDDLEWARE.md
@@ -6,13 +6,19 @@
Request arrives
│
▼
-1. CORS middleware app.use('*', cors())
+1. CORS middleware app.use('*', cors({ exposeHeaders }))
│
▼
2. Client injection app.use('*', clientInjectionMiddleware)
│
▼
-3. requireAuth api.use('*', requireAuth) <- protected routes only
+3. rateLimit(ip) app.use('/api/*', rateLimit(RATE_LIMIT_RULES.ip, clientIp))
+ │
+ ▼
+4. requireAuth api.use('*', requireAuth) <- protected routes only
+ │
+ ▼
+5. rateLimit(user, quota, publish) <- protected routes only
│
▼
Route handler
@@ -27,7 +33,7 @@ Route handler
Configured with defaults - allows all origins in development. For production, the Worker's CORS behavior should be tightened to only allow `FRONTEND_URL`.
-**Current config:** `cors()` with no options (allows all origins). This is acceptable for a self-hosted deployment where the Worker URL is not publicly advertised.
+**Current config:** `cors({ exposeHeaders: RATE_LIMIT_HEADERS })`. All origins are allowed, which is acceptable for a self-hosted deployment where the Worker URL is not publicly advertised. `exposeHeaders` lets the browser read `RateLimit-Limit`, `RateLimit-Remaining`, `RateLimit-Reset` and `Retry-After`.
---
@@ -42,12 +48,14 @@ Creates per-request Supabase and Redis client instances and sets them on the Hon
app.use('*', async (c, next) => {
c.set('supabase', getSupabase(c.env));
c.set('redis', getRedis(c.env));
+ c.set('rateLimitRedis', getRateLimitRedis(c.env));
await next();
});
```
**`getSupabase(env)`** - creates a Supabase client with the service-role key. Used for all DB operations.
-**`getRedis(env)`** - creates an Upstash Redis client if `UPSTASH_REDIS_REST_URL` is set, otherwise returns `null`. All cache functions in `lib/cache.js` handle `null` silently.
+**`getRedis(env)`** - creates an Upstash Redis client if `UPSTASH_REDIS_REST_URL` is set, otherwise returns `null`. All cache functions in `lib/cache.ts` handle `null` silently.
+**`getRateLimitRedis(env)`** - a second Upstash client for the rate limiter, with retries off and a 1 second timeout, so a Redis outage cannot slow every request. `null` without credentials.
---
@@ -80,6 +88,17 @@ export async function requireAuth(c, next) {
---
+## 4. rateLimit Middleware
+
+**Source:** `backend/middleware/rateLimit.ts`, rules and algorithms in `backend/lib/rateLimit/`
+**Applied to:** every `/api` request (`ip` rule, before `requireAuth`), every protected request (`user`), quota-spending routes (`quota`), Instagram publishing routes (`publish`) and the public OAuth callback (`oauth`)
+
+`rateLimit(rule, identify, applies?)` returns a middleware. `identify(c)` returns the key (`clientIp` or `userKey`); a request without one is not limited. `applies(c)` restricts a rule to some routes (`matchesRoute(QUOTA_ROUTES, ...)`). Allowed responses get `RateLimit-*` headers for the most restrictive rule; a request over a limit gets `429` with `Retry-After` and `{ success: false, error, retryAfter }`.
+
+See `RATE_LIMITING.md` for the rules, the algorithms and how failures are handled.
+
+---
+
## Adding New Middleware
Place new middleware files in `backend/middleware/`. Follow this pattern:
diff --git a/docs/architecture/backend/RATE_LIMITING.md b/docs/architecture/backend/RATE_LIMITING.md
new file mode 100644
index 0000000..45d4f88
--- /dev/null
+++ b/docs/architecture/backend/RATE_LIMITING.md
@@ -0,0 +1,113 @@
+# Rate Limiting
+
+Every `/api` request is rate limited inside the Worker. Cloudflare does not limit requests to a `workers.dev` Worker on its own: WAF rate limiting rules need a zone the owner controls, and the Workers rate limiting binding is per location and only supports 10 or 60 second periods. So the Worker enforces its own limits, which protect three things:
+
+- Supabase Auth, which `requireAuth` calls on every protected request
+- The shared YouTube Data API quota and the Instagram and Reddit API limits
+- Instagram publishing, which Instagram caps at 100 posts a day per account
+
+## Request Flow
+
+```
+Request
+ -> CORS (exposes the rate limit headers to the browser)
+ -> client injection (supabase, redis, rateLimitRedis)
+ -> rateLimit(ip) every /api request, keyed by client IP, before authentication
+ -> requireAuth protected routes only
+ -> rateLimit(user) every protected request, keyed by user id
+ -> rateLimit(quota) routes that spend platform API quota, keyed by user id
+ -> rateLimit(publish) Instagram container and publish routes, keyed by user id
+ -> route handler
+```
+
+The public OAuth callback (`GET /api/auth/instagram/callback`) also passes `rateLimit(oauth)`, keyed by IP.
+
+## Rules
+
+Defined in `backend/lib/rateLimit/rules.ts`.
+
+| Rule | Applies to | Key | Algorithm | Limit |
+|---|---|---|---|---|
+| `ip` | Every `/api` request | Client IP; IPv6 by /64 | Sliding window counter | 300 per minute |
+| `user` | Every protected request | User id from the verified JWT | Token bucket | Bursts of 120, refills 2 per second |
+| `quota` | `POST /accounts`, `/accounts/reddit`, `/accounts/instagram`, `/accounts/refresh-all`, `/accounts/:id/refresh`, `/accounts/:id/refresh-ig-token`, `/resolve-channel`, `/tracked-content`, `/tracked-content/:id/refresh`, `GET` or `POST /process-scheduled` | User id | Sliding window log | 30 per 10 minutes |
+| `publish` | `POST /accounts/:id/ig-media-publish`, `/accounts/:id/ig-publish` | User id | Leaking bucket | 50 deep, drains 1 every 15 seconds |
+| `oauth` | `GET /auth/instagram/callback` | Client IP | Fixed window counter | 10 per 10 minutes |
+
+The limits are sized for the dashboard: an Overview load sends about 20 requests, Instagram container polling sends one every 3 seconds, and bulk publishing sends two Instagram calls per file. Lowering them can block normal use; test the Overview, bulk publishing and tracked content refresh after any change.
+
+The client IP comes from `CF-Connecting-IP`, which Cloudflare always sets and which a client cannot override. Locally, `wrangler dev` does not set it, so the IP rule only applies when a test sends the header. IPv4-mapped IPv6 addresses (`::ffff:203.0.113.7`) are limited as the IPv4 address.
+
+## Algorithms
+
+`backend/lib/rateLimit/algorithms.ts` implements the five standard algorithms as pure functions: given the saved state, the time and the config, each returns the new state and a decision `{ allowed, limit, remaining, resetMs, retryAfterMs }`.
+
+| Algorithm | State | How it decides | Why it fits its rule |
+|---|---|---|---|
+| Token bucket | Tokens left, last update | Refills `refillPerSecond` tokens up to `capacity`; a request takes one token | Allows page-load bursts, then a steady rate (`user`) |
+| Leaking bucket | Level, last update | The level drains at `leakPerSecond`; a request adds one; a full bucket rejects | Paces a stream evenly (`publish`). The Worker cannot hold requests in a queue, so this is the "leaky bucket as a meter" form: it rejects instead of delaying. |
+| Fixed window counter | Window number, count | Counts requests per aligned window | Simple and exact per window, and the boundary burst does not matter at this volume (`oauth`) |
+| Sliding window log | Timestamps of accepted requests | Drops timestamps older than the window; accepts while fewer than `limit` remain | Exact in every rolling window, for the rule that protects paid quota (`quota`). Only accepted requests are logged, so the log never exceeds `limit` entries. |
+| Sliding window counter | Window number, current count, previous count | Estimates `previous * overlap + current`, where overlap is the share of the previous window still inside the sliding window | Constant memory for the highest-volume rule, close to exact (`ip`) |
+
+Bucket levels are rounded to a millionth after each step, so the saved value survives Redis's text storage exactly and the two implementations never disagree.
+
+## Stores
+
+`backend/lib/rateLimit/stores.ts` has two stores behind one interface.
+
+**Redis (`RedisStore`).** Each algorithm has a Lua script in `backend/lib/rateLimit/scripts.ts`. A script reads the state, decides and writes the new state in one atomic step, so two isolates can never both read the same count and both pass. This is the race condition that a read-then-write limiter has. Scripts run with `EVALSHA` and fall back to `EVAL` the first time (`redis.createScript().exec()`). The clock is passed in `ARGV[1]` because Upstash requires deterministic scripts. Every key a script touches is `KEYS[1]`, and every key expires once its state no longer matters.
+
+**Memory (`MemoryStore`).** The same algorithm functions run against a per-isolate `Map`, capped at 10,000 keys with least-recently-used eviction. Cloudflare runs many isolates, so these counts are per isolate rather than global.
+
+## Failure Handling
+
+Rate limiting never fails a request because of its own storage:
+
+- **No Redis configured:** every rule counts in memory.
+- **Redis fails or times out:** the limiter uses a separate client (`getRateLimitRedis()` in `lib/redis.ts`) that does not retry and gives up after 1 second. On a failure the isolate logs once and counts in memory for 30 seconds before it tries Redis again, so an outage costs at most one second per isolate every 30 seconds.
+- **Deny cache:** when Redis rejects a key, the isolate remembers the retry time and rejects that key locally until then. A client flooding a limit costs no Redis commands.
+
+## Responses
+
+Every response that passed a limit carries the most restrictive applied rule:
+
+```
+RateLimit-Limit: 120
+RateLimit-Remaining: 117
+RateLimit-Reset: 2 seconds until the limit is fully restored
+```
+
+A request over a limit gets `429 Too Many Requests`:
+
+```
+Retry-After: 12
+RateLimit-Limit: 300
+RateLimit-Remaining: 0
+RateLimit-Reset: 12
+
+{ "success": false, "error": "Too many requests from your network - try again in 12 seconds.", "retryAfter": 12 }
+```
+
+CORS exposes the four headers. The frontend needs no special handling: `request()` in `services/api.ts` throws the `error` text, and pages show it in a toast.
+
+## Redis Keys
+
+`ratelimit:{rule}:{identifier}`, for example `ratelimit:user:<uuid>` or `ratelimit:ip:203.0.113.7`. Bucket, fixed window and sliding counter keys are hashes; sliding log keys are sorted sets. All keys expire on their own.
+
+## Cost
+
+A rate-limited request costs one Redis script call per rule that applies: two for most protected requests (`ip` and `user`), three on quota and publish routes. On Upstash's free tier, which counts the commands inside a script, a small team stays well within the monthly allowance. Requests answered from the deny cache cost nothing.
+
+## Changing a Limit
+
+1. Edit the rule in `backend/lib/rateLimit/rules.ts`. To limit a new route, add it to `QUOTA_ROUTES` or `PUBLISH_ROUTES`.
+2. Run `npm test --workspace backend`. `tests/middleware/rateLimit.test.ts` checks the route matchers.
+3. Update the table above.
+
+## Verification
+
+- `backend/tests/lib/rateLimit/algorithms.test.ts`: every algorithm's decisions, retry times, reset times and state lifetimes.
+- `backend/tests/lib/rateLimit/limiter.test.ts`: the Redis path, the memory fallback, the circuit breaker, the deny cache and memory eviction.
+- `backend/tests/middleware/rateLimit.test.ts`: headers, the 429 body, per-client separation, route filters, IPv6 keys and the rule table.
+- The Lua scripts were run in a Lua VM against a fake Redis and matched the TypeScript algorithms exactly on 110,000 random requests, including bursts, idle gaps and clocks that move backwards.
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index 660ce30..7ed5bd3 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -2,6 +2,8 @@
All routes live under `/api`. Routes under the `api` sub-app require a valid Supabase JWT (`requireAuth` middleware). Public routes bypass auth.
+Every route is rate limited and can answer `429` with `Retry-After`; see `RATE_LIMITING.md` for which rule covers which route.
+
## Public Routes
| Method | Path | Handler | Purpose |
diff --git a/docs/guidelines/API_CONVENTIONS.md b/docs/guidelines/API_CONVENTIONS.md
index 799e2b1..25c5c98 100644
--- a/docs/guidelines/API_CONVENTIONS.md
+++ b/docs/guidelines/API_CONVENTIONS.md
@@ -41,6 +41,7 @@ The `request()` function in `frontend/src/services/api.js` reads `data.error` an
| `401` | Authentication required or token invalid (returned by `requireAuth`) |
| `403` | Authenticated but not authorized (wrong user for this resource) |
| `404` | Resource not found |
+| `429` | Rate limit exceeded; returned by the `rateLimit` middleware only, with `Retry-After` and `{ success: false, error, retryAfter }` (see `docs/architecture/backend/RATE_LIMITING.md`) |
| `500` | Unexpected server error |
## Request Bodies
diff --git a/docs/philosophy/PERFORMANCE.md b/docs/philosophy/PERFORMANCE.md
index 842c9c0..56b5f7c 100644
--- a/docs/philosophy/PERFORMANCE.md
+++ b/docs/philosophy/PERFORMANCE.md
@@ -38,6 +38,10 @@ When fixing the known TTL issue, use the Upstash Redis `EX` option:
await redis.set(key, data, { ex: 3600 }); // expire after 1 hour
```
+## Rate Limiting Cost
+
+Each protected request runs two rate limit checks (`ip` before authentication, `user` after it), each one Redis script call, so a request pays two short Upstash round trips. A client already over its limit is answered from the isolate without Redis, and a Redis outage costs at most one 1 second timeout per isolate every 30 seconds. See `docs/architecture/backend/RATE_LIMITING.md`.
+
## Edge Deployment
The Cloudflare Worker runs at the edge - in a data center close to the user. This means:
diff --git a/docs/philosophy/SECURITY.md b/docs/philosophy/SECURITY.md
index 89bc431..99ce437 100644
--- a/docs/philosophy/SECURITY.md
+++ b/docs/philosophy/SECURITY.md
@@ -62,11 +62,15 @@ const { data } = await supabase.from('accounts').select('*').eq('id', accountId)
The Instagram OAuth flow uses a self-verifying HMAC state token to prevent CSRF:
1. On OAuth start: state = `base64url(userId:timestamp)` + `.` + `HMAC-SHA256(secret, payload)`
-2. Stored in Redis with a TTL of 10 minutes
+2. Nothing is stored server-side; the timestamp inside the signed payload expires the state after 10 minutes
3. On OAuth callback: verify HMAC before accepting the `code` parameter
If the HMAC check fails, the callback returns 400 and discards the code. An attacker cannot forge a valid state without the `INSTAGRAM_APP_SECRET`.
+## Rate Limiting
+
+Every `/api` request is rate limited per client IP before authentication, so a flood of invalid tokens never reaches Supabase Auth. Protected requests are also limited per user, and routes that spend the shared YouTube quota or the Instagram and Reddit limits have a tighter per-user rule. Limits are counted atomically in Redis (one Lua script per check) and fall back to per-isolate memory when Redis is absent or failing, so they never fail open entirely and never fail a request. See `docs/architecture/backend/RATE_LIMITING.md`.
+
## Input Validation
The backend validates:
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index 7e1a1cd..91e2378 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -31,6 +31,8 @@ Backend tests are in `backend/tests/lib`, `backend/tests/routes`, `backend/tests
Frontend tests cover shared helpers in `src/lib/` and `src/utils/` (hold-to-confirm timing, command palette ranking, library filtering and paging, platform helpers, and a check that every Lucide icon imported in `src` exists) and page helpers in `src/features/**` and `src/docs/**`, such as `features/analytics/overview/overviewStats.js`. A testable helper is a plain `.js` file with no JSX and no `@/` imports, and its imports of project files are relative paths that end in `.js`, so Node can load it directly. This rule lives here, so helper files do not repeat it in a header comment.
+Rate limiting has its own tests: `tests/lib/rateLimit/algorithms.test.ts` (each algorithm's decisions, retry and reset times), `tests/lib/rateLimit/limiter.test.ts` (Redis path, memory fallback, circuit breaker, deny cache, eviction) and `tests/middleware/rateLimit.test.ts` (headers, the 429 body, route filters, IPv6 keys). The Lua scripts in `lib/rateLimit/scripts.ts` cannot run in Node; when you change one, change the twin function in `algorithms.ts` the same way and check both against each other in a Lua VM (see `docs/architecture/backend/RATE_LIMITING.md`).
+
Backend route and scheduler tests (`tests/routes/*.test.js`, `tests/utils/scheduler.test.js`) run the real handlers against `tests/fixtures/fakeSupabase.js` and a scripted `fetch`, then compare responses, queries and outgoing requests with the `tests/fixtures/*.golden.json` snapshots. Rows tagged with `tableRow(name, row)` are only visible to that table; untagged rows are visible to every table. A refactor must leave the snapshots unchanged. Prettier ignores the snapshots (`.prettierignore`), because the tests compare them byte for byte.
The testing workflow documented here describes what should run before shipping any change.
@@ -96,6 +98,11 @@ Open the app in a browser. For each changed area, test:
- [ ] Login with invalid credentials -> error message shown
- [ ] Sign out -> redirects to login
+**Rate limiting (if changed):**
+- [ ] `curl -i -H "CF-Connecting-IP: 203.0.113.1" http://localhost:8787/api/health` shows `RateLimit-Limit`, `RateLimit-Remaining` and `RateLimit-Reset`
+- [ ] More requests than the rule allows return `429` with `Retry-After` and a message that says when to retry
+- [ ] The Overview, bulk publishing and tracked content refresh still work without a `429`
+
**Accounts:**
- [ ] Add a YouTube channel by URL -> appears in sidebar
- [ ] Delete an account -> removed from sidebar
diff --git a/frontend/src/docs/pages/selfHost/Redis.tsx b/frontend/src/docs/pages/selfHost/Redis.tsx
index ca7eaaa..dc09613 100644
--- a/frontend/src/docs/pages/selfHost/Redis.tsx
+++ b/frontend/src/docs/pages/selfHost/Redis.tsx
@@ -4,8 +4,9 @@ import { DocTitle, P, A, Steps, Step } from '../../components';
export default function Redis() {
return (
<>
- <DocTitle title="Upstash Redis (optional)" lead="A cache that saves YouTube and Instagram quota and makes pages load faster." />
+ <DocTitle title="Upstash Redis (optional)" lead="A cache that saves YouTube and Instagram quota, makes pages load faster, and makes rate limits exact." />
<P>Twiligent works fully without Redis. Every cache read falls back to a live API call, and Redis errors are ignored. Add it when you have several members or many YouTube channels.</P>
+ <P>The backend also limits how fast each person and each network can call it, so one client cannot use up the shared YouTube quota. With Redis, those limits are counted once across every Cloudflare location. Without it, each Worker instance counts on its own, so the limits are looser but still apply. There is nothing to configure.</P>
<Steps>
<Step title="Create a database">
<P>Sign in at <A href="https://console.upstash.com">console.upstash.com</A>, choose <strong>Create database</strong>, and pick the region closest to your Supabase project.</P>