1.9 KiB
1.9 KiB
Postgres Rate Limiting Reference
Overview
This document describes how to implement API rate limiting using Postgres in the Fiddy Finance Buddy App. It covers:
- Rate limiting tiers and keying strategies
- Data model and query patterns
- Cleanup/retention strategy
- Operational considerations
Rate Limiting Tiers & Keying
- Auth endpoints (login/register): Strict limits per IP and identifier (email)
- Write endpoints (POST/PUT/DELETE): Moderate limits per user and IP
- Read endpoints (GET): Higher limits per user and IP
- Keying:
- Unauthenticated: IP only
- Auth endpoints: IP + email
- Authenticated: user ID + IP
Data Model (Suggested)
Table: rate_limits
key(text, primary key) — composed from route + identifierwindow_start(timestamp) — start of the time windowcount(integer) — request count within the windowupdated_at(timestamp)
Key format examples:
auth:login:ip:1.2.3.4auth:login:email:user@example.comentries:write:user:123
Query Pattern (High-Level)
- On each request:
- Compute key and current window
- Attempt upsert: increment
countif within window - If
countexceeds limit, respond 429
Cleanup / Retention
- Expired rows can accumulate; set a retention window (e.g., 24–72 hours)
- Plan a periodic cleanup task or opportunistic cleanup in code paths
- Avoid large table growth by deleting rows older than retention
Operational Considerations
- Postgres rate limiting adds read/write load to the primary DB
- Use indexes on
keyandwindow_startfor fast lookups - Monitor query latency and lock contention under burst traffic
- Consider Redis migration when DB contention or volume increases
Migration Path
- See docs/POSTGRES_TO_REDIS_RATELIMITTING_MIGRATION_REFERENCE.md for triggers and Redis ops guidance.
Last updated: 2026-02-09