Files
test-glm47/ai_coder_1/subtasks/Decomp-002-01.md
T
2026-02-04 16:54:36 +10:00

8.9 KiB

Subtask: Database Schema for Chat Service

Parent Task: Decomp/002 Subtask ID: Decomp/002-01 Dependencies: None

Description

Design and implement database schema for real-time chat service supporting users, servers, channels, messages, and presence. Schema must support high write throughput (100K concurrent users) and efficient pagination for message history.

Requirements

  • Store users with profile information
  • Store servers/guilds (like Discord)
  • Store channels within servers
  • Store messages with metadata
  • Store user presence (online/offline/away)
  • Support message threading/replies
  • Support message reactions
  • Store file attachments metadata
  • Efficient pagination for message history
  • Indexes for common query patterns

Technical Specifications

Database choice: PostgreSQL (for ACID, JSONB, full-text search)

Schema definition:

-- Users table
CREATE TABLE users (
    id BIGSERIAL PRIMARY KEY,
    username VARCHAR(32) NOT NULL UNIQUE,
    email VARCHAR(255) NOT NULL UNIQUE,
    password_hash VARCHAR(255) NOT NULL,
    display_name VARCHAR(100),
    avatar_url TEXT,
    bio TEXT,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    last_seen_at TIMESTAMP
);

CREATE INDEX idx_users_username ON users(username);
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_last_seen ON users(last_seen_at);

-- Servers/Guilds table
CREATE TABLE servers (
    id BIGSERIAL PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    owner_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    icon_url TEXT,
    description TEXT,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
    max_members INTEGER DEFAULT 100000,
    region VARCHAR(10)
);

CREATE INDEX idx_servers_owner ON servers(owner_id);

-- Server members (many-to-many with roles)
CREATE TABLE server_members (
    id BIGSERIAL PRIMARY KEY,
    server_id BIGINT NOT NULL REFERENCES servers(id) ON DELETE CASCADE,
    user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    nickname VARCHAR(100),
    joined_at TIMESTAMP NOT NULL DEFAULT NOW(),
    roles JSONB DEFAULT '[]'::jsonb,
    UNIQUE(server_id, user_id)
);

CREATE INDEX idx_server_members_server ON server_members(server_id);
CREATE INDEX idx_server_members_user ON server_members(user_id);

-- Channels table
CREATE TABLE channels (
    id BIGSERIAL PRIMARY KEY,
    server_id BIGINT REFERENCES servers(id) ON DELETE CASCADE,  -- NULL for DMs
    type VARCHAR(20) NOT NULL,  -- 'text', 'voice', 'dm', 'category'
    name VARCHAR(100) NOT NULL,
    position INTEGER DEFAULT 0,
    topic TEXT,
    is_nsfw BOOLEAN DEFAULT FALSE,
    slowmode_seconds INTEGER DEFAULT 0,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
    parent_id BIGINT REFERENCES channels(id)  -- For categories
);

CREATE INDEX idx_channels_server ON channels(server_id);
CREATE INDEX idx_channels_type ON channels(type);
CREATE INDEX idx_channels_parent ON channels(parent_id);

