Files
Portfolio/supabase/migrations/20260125_create_rate_limits_table.sql
T

42 lines
1.8 KiB
SQL

-- Create rate_limits table for persistent rate limiting
-- This replaces the in-memory Map-based rate limiter
CREATE TABLE IF NOT EXISTS rate_limits (
-- Unique identifier (typically IP address)
identifier TEXT NOT NULL,
-- Number of requests in the current time window
count INTEGER NOT NULL DEFAULT 1,
-- Start of the rate limit window (for sliding window algorithm)
window_start TIMESTAMPTZ NOT NULL,
-- Timestamp when the record was created
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-- Timestamp when the record was last updated
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-- Primary key ensures one record per identifier per time window
PRIMARY KEY (identifier, window_start)
);
-- Index for fast lookups by identifier and window_start
-- This is critical for rate limiting performance
CREATE INDEX IF NOT EXISTS idx_rate_limits_identifier_window
ON rate_limits(identifier, window_start DESC);
-- Index for cleanup queries (to remove old rate limit records)
CREATE INDEX IF NOT EXISTS idx_rate_limits_window_start
ON rate_limits(window_start);
-- Add a comment to the table
COMMENT ON TABLE rate_limits IS 'Stores rate limiting data for API endpoints. Each record tracks request counts within a time window for a specific identifier (typically IP address).';
-- Add comments to columns for documentation
COMMENT ON COLUMN rate_limits.identifier IS 'Unique identifier for the client (typically IP address)';
COMMENT ON COLUMN rate_limits.count IS 'Number of requests made in the current time window';
COMMENT ON COLUMN rate_limits.window_start IS 'Start timestamp of the rate limit window';
COMMENT ON COLUMN rate_limits.created_at IS 'Timestamp when this record was first created';
COMMENT ON COLUMN rate_limits.updated_at IS 'Timestamp when this record was last updated';