DEV Community

Roberto Luna
Roberto Luna

Posted on

Implementing a Fixed‑Window Postgres Rate Limiter for a Public API

Implementing a Fixed‑Window Postgres Rate Limiter for a Public API

TL;DR: I added a PostgreSQL‑backed fixed‑window rate limiter to stop the API from returning 429 on every request. The change lives in src/infra/postgresRateLimiter.ts and is wired through the request middleware, with metadata updated to point to the new Dev.to article.


The Problem

Our public API started responding with HTTP 429 Too Many Requests for every call after we opened the first pilot of the AI Business Academy curriculum. The error looked like this:

GET https://api.vibecoding.com/v1/curriculum
Status: 429
Headers: { "Retry-After": "1" }
Body: { "error": "Rate limit exceeded" }
Enter fullscreen mode Exit fullscreen mode

The root cause was a missing rate‑limiting layer. The API gateway was forwarding all traffic directly to the service, and our downstream PostgreSQL instance was being hammered by repeated polling from the front‑end client. Without a limiter, the database connection pool exhausted, leading to the 429 responses.

What I Tried First

My first attempt was to use an in‑memory token bucket implemented with a simple JavaScript Map. The idea was to store a counter per API key and reset it every minute:

// naive‑in‑memory‑limiter.ts
const counters = new Map<string, { count: number; reset: number }>();

export function allow(key: string, limit = 60): boolean {
  const now = Date.now();
  const entry = counters.get(key) ?? { count: 0, reset: now + 60_000 };
  if (now > entry.reset) {
    entry.count = 0;
    entry.reset = now + 60_000;
  }
  if (entry.count >= limit) return false;
  entry.count++;
  counters.set(key, entry);
  return true;
}
Enter fullscreen mode Exit fullscreen mode

It worked locally, but in production the stateless nature of our serverless functions meant each invocation had its own memory space, so the counters never shared state. The result was still 429 for every request, because each instance thought it was the first call.

The Implementation

Architecture Decision

I switched to a fixed‑window rate limiter stored in PostgreSQL. This approach gives us:

  • Strong consistency – every request reads the same counter row.
  • Persistence – counters survive restarts.
  • Scalability – works across multiple serverless instances.

The limiter lives in src/infra/postgresRateLimiter.ts and is used as an Express‑style middleware.

Database Schema

-- migrations/20231125_create_rate_limit_table.sql
CREATE TABLE api_rate_limits (
  api_key      TEXT PRIMARY KEY,
  window_start TIMESTAMPTZ NOT NULL,
  request_count INTEGER NOT NULL DEFAULT 0
);
Enter fullscreen mode Exit fullscreen mode

The window_start marks the beginning of the current fixed window (e.g., the start of the minute).

Core Logic

// src/infra/postgresRateLimiter.ts
import { Pool } from 'pg';
import type { Request, Response, NextFunction } from 'express';

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});

const LIMIT = 60;               // max requests per minute
const WINDOW_MS = 60_000;       // 1 minute

export async function rateLimiter(req: Request, _res: Response, next: NextFunction) {
  const apiKey = req.headers['x-api-key'] as string;
  if (!apiKey) {
    return next(); // optional: unauthenticated routes may be unrestricted
  }

  const client = await pool.connect();
  try {
    await client.query('BEGIN');

    // 1️⃣ Try to fetch the current window row
    const { rows } = await client.query(
      `SELECT window_start, request_count
       FROM api_rate_limits
       WHERE api_key = $1
       FOR UPDATE`,
      [apiKey],
    );

    const now = Date.now();
    let windowStart: Date;
    let count: number;

    if (rows.length === 0) {
      // First request for this key – create a row
      windowStart = new Date(now);
      count = 1;
      await client.query(
        `INSERT INTO api_rate_limits (api_key, window_start, request_count)
         VALUES ($1, $2, $3)`,
        [apiKey, windowStart, count],
      );
    } else {
      // Existing row – check window expiration
      const row = rows[0];
      windowStart = new Date(row.window_start);
      const elapsed = now - windowStart.getTime();

      if (elapsed > WINDOW_MS) {
        // Window expired – reset
        windowStart = new Date(now);
        count = 1;
        await client.query(
          `UPDATE api_rate_limits
           SET window_start = $1, request_count = $2
           WHERE api_key = $3`,
          [windowStart, count, apiKey],
        );
      } else {
        // Same window – increment
        count = row.request_count + 1;
        if (count > LIMIT) {
          // Exceeded – abort transaction and send 429
          await client.query('ROLLBACK');
          const retryAfter = Math.ceil((WINDOW_MS - elapsed) / 1000);
          const err = new Error('Rate limit exceeded');
          (err as any).status = 429;
          (err as any).retryAfter = retryAfter;
          return next(err);
        }
        await client.query(
          `UPDATE api_rate_limits
           SET request_count = $1
           WHERE api_key = $2`,
          [count, apiKey],
        );
      }
    }

    await client.query('COMMIT');
    // Attach rate‑limit info to response headers (optional)
    req.res?.setHeader('X-RateLimit-Limit', LIMIT);
    req.res?.setHeader('X-RateLimit-Remaining', LIMIT - count);
    next();
  } catch (e) {
    await client.query('ROLLBACK');
    next(e);
  } finally {
    client.release();
  }
}
Enter fullscreen mode Exit fullscreen mode

Key points in the code:

  • FOR UPDATE locks the row, guaranteeing atomic increments.
  • The transaction is rolled back on limit breach, preventing the counter from inflating.
  • retryAfter is calculated from the remaining window time and attached to the error for the error‑handling middleware.

Wiring the Middleware

// src/server.ts
import express from 'express';
import { rateLimiter } from './infra/postgresRateLimiter';
import routes from './routes';

const app = express();

app.use(express.json());

// Apply limiter globally (or per‑router)
app.use(rateLimiter);

app.use('/api', routes);

// Centralized error handler
app.use((err: any, _req: Request, res: Response, _next: NextFunction) => {
  if (err.status === 429) {
    res.setHeader('Retry-After', err.retryAfter);
    return res.status(429).json({ error: err.message });
  }
  console.error(err);
  res.status(500).json({ error: 'Internal Server Error' });
});

export default app;
Enter fullscreen mode Exit fullscreen mode

Updating Project Metadata

With the new article published on Dev.to, I also updated the metadata.json file so our automation pipeline knows the URL:

--- a/content/2026/11/25/ai-business-academy/metadata.json
+++ b/content/2026/11/25/ai-business-academy/metadata.json
@@
   "devto_url": "",
+  "devto_url": "https://dev.to/zaerohell/implementing-a-fixed-window-rate-limiter-in-postgres-4c5b",
   "medium_generated": true,
-  "substack_generated": false,
+  "substack_generated": true,
Enter fullscreen mode Exit fullscreen mode

This tiny change lets our content‑automation scripts pull the correct link for future newsletters and cross‑posts.

Key Takeaway

When you need


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-26

#playadev #buildinpublic

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The part that rings true is the in-memory Map working locally and then falling apart in production — serverless makes per-instance counters almost useless, so moving the counter into Postgres was the right call. Using FOR UPDATE for the atomic increment and rolling back on a breach so the counter does not inflate is a nice detail too. One edge I keep thinking about with fixed windows is the burst right at the boundary, where a client can double up across two windows — did you consider a sliding window for the curriculum endpoint, or is the fixed window good enough at your current traffic? What limit did you settle on for curriculumStatus?