-- Direct message channels
CREATE TABLE dm_channels (
    id BIGSERIAL PRIMARY KEY,
    type VARCHAR(20) NOT NULL,  -- 'dm' (2 users), 'group_dm' (3+ users)
    created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE TABLE dm_channel_members (
    channel_id BIGINT NOT NULL REFERENCES dm_channels(id) ON DELETE CASCADE,
    user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    joined_at TIMESTAMP NOT NULL DEFAULT NOW(),
    UNIQUE(channel_id, user_id)
);

CREATE INDEX idx_dm_members_channel ON dm_channel_members(channel_id);
CREATE INDEX idx_dm_members_user ON dm_channel_members(user_id);

-- Messages table (partitioned by month for scalability)
CREATE TABLE messages (
    id BIGSERIAL PRIMARY KEY,
    channel_id BIGINT NOT NULL REFERENCES channels(id) ON DELETE CASCADE,
    author_id BIGINT NOT NULL REFERENCES users(id) ON DELETE SET NULL,
    content TEXT NOT NULL,
    type VARCHAR(20) DEFAULT 'default',  -- 'default', 'reply', 'system'
    reply_to_id BIGINT REFERENCES messages(id) ON DELETE SET NULL,
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
    edited_at TIMESTAMP,
    is_pinned BOOLEAN DEFAULT FALSE,
    metadata JSONB DEFAULT '{}'::jsonb,  -- For extensions
    mentions JSONB DEFAULT '[]'::jsonb,  -- Array of user IDs
    -- Denormalized for pagination
    channel_position BIGINT NOT NULL  -- Per-channel sequence number
);

-- Partition messages by month
CREATE TABLE messages_2025_02 PARTITION OF messages
    FOR VALUES FROM ('2025-02-01') TO ('2025-03-01');

CREATE INDEX idx_messages_channel ON messages(channel_id, channel_position DESC);
CREATE INDEX idx_messages_author ON messages(author_id);
CREATE INDEX idx_messages_created ON messages(created_at DESC);
CREATE INDEX idx_messages_reply_to ON messages(reply_to_id);
CREATE INDEX idx_messages_mentions ON messages USING GIN(mentions);
CREATE INDEX idx_messages_fts ON messages USING GIN(to_tsvector('english', content));

-- Message reactions
CREATE TABLE message_reactions (
    id BIGSERIAL PRIMARY KEY,
    message_id BIGINT NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
    user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    emoji VARCHAR(100) NOT NULL,  -- Unicode or custom emoji ID
    emoji_type VARCHAR(10) DEFAULT 'unicode',  -- 'unicode', 'custom'
    created_at TIMESTAMP NOT NULL DEFAULT NOW(),
    UNIQUE(message_id, user_id, emoji)
);

CREATE INDEX idx_reactions_message ON message_reactions(message_id);
CREATE INDEX idx_reactions_user ON message_reactions(user_id);

-- User presence
CREATE TABLE user_presence (
    user_id BIGINT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
    status VARCHAR(20) NOT NULL DEFAULT 'offline',  -- 'online', 'idle', 'dnd', 'offline'
    last_updated TIMESTAMP NOT NULL DEFAULT NOW(),
    active_device_id VARCHAR(100),  -- Socket ID for connection tracking
    activities JSONB DEFAULT '[]'::jsonb  -- Playing X, listening to Y
);

CREATE INDEX idx_presence_status ON user_presence(status);
CREATE INDEX idx_presence_updated ON user_presence(last_updated);

-- File attachments
CREATE TABLE attachments (
    id BIGSERIAL PRIMARY KEY,
    message_id BIGINT NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
    filename VARCHAR(255) NOT NULL,
    content_type VARCHAR(100) NOT NULL,
    size_bytes BIGINT NOT NULL,
    storage_path TEXT NOT NULL,  -- S3 key or local path
    width INTEGER,  -- For images/videos
    height INTEGER,
    duration_seconds INTEGER,  -- For audio/video
    is_spoiler BOOLEAN DEFAULT FALSE,
    created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_attachments_message ON attachments(message_id);
CREATE INDEX idx_attachments_type ON attachments(content_type);

-- Read receipts (optional, for read status)
CREATE TABLE channel_read_state (
    user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    channel_id BIGINT NOT NULL REFERENCES channels(id) ON DELETE CASCADE,
    last_read_message_id BIGINT NOT NULL REFERENCES messages(id),
    last_read_at TIMESTAMP NOT NULL DEFAULT NOW(),
    mention_count INTEGER DEFAULT 0,
    UNIQUE(user_id, channel_id)
);

CREATE INDEX idx_read_state_user_channel ON channel_read_state(user_id, channel_id);

Partition management:

-- Function to create monthly partitions
CREATE OR REPLACE FUNCTION create_monthly_partition(month_date DATE)
RETURNS VOID AS $$
DECLARE
    partition_name TEXT;
    start_date TEXT;
    end_date TEXT;
BEGIN
    partition_name := 'messages_' || to_char(month_date, 'YYYY_MM');
    start_date := to_char(month_date, 'YYYY-MM-DD');
    end_date := to_char(month_date + INTERVAL '1 month', 'YYYY-MM-DD');

    EXECUTE format(
        'CREATE TABLE IF NOT EXISTS %I PARTITION OF messages
         FOR VALUES FROM (%L) TO (%L)',
        partition_name, start_date, end_date
    );
END;
$$ LANGUAGE plpgsql;

Acceptance Criteria

  • All tables created without errors
  • Foreign key constraints enforced
  • Unique constraints prevent duplicates
  • Partitioning allows efficient time-based queries
  • Indexes support common query patterns
  • JSONB fields enable flexible metadata storage
  • Full-text search index on message content

Notes

Trade-offs:

  • PostgreSQL vs MongoDB: PostgreSQL chosen for ACID guarantees and mature tooling
  • Partitioning by month: Balances partition count with query efficiency
  • Channel position denormalization: Speeds up pagination at cost of write complexity

Scalability considerations:

  • Messages table grows fastest — partitioning essential
  • Consider archive for messages older than 6 months
  • Read receipts can be moved to separate database (Redis)

Alternatives considered:

  • Single messages table: Rejected, doesn't scale to billions of messages
  • NoSQL document store: Rejected, complex queries (mentions, reactions) harder
  • Separate DB per server: Rejected, too complex for initial implementation