Pg fair queue

From KilimcininKorOglu/cli-tweaks · View interactive version

Pg fair queue is an AI agent skill from the GitHub repository KilimcininKorOglu/cli-tweaks. Audits a Postgres-backed task queue (schema plus pop query) for fairness and O(n) traps where one tenant's backlog starves others, and on request applies a write-time block-ID round-robin design with per-group concurrency limits.

How to use this skill

Skill file

Postgres Fair Queue

Deterministic round-robin across tenants/groups in a Postgres task queue, with constant-time pop and optional per-group concurrency limits. The trick: encode the round-robin rank into the task ID at write time so the pop query stays a plain ORDER BY id ... FOR UPDATE SKIP LOCKED index scan.

Default behavior is scan. Applying changes the ID scheme and adds tables; it is a migration, not a patch.

Usage

/pg-fair-queue            # Scan existing queue: fairness, scaling traps, concurrency (DEFAULT)
/pg-fair-queue scan       # Same as default
/pg-fair-queue fix        # Implement the block-ID design (schema + queries + worker changes)

The Problem

One FIFO queue: tenant Bob enqueues 10,000 tasks, tenant Alice enqueues 1. Alice waits behind all 10,000. Adding workers does not fix this; it only speeds up Bob.

Why Not `PARTITION BY`

The obvious fix — row_number() OVER (PARTITION BY group_key ORDER BY id) then ORDER BY rn, id — fails three ways:

  1. FOR UPDATE is not allowed with window functions. Splitting into two CTEs "works" but the first CTE selects rows already locked by other workers, and the second CTE's SKIP LOCKED then discards them — concurrent workers pop 0 rows.
  2. The window aggregate scans every QUEUED row. At ~25k queued rows the pop query exceeds the polling interval, workers stall, backlog grows, and the system cannot recover by adding workers.
  3. JOIN LATERAL per group scales with group count; decrementing ranks after reads scales with group size. Neither is constant-time.

The Design: Block-Addressed IDs

Partition the BIGINT ID space into blocks of BLOCK_LEN (e.g. 2^20 = 1,048,576). Each group has a small integer gid (< BLOCK_LEN) and a pointer block_addr to the last block it wrote into. A global pointer max_assigned_block tracks the block of the highest non-QUEUED task.

Task ID = gid + BLOCK_LEN × block_addr.

Enqueue for group j:

Consequences:

Constraints:

Phase 1: Scan

Read the schema and the pop query. Check:

| Check | Finding if present |

|--------------------------------------------------------------|------------------------------------------------------|

| Single global ORDER BY id/created_at with no group notion | No fairness; one tenant can starve all others |

| row_number() OVER (PARTITION BY ...) in pop path | O(queued rows) per pop; worker stall above ~25k rows |

| Window function + FOR UPDATE split across CTEs | Concurrent workers pop 0 rows (locked rows pre-selected) |

| ORDER BY random() | Non-deterministic; no ordering guarantees |

| No FOR UPDATE SKIP LOCKED | Duplicate dispatch under concurrent workers |

| Workers start simultaneously with fixed poll interval | Thundering herd on the pop query |

| No upper bound on QUEUED rows | Unrecoverable degradation under backlog |

| Per-group concurrency enforced in application memory | Not consistent across workers; races |

| Watermark/pointer maintained by ... WHERE status <> 'QUEUED' ORDER BY id DESC LIMIT 1 | O(queued) per pop; scans every queued row above the frontier |

| Pop query lacks index on (status, id) or partial index | Seq scan under load |

Report each finding with the EXPLAIN ANALYZE of the current pop query at a representative backlog (seed 25k and 1M rows if a test DB is available). Then recommend: block-ID design (strict fairness), or OVERFLOW gate + simpler queue (approximate fairness, higher write rate).

Phase 2: Fix

2.1 Schema

CREATE TYPE task_status AS ENUM ('QUEUED','RUNNING','SUCCEEDED','FAILED','CANCELLED','OVERFLOW');

CREATE TABLE task_groups (
    gid        BIGINT PRIMARY KEY,           -- dense small integer, < BLOCK_LEN
    group_key  TEXT NOT NULL UNIQUE,
    block_addr BIGINT NOT NULL
);

