# Subtask: Database Schema Design **Parent Task**: Decomp/001 **Subtask ID**: Decomp/001-01 **Dependencies**: None ## Description Design and implement the database schema for URL storage, including tables for URLs, analytics, and rate limiting. Support 10M URLs with proper indexing for fast lookups. ## Requirements - Store original URLs, short codes, custom aliases - Support link expiration with TTL - Track creation timestamp and access counts - Handle duplicate URL detection efficiently - Support composite indexes for common query patterns ## Technical Specifications ### Technology Stack - **Database**: PostgreSQL (for ACID guarantees and complex queries) - **Connection Pooling**: pgbouncer or connection pooler ### Schema Tables ```sql -- URLs table CREATE TABLE urls ( id BIGSERIAL PRIMARY KEY, short_code VARCHAR(8) UNIQUE NOT NULL, original_url TEXT NOT NULL, custom_alias BOOLEAN DEFAULT FALSE, created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), expires_at TIMESTAMP WITH TIME ZONE, access_count BIGINT DEFAULT 0, checksum VARCHAR(64) -- For duplicate detection ); -- Indexes CREATE INDEX idx_short_code ON urls(short_code); CREATE INDEX idx_checksum ON urls(checksum); CREATE INDEX idx_expires_at ON urls(expires_at) WHERE expires_at IS NOT NULL; -- Analytics table (separate for performance) CREATE TABLE url_analytics ( id BIGSERIAL PRIMARY KEY, url_id BIGINT REFERENCES urls(id) ON DELETE CASCADE, clicked_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), user_agent TEXT, ip_address INET, country_code CHAR(2), city VARCHAR(100), referrer TEXT ); CREATE INDEX idx_url_id_clicked ON url_analytics(url_id, clicked_at DESC); -- Rate limiting table CREATE TABLE rate_limits ( id BIGSERIAL PRIMARY KEY, identifier VARCHAR(255) NOT NULL, -- IP or API key action VARCHAR(50) NOT NULL, -- 'create', 'redirect' window_start TIMESTAMP WITH TIME ZONE DEFAULT NOW(), request_count INTEGER DEFAULT 1, PRIMARY KEY (identifier, action, window_start) ); ``` ### Data Structures - **checksum**: SHA-256 hash of original URL for duplicate detection - **short_code**: Base62 encoded ID (6-8 characters) ## Acceptance Criteria - [ ] Schema SQL file created with all tables and indexes - [ ] Migration script for schema creation - [ ] Foreign key constraints properly defined - [ ] Indexes cover all query patterns (short_code lookup, duplicate detection, expiration cleanup) - [ ] Support for 10M+ rows without performance degradation ## Notes - **Trade-off**: Chose SQL over NoSQL for strong consistency and transaction support - **Scaling**: Consider partitioning by date for analytics table at 100M+ rows - **Cleanup**: Need background job for expired URL deletion (subtask dependency) ## Edge Cases - What happens when URL exceeds maximum length? (TEXT type handles this) - Concurrent inserts with same checksum? (UNIQUE constraint + application logic) - Timezone handling for expiration? (Always use UTC internally)