# Subtask: Database Schema for Task Queue **Parent Task**: Decomp/003 **Subtask ID**: Decomp/003-01 **Dependencies**: None ## Description Design and implement database schema for distributed task queue supporting task scheduling, priorities, retries, result storage, and workflow dependencies. Schema must support high write throughput (1M tasks/day). ## Requirements - Store tasks with metadata and arguments - Support task priorities (high, normal, low) - Track task status (pending, running, completed, failed) - Store task results and error messages - Support task dependencies (DAG execution) - Track retry counts and backoff schedules - Worker registration and heartbeat tracking - Task queue partitioning by queue name ## Technical Specifications **Database choice**: PostgreSQL for ACID, with Redis as broker for performance **Schema definition**: ```sql -- Task queues CREATE TABLE task_queues ( id SERIAL PRIMARY KEY, name VARCHAR(100) NOT NULL UNIQUE, description TEXT, priority INTEGER DEFAULT 5, -- Default priority for tasks in this queue max_retries INTEGER DEFAULT 3, retry_backoff_base INTEGER DEFAULT 2, -- Exponential backoff base retry_backoff_max INTEGER DEFAULT 3600, -- Max backoff in seconds created_at TIMESTAMP NOT NULL DEFAULT NOW(), is_active BOOLEAN DEFAULT TRUE ); -- Tasks table CREATE TABLE tasks ( id BIGSERIAL PRIMARY KEY, queue_id INTEGER NOT NULL REFERENCES task_queues(id) ON DELETE RESTRICT, task_name VARCHAR(200) NOT NULL, -- Function name to execute args JSONB DEFAULT '[]'::jsonb, -- Positional arguments kwargs JSONB DEFAULT '{}'::jsonb, -- Keyword arguments priority INTEGER DEFAULT 5, -- 0=highest, 10=lowest status VARCHAR(20) NOT NULL DEFAULT 'pending', -- pending, running, completed, failed, cancelled result JSONB, -- Task result (if successful) error TEXT, -- Error message (if failed) traceback TEXT, -- Full traceback (if failed) retry_count INTEGER DEFAULT 0, max_retries INTEGER DEFAULT 3, scheduled_at TIMESTAMP, -- For scheduled/cron tasks started_at TIMESTAMP, completed_at TIMESTAMP, expires_at TIMESTAMP, -- Result expiration worker_id INTEGER, -- Worker that executed the task parent_task_id BIGINT REFERENCES tasks(id) ON DELETE CASCADE, -- For workflow/chaining task_group_id VARCHAR(100), -- For grouping related tasks metadata JSONB DEFAULT '{}'::jsonb, -- Custom metadata created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW() ); -- Indexes for task processing CREATE INDEX idx_tasks_queue_status ON tasks(queue_id, status) WHERE status IN ('pending', 'retry'); CREATE INDEX idx_tasks_priority ON tasks(queue_id, priority, created_at) WHERE status IN ('pending', 'retry'); CREATE INDEX idx_tasks_scheduled ON tasks(scheduled_at) WHERE status = 'pending' AND scheduled_at IS NOT NULL; CREATE INDEX idx_tasks_worker ON tasks(worker_id) WHERE status = 'running'; CREATE INDEX idx_tasks_parent ON tasks(parent_task_id) WHERE status != 'completed'; CREATE INDEX idx_tasks_group ON tasks(task_group_id); CREATE INDEX idx_tasks_created_at ON tasks(created_at DESC); -- Task dependencies (DAG support) CREATE TABLE task_dependencies ( id BIGSERIAL PRIMARY KEY, task_id BIGINT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE, depends_on_task_id BIGINT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE, UNIQUE(task_id, depends_on_task_id) ); CREATE INDEX idx_task_deps_task ON task_dependencies(task_id); CREATE INDEX idx_task_deps_depends ON task_dependencies(depends_on_task_id); -- Workers table CREATE TABLE workers ( id SERIAL PRIMARY KEY, worker_name VARCHAR(200) NOT NULL UNIQUE, pid INTEGER, -- Process ID hostname VARCHAR(255), queues JSONB DEFAULT '[]'::jsonb, -- Queues this worker processes concurrency INTEGER DEFAULT 1, -- Max concurrent tasks current_tasks INTEGER DEFAULT 0, -- Currently running tasks last_heartbeat TIMESTAMP NOT NULL DEFAULT NOW(), started_at TIMESTAMP NOT NULL DEFAULT NOW(), metadata JSONB DEFAULT '{}'::jsonb ); CREATE INDEX idx_workers_heartbeat ON workers(last_heartbeat); CREATE INDEX idx_workers_active ON workers(last_heartbeat) WHERE last_heartbeat > NOW() - INTERVAL '1 minute'; -- Task execution history (for analytics) CREATE TABLE task_history ( id BIGSERIAL PRIMARY KEY, task_id BIGINT NOT NULL REFERENCES tasks(id) ON DELETE CASCADE, worker_id INTEGER REFERENCES workers(id) ON DELETE SET NULL, status VARCHAR(20) NOT NULL, timestamp TIMESTAMP NOT NULL DEFAULT NOW(), details JSONB ); CREATE INDEX idx_task_history_task ON task_history(task_id, timestamp); CREATE INDEX idx_task_history_timestamp ON task_history(timestamp DESC); -- Periodic/Cron tasks CREATE TABLE periodic_tasks ( id SERIAL PRIMARY KEY, name VARCHAR(200) NOT NULL UNIQUE, task_name VARCHAR(200) NOT NULL, args JSONB DEFAULT '[]'::jsonb, kwargs JSONB DEFAULT '{}'::jsonb, queue_id INTEGER NOT NULL REFERENCES task_queues(id), cron_expression VARCHAR(100) NOT NULL, -- Standard cron expression last_run_at TIMESTAMP, next_run_at TIMESTAMP, is_active BOOLEAN DEFAULT TRUE, metadata JSONB DEFAULT '{}'::jsonb, created_at TIMESTAMP NOT NULL DEFAULT NOW() ); CREATE INDEX idx_periodic_next_run ON periodic_tasks(next_run_at) WHERE is_active = TRUE; -- Locks for distributed coordination CREATE TABLE advisory_locks ( lock_key VARCHAR(255) PRIMARY KEY, acquired_by VARCHAR(255) NOT NULL, acquired_at TIMESTAMP NOT NULL DEFAULT NOW(), expires_at TIMESTAMP NOT NULL ); CREATE INDEX idx_locks_expires ON advisory_locks(expires_at); -- Functions and triggers CREATE OR REPLACE FUNCTION update_updated_at() RETURNS TRIGGER AS $$ BEGIN NEW.updated_at = NOW(); RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER tasks_updated_at BEFORE UPDATE ON tasks FOR EACH ROW EXECUTE FUNCTION update_updated_at(); -- Function to dequeue tasks (atomic, with FOR UPDATE SKIP LOCKED) CREATE OR REPLACE FUNCTION dequeue_tasks( p_queue_id INTEGER, p_worker_id INTEGER, p_limit INTEGER DEFAULT 1 ) RETURNS SETOF tasks AS $$ DECLARE task_record tasks; BEGIN -- Update worker heartbeat UPDATE workers SET last_heartbeat = NOW() WHERE id = p_worker_id; -- Find and lock pending tasks FOR task_record IN SELECT t.id FROM tasks t WHERE t.queue_id = p_queue_id AND t.status = 'pending' AND (t.scheduled_at IS NULL OR t.scheduled_at <= NOW()) AND NOT EXISTS ( -- Check if dependencies are satisfied SELECT 1 FROM task_dependencies td WHERE td.task_id = t.id AND NOT EXISTS ( SELECT 1 FROM tasks dep WHERE dep.id = td.depends_on_task_id AND dep.status = 'completed' ) ) ORDER BY t.priority ASC, t.created_at ASC LIMIT p_limit FOR UPDATE SKIP LOCKED LOOP -- Mark as running UPDATE tasks SET status = 'running', started_at = NOW(), worker_id = p_worker_id WHERE id = task_record.id; -- Increment worker's current task count UPDATE workers SET current_tasks = current_tasks + 1 WHERE id = p_worker_id; RETURN QUERY SELECT * FROM tasks WHERE id = task_record.id; END LOOP; RETURN; END; $$ LANGUAGE plpgsql; ``` **Redis data structures for broker** (alternative/complement to SQL): ``` # Task queue (list) queue:{name}:pending -> [task_id1, task_id2, ...] # Task data (hash) task:{task_id} -> { "queue": "default", "name": "task_function", "args": "[...]", "kwargs": "{...}", "priority": "5", "retry_count": "0" } # Scheduled tasks (sorted set) schedule:tasks -> {score: scheduled_time, member: task_json} # Running tasks (set) workers:{worker_id}:running -> {task_id1, task_id2} # Task results (string with expiration) result:{task_id} -> json_result (TTL: 1 day) # Worker heartbeats (hash with expiration) worker:{worker_id}:heartbeat -> {"last_seen": timestamp} # Locks (for distributed operations) lock:{name} -> worker_id (with TTL) ``` ## Acceptance Criteria - [ ] All tables created without errors - [ ] Foreign key constraints enforced - [ ] dequeue_tasks function atomically reserves tasks - [ ] SKIP LOCKED prevents worker contention - [ ] Task dependencies tracked correctly - [ ] Worker heartbeat tracking functional - [ ] Cron tasks can be scheduled ## Notes **Trade-offs**: - PostgreSQL vs Redis broker: PostgreSQL for persistence, Redis for performance - Skip locked vs advisory locks: Skip locked simpler for queues **Scalability**: - Partition tasks table by queue_id for very high throughput - Consider separate history database for analytics **Alternatives considered**: - Redis-only: Rejected, lacks durability for requirements - MongoDB: Rejected, weaker transaction support