CREATE TABLE task_ptrs (                      -- single row
    singleton  BOOL PRIMARY KEY DEFAULT TRUE CHECK (singleton),
    max_assigned_block BIGINT NOT NULL DEFAULT 0
);
INSERT INTO task_ptrs DEFAULT VALUES;

CREATE TABLE tasks (
    id         BIGINT PRIMARY KEY,            -- assigned, NOT serial
    group_key  TEXT NOT NULL REFERENCES task_groups(group_key),
    status     task_status NOT NULL DEFAULT 'QUEUED',
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    args       JSONB NOT NULL DEFAULT '{}'
);
CREATE INDEX tasks_queued_idx ON tasks (id) WHERE status = 'QUEUED';

BLOCK_LEN is a constant in the application and in SQL (1048576). Put it in one place.

2.2 Enqueue

-- $1 group_key, $2 args
WITH g AS (
    INSERT INTO task_groups (gid, group_key, block_addr)
    VALUES (
        COALESCE((SELECT max(gid) FROM task_groups), -1) + 1,
        $1,
        (SELECT max_assigned_block FROM task_ptrs)
    )
    ON CONFLICT (group_key) DO UPDATE SET
        block_addr = GREATEST(task_groups.block_addr + 1,
                              (SELECT max_assigned_block FROM task_ptrs))
    RETURNING gid, block_addr
)
INSERT INTO tasks (id, group_key, args)
SELECT gid + 1048576 * block_addr, $1, $2 FROM g
RETURNING id;

The max(gid)+1 is racy under concurrent new groups; serialize new-group creation with an advisory lock (pg_advisory_xact_lock(hashtext('task_groups'))) or pre-register groups.

2.3 Pop (unchanged shape, with per-group concurrency)

-- $1 limit, $2 concurrency per group
WITH lo AS (
    SELECT COALESCE(min(id), 0) AS min_id FROM tasks WHERE status = 'QUEUED'
),
picked AS (
    SELECT id FROM tasks
    WHERE status = 'QUEUED'
      AND id >= (SELECT min_id FROM lo)
      AND id <  (SELECT min_id FROM lo) + $2::bigint * 1048576
    ORDER BY id
    FOR UPDATE SKIP LOCKED
    LIMIT $1
)
UPDATE tasks t SET status = 'RUNNING'
FROM picked WHERE t.id = picked.id
RETURNING t.*;

Drop the id < bound for no per-group limit.

The id < window bounds a group to at most c tasks in a single pop's candidate set (a group has one task per block, so c blocks hold at most c). It is not a hard cap on tasks RUNNING per group across workers over time. For a strict global limit, also track a running count per group and skip a group at its cap.

2.4 Advance the global pointer — same transaction as pop

max_assigned_block is the block of the dispatch frontier: the highest block whose tasks have left QUEUED. Advance it from the rows this pop just dispatched, not by scanning for the highest non-QUEUED task.

-- $1 = max(id) among the rows this pop returned (0 if it returned none)
UPDATE task_ptrs
SET max_assigned_block = GREATEST(max_assigned_block, $1::bigint / 1048576);

Pop takes the lowest QUEUED ids, so max(id) of the popped rows is the new frontier. This is O(popped) and keeps the pop transaction constant-time.

NEVER advance the pointer with SELECT ... WHERE status <> 'QUEUED' ORDER BY id DESC LIMIT 1. Under a backlog the highest ids are all QUEUED future blocks, so that scan skips every queued row above the frontier — O(queued) per pop, the exact trap this design exists to avoid.

Without this advance, idle groups keep landing in old blocks and fairness degrades.

2.5 Worker hygiene

Phase 3: Verification

# 1. Seed: 1000 groups, skewed (one group 90% of tasks), 1M rows
# 2. EXPLAIN ANALYZE the pop query — expect Index Scan on tasks_queued_idx, no WindowAgg, no Seq Scan
# 3. Run 10 workers simultaneously — each must pop `limit` rows on the first poll, none 0
# 4. Fairness: enqueue 1 task for a fresh group behind a 100k backlog; it must be dispatched within ~1 poll
# 5. Concurrency: with c=5, count RUNNING per group — never > 5 from a single pop window
# 6. Pointer: after draining, task_ptrs.max_assigned_block == max block of any group

Rules

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.