Implementing a Fixed‑Window Postgres Rate Limiter and Deep AI Health Check in the AI Business Academy
TL;DR: Added a Postgres‑backed fixed‑window rate limiter and a comprehensive AI health‑check endpoint to protect the API from overload and surface hidden failures. The changes landed in version 0.1.1 and are now part of the production Docker image.
The Problem
Our API layer for the AI Business Academy was handling two critical workloads:
- AI health diagnostics – a
/health/aiendpoint that queried several external models (ChatGPT, Gemini, etc.) to verify connectivity and latency. - Rate‑limited public endpoints – the
/api/v1/promptroute that accepted user prompts and forwarded them to the LLMs.
Both endpoints were unprotected. During a live demo the /health/ai call hung for 30 seconds, and the prompt endpoint started returning 429 Too Many Requests sporadically because the underlying Postgres instance was being hammered by a naive in‑memory counter that didn’t survive container restarts. The symptom in the logs was:
ERROR 2026-11-25T14:02:37.123Z rateLimiter - Rate limit exceeded for user_id=42 We needed a persistent, low‑overhead limiter and a health‑check that actually exercised the AI services rather than just returning “OK”.
What I Tried First
In‑Memory Counter
// src/middleware/rateLimiter.ts (initial attempt) const counters = new Map<string, { count: number; reset: number }>(); export function rateLimiter(req, res, next) { const key = req.ip; const now = Date.now(); const window = 60_000; // 1 minute if (!counters.has(key) || counters.get(key)!.reset < now) { counters.set(key, { count: 1, reset: now + window }); } else { const entry = counters.get(key)!; entry.count += 1; if (entry.count > 100) { return res.status(429).json({ error: "Rate limit exceeded" }); } } next(); } What went wrong?
- The map lives only in the container’s memory, so a pod restart resets all counters, allowing a burst of requests that bypasses the limit.
- In a horizontally‑scaled environment each replica kept its own counter, effectively multiplying the allowed request rate.
Redis‑Based Token Bucket
I spun up a Redis container and swapped the map for a token bucket. The implementation worked, but it introduced an external dependency that we didn’t need for a small pilot. Deploying Redis on Vercel’s serverless platform added latency and cost, and the team wasn’t comfortable managing another service.
The Implementation
Why Postgres?
The project already uses Neon (serverless Postgres) for user data, so we can leverage the same connection pool. A fixed‑window algorithm fits our use case (simple per‑minute caps) and can be expressed in a single SQL statement, keeping latency sub‑millisecond.
File Changes
| File | Purpose |
|---|---|
src/middleware/rateLimiter.ts | Postgres‑backed fixed‑window limiter |
src/health/aiHealth.ts | Deep health‑check that pings external LLMs |
src/routes/health.ts | Registers /health/ai endpoint |
Dockerfile | Installs pg and copies new source |
CHANGELOG.md | Documents version 0.1.1 |
ROADMAP.md | Updates milestone for rate limiter |
Below are the key snippets from the diff.
CHANGELOG.md entry (added in commit 960d5d1c)
+## [0.1.1] — 2026-11-25 + +### Added +- Postgres fixed-window rate limiter +- Deep AI health check endpoint Rate Limiter (src/middleware/rateLimiter.ts)
import { Pool } from "pg"; import type { Request, Response, NextFunction } from "express"; const pool = new Pool({ connectionString: process.env.DATABASE_URL, }); /** * Fixed‑window rate limiter. * Limits each IP to `MAX_REQUESTS` per `WINDOW_MS`. */ export async function rateLimiter( req: Request, res: Response, next: NextFunction ) { const ip = req.ip; const MAX_REQUESTS = 120; // per minute const WINDOW_MS = 60_000; const now = Date.now(); const windowStart = Math.floor(now / WINDOW_MS) * WINDOW_MS; const sql = ` INSERT INTO rate_limits (ip, window_start, count) VALUES ($1, to_timestamp($2 / 1000), 1) ON CONFLICT (ip, window_start) DO UPDATE SET count = rate_limits.count + 1 RETURNING count; `; try { const { rows } = await pool.query(sql, [ip, windowStart]); const currentCount = rows[0].count; if (currentCount > MAX_REQUESTS) { return res .status(429) .json({ error: "Rate limit exceeded", limit: MAX_REQUESTS }); } next(); } catch (err) { console.error("Rate limiter error:", err); // Fail‑open: let the request through if the DB is unavailable next(); } } Schema migration (run once):
CREATE TABLE IF NOT EXISTS rate_limits ( ip TEXT NOT NULL, window_start TIMESTAMP NOT NULL, count INTEGER NOT NULL, PRIMARY KEY (ip, window_start) ); Deep AI Health Check (src/health/aiHealth.ts)
ts import fetch from "node-fetch"; interface ServiceStatus { name: string; healthy: boolean; latencyMs: number; error?: string; } /** * Pings external AI services and aggregates their status. --- *Part of my [Build in Public](https://dev.to/zaerohell) series — sharing the real process of building SaaS projects from Playa del Carmen, México.* *Repo: `zaerohell/ai-business-academy` · 2026-11-25* \#playadev #buildinpublic 