Implementing a Fixed‑Window Postgres Rate Limiter for a Public API
TL;DR: I added a deterministic fixed‑window rate limiter backed by PostgreSQL to stop the API from spitting out 429 on every request. The change lives in src/infra/postgresRateLimiter.ts and required a tiny schema tweak plus a few atomic SQL statements.
The Problem
Our public API (Node + TypeScript) started returning 429 Too Many Requests on every call after we introduced a new endpoint for the AI Business Academy pilot. The symptom was clear in the logs:
2026-11-26T14:32:11.045Z ERROR Rate limit exceeded for user_id=42, endpoint=/v1/predict Response: 429 Too Many Requests The root cause was a missing rate‑limit layer. We had a placeholder src/infra/postgresRateLimiter.ts that only returned true and never persisted counters. Because the limiter never reset, the first request hit the default limit and all subsequent requests were blocked.
What I Tried First
My first attempt was to cheat with an in‑memory map:
// src/infra/postgresRateLimiter.ts (initial version) const counters = new Map<string, number>(); export async function canProceed(key: string, limit: number): Promise<boolean> { const count = counters.get(key) ?? 0; if (count >= limit) return false; counters.set(key, count + 1); return true; } This worked locally but fell apart in production:
- Stateless containers – each instance had its own map, so the limit was effectively per pod, not per user.
- Process restarts – counters vanished, allowing bursts that bypassed the limit.
- No persistence – we couldn't audit or back‑fill usage data.
The failure was immediate: after a container restart, the 429 disappeared for a few minutes, then reappeared once the in‑memory counter filled again.
The Implementation
1. Database schema
I added a tiny table to track request counts per fixed window:
-- migrations/20261126_create_rate_limit_table.sql CREATE TABLE api_rate_limits ( key TEXT NOT NULL, window_start TIMESTAMPTZ NOT NULL, count INTEGER NOT NULL, PRIMARY KEY (key, window_start) ); key is a composite of user_id and endpoint. window_start marks the beginning of the current fixed window (e.g., the current minute).
2. Atomic upsert
Postgres can atomically increment a counter with INSERT … ON CONFLICT … DO UPDATE. The implementation lives in src/infra/postgresRateLimiter.ts:
// src/infra/postgresRateLimiter.ts import { Pool } from 'pg'; import { formatISO } from 'date-fns'; const pool = new Pool({ connectionString: process.env.DATABASE_URL, }); /** * Returns true if the request is allowed, false otherwise. * * @param key Unique identifier (e.g., `${userId}:${endpoint}`) * @param limit Max requests per window * @param windowSeconds Length of the fixed window in seconds */ export async function canProceed( key: string, limit: number, windowSeconds: number = 60, ): Promise<boolean> { const client = await pool.connect(); try { await client.query('BEGIN'); // Compute the start of the current window (rounded down to the nearest windowSeconds) const now = new Date(); const windowStart = new Date( Math.floor(now.getTime() / (windowSeconds * 1000)) * windowSeconds * 1000, ); const windowStartISO = formatISO(windowStart); // Upsert the counter atomically const upsertResult = await client.query( ` INSERT INTO api_rate_limits (key, window_start, count) VALUES ($1, $2, 1) ON CONFLICT (key, window_start) DO UPDATE SET count = api_rate_limits.count + 1 RETURNING count; `, [key, windowStartISO], ); const { count } = upsertResult.rows[0]; // If we exceeded the limit, abort the transaction if (count > limit) { await client.query('ROLLBACK'); return false; } await client.query('COMMIT'); return true; } catch (err) { await client.query('ROLLBACK'); console.error('Rate limiter error:', err); // Fail‑open: allow the request if the limiter crashes return true; } finally { client.release(); } } Key points:
- Fixed window calculation – we round the current timestamp down to the nearest
windowSeconds. This guarantees that all requests within the same window share the samewindow_start. -
INSERT … ON CONFLICT … DO UPDATE– guarantees atomicity without explicit locks. - Transaction boundaries – we
ROLLBACKif the limit is exceeded, ensuring the counter isn’t incremented beyond the allowed quota. - Fail‑open policy – if the DB throws, we log and let the request through rather than taking the API down.
3. Middleware integration
The limiter is now called from an Express middleware:
// src/middleware/rateLimiter.ts import { Request, Response, NextFunction } from 'express'; import { canProceed } from '../infra/postgresRateLimiter'; export async function rateLimiter( req: Request, res: Response, next: NextFunction, ) { const userId = req.header('x-user-id') ?? 'anonymous'; const endpoint = req.path; const key = `${userId}:${endpoint}`; const allowed = await canProceed(key, 100, 60); // 100 req/min per user/endpoint if (!allowed) { return res.status(429).json({ error: 'Rate limit exceeded' }); } next(); } And wired up in src/server.ts:
import express from 'express'; import { rateLimiter } from './middleware/rateLimiter'; const app = express(); app.use(rateLimiter); // … other routes app.listen(process.env.PORT ?? 3000); 4. Updating the repo metadata
The only non‑code change was to surface the new Dev.to article URL in content/2026/11/26/content-automation/metadata.json:
- "devto_url": "", + "devto_url": "https://dev.to/zaerohell/implementing-a-fixed-window-postgres-rate-limiter-for-a-public-api-m5p", This makes the automation pipeline aware that the article is published and prevents duplicate pushes.
Key Takeaway
When you need a deterministic rate limiter in a horizontally‑scaled Node service, a fixed‑window table with an atomic upsert is simple, reliable, and observable. It avoids the complexity of Redis‑based token buckets while still giving you per‑user, per‑endpoint granularity and a persistent audit trail.
What's Next
- Sliding‑window approximation – replace the fixed window with a time‑bucketed sliding algorithm to smooth traffic spikes.
- Metrics export – push
countandwindow_startstats to Prometheus for real‑time monitoring. - Cache layer – add a short‑lived in‑memory cache (e.g.,
node-cache) to cut down DB round‑trips for high‑throughput endpoints.
Roberto Luna Osorio – Full Stack Developer & Project Lead
Playa del Carmen, México
vibecoding #buildinpublic #postgres #nodejs #typescript #rate-limiting #backend #devops
Part of my Build in Public series — sharing the real process of building SaaS projects from Playa del Carmen, México.
Repo: zaerohell/content-automation · 2026-11-27
#playadev #buildinpublic
