{
  "schemaVersion": "1.0",
  "item": {
    "slug": "postgres-job-queue",
    "name": "Postgres Job Queue",
    "source": "tencent",
    "type": "skill",
    "category": "开发工具",
    "sourceUrl": "https://clawhub.ai/wpank/postgres-job-queue",
    "canonicalUrl": "https://clawhub.ai/wpank/postgres-job-queue",
    "targetPlatform": "OpenClaw"
  },
  "install": {
    "downloadMode": "redirect",
    "downloadUrl": "/downloads/postgres-job-queue",
    "sourceDownloadUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=postgres-job-queue",
    "sourcePlatform": "tencent",
    "targetPlatform": "OpenClaw",
    "installMethod": "Manual import",
    "extraction": "Extract archive",
    "prerequisites": [
      "OpenClaw"
    ],
    "packageFormat": "ZIP package",
    "includedAssets": [
      "README.md",
      "SKILL.md"
    ],
    "primaryDoc": "SKILL.md",
    "quickSetup": [
      "Download the package from Yavira.",
      "Extract the archive and review SKILL.md first.",
      "Import or place the package into your OpenClaw setup."
    ],
    "agentAssist": {
      "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
      "steps": [
        "Download the package from Yavira.",
        "Extract it into a folder your agent can access.",
        "Paste one of the prompts below and point your agent at the extracted folder."
      ],
      "prompts": [
        {
          "label": "New install",
          "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
        },
        {
          "label": "Upgrade existing",
          "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
        }
      ]
    },
    "sourceHealth": {
      "source": "tencent",
      "status": "healthy",
      "reason": "direct_download_ok",
      "recommendedAction": "download",
      "checkedAt": "2026-04-30T16:55:25.780Z",
      "expiresAt": "2026-05-07T16:55:25.780Z",
      "httpStatus": 200,
      "finalUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=network",
      "contentType": "application/zip",
      "probeMethod": "head",
      "details": {
        "probeUrl": "https://wry-manatee-359.convex.site/api/v1/download?slug=network",
        "contentDisposition": "attachment; filename=\"network-1.0.0.zip\"",
        "redirectLocation": null,
        "bodySnippet": null
      },
      "scope": "source",
      "summary": "Source download looks usable.",
      "detail": "Yavira can redirect you to the upstream package for this source.",
      "primaryActionLabel": "Download for OpenClaw",
      "primaryActionHref": "/downloads/postgres-job-queue"
    },
    "validation": {
      "installChecklist": [
        "Use the Yavira download entry.",
        "Review SKILL.md after the package is downloaded.",
        "Confirm the extracted package contains the expected setup assets."
      ],
      "postInstallChecks": [
        "Confirm the extracted package includes the expected docs or setup files.",
        "Validate the skill or prompts are available in your target agent workspace.",
        "Capture any manual follow-up steps the agent could not complete."
      ]
    },
    "downloadPageUrl": "https://openagent3.xyz/downloads/postgres-job-queue",
    "agentPageUrl": "https://openagent3.xyz/skills/postgres-job-queue/agent",
    "manifestUrl": "https://openagent3.xyz/skills/postgres-job-queue/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/postgres-job-queue/agent.md"
  },
  "agentAssist": {
    "summary": "Hand the extracted package to your coding agent with a concrete install brief instead of figuring it out manually.",
    "steps": [
      "Download the package from Yavira.",
      "Extract it into a folder your agent can access.",
      "Paste one of the prompts below and point your agent at the extracted folder."
    ],
    "prompts": [
      {
        "label": "New install",
        "body": "I downloaded a skill package from Yavira. Read SKILL.md from the extracted folder and install it by following the included instructions. Then review README.md for any prerequisites, environment setup, or post-install checks. Tell me what you changed and call out any manual steps you could not complete."
      },
      {
        "label": "Upgrade existing",
        "body": "I downloaded an updated skill package from Yavira. Read SKILL.md from the extracted folder, compare it with my current installation, and upgrade it while preserving any custom configuration unless the package docs explicitly say otherwise. Then review README.md for any prerequisites, environment setup, or post-install checks. Summarize what changed and any follow-up checks I should run."
      }
    ]
  },
  "documentation": {
    "source": "clawhub",
    "primaryDoc": "SKILL.md",
    "sections": [
      {
        "title": "PostgreSQL Job Queue",
        "body": "Production-ready job queue using PostgreSQL with priority scheduling, batch claiming, and progress tracking."
      },
      {
        "title": "When to Use",
        "body": "Need job queue but want to avoid Redis/RabbitMQ dependencies\nJobs need priority-based scheduling\nLong-running jobs need progress visibility\nJobs should survive service restarts"
      },
      {
        "title": "Schema Design",
        "body": "CREATE TABLE jobs (\n    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n    job_type VARCHAR(50) NOT NULL,\n    priority INT NOT NULL DEFAULT 100,\n    status VARCHAR(20) NOT NULL DEFAULT 'pending',\n    data JSONB NOT NULL DEFAULT '{}',\n    \n    -- Progress tracking\n    progress INT DEFAULT 0,\n    current_stage VARCHAR(100),\n    events_count INT DEFAULT 0,\n    \n    -- Worker tracking\n    worker_id VARCHAR(100),\n    claimed_at TIMESTAMPTZ,\n    \n    -- Timing\n    created_at TIMESTAMPTZ DEFAULT NOW(),\n    started_at TIMESTAMPTZ,\n    completed_at TIMESTAMPTZ,\n    \n    -- Retry handling\n    attempts INT DEFAULT 0,\n    max_attempts INT DEFAULT 3,\n    last_error TEXT,\n    \n    CONSTRAINT valid_status CHECK (\n        status IN ('pending', 'claimed', 'running', 'completed', 'failed', 'cancelled')\n    )\n);\n\n-- Critical: Partial index for fast claiming\nCREATE INDEX idx_jobs_claimable ON jobs (priority DESC, created_at ASC) \n    WHERE status = 'pending';\nCREATE INDEX idx_jobs_worker ON jobs (worker_id) \n    WHERE status IN ('claimed', 'running');"
      },
      {
        "title": "Batch Claiming with SKIP LOCKED",
        "body": "CREATE OR REPLACE FUNCTION claim_job_batch(\n    p_worker_id VARCHAR(100),\n    p_job_types VARCHAR(50)[],\n    p_batch_size INT DEFAULT 10\n) RETURNS SETOF jobs AS $$\nBEGIN\n    RETURN QUERY\n    WITH claimable AS (\n        SELECT id\n        FROM jobs\n        WHERE status = 'pending'\n          AND job_type = ANY(p_job_types)\n          AND attempts < max_attempts\n        ORDER BY priority DESC, created_at ASC\n        LIMIT p_batch_size\n        FOR UPDATE SKIP LOCKED  -- Critical: skip locked rows\n    ),\n    claimed AS (\n        UPDATE jobs\n        SET status = 'claimed',\n            worker_id = p_worker_id,\n            claimed_at = NOW(),\n            attempts = attempts + 1\n        WHERE id IN (SELECT id FROM claimable)\n        RETURNING *\n    )\n    SELECT * FROM claimed;\nEND;\n$$ LANGUAGE plpgsql;"
      },
      {
        "title": "Go Implementation",
        "body": "const (\n    PriorityExplicit   = 150  // User-requested\n    PriorityDiscovered = 100  // System-discovered\n    PriorityBackfill   = 30   // Background backfills\n)\n\ntype JobQueue struct {\n    db       *pgx.Pool\n    workerID string\n}\n\nfunc (q *JobQueue) Claim(ctx context.Context, types []string, batchSize int) ([]Job, error) {\n    rows, err := q.db.Query(ctx,\n        \"SELECT * FROM claim_job_batch($1, $2, $3)\",\n        q.workerID, types, batchSize,\n    )\n    if err != nil {\n        return nil, err\n    }\n    defer rows.Close()\n\n    var jobs []Job\n    for rows.Next() {\n        var job Job\n        if err := rows.Scan(&job); err != nil {\n            return nil, err\n        }\n        jobs = append(jobs, job)\n    }\n    return jobs, nil\n}\n\nfunc (q *JobQueue) Complete(ctx context.Context, jobID uuid.UUID) error {\n    _, err := q.db.Exec(ctx, `\n        UPDATE jobs \n        SET status = 'completed',\n            progress = 100,\n            completed_at = NOW()\n        WHERE id = $1`,\n        jobID,\n    )\n    return err\n}\n\nfunc (q *JobQueue) Fail(ctx context.Context, jobID uuid.UUID, errMsg string) error {\n    _, err := q.db.Exec(ctx, `\n        UPDATE jobs \n        SET status = CASE \n                WHEN attempts >= max_attempts THEN 'failed' \n                ELSE 'pending' \n            END,\n            last_error = $2,\n            worker_id = NULL,\n            claimed_at = NULL\n        WHERE id = $1`,\n        jobID, errMsg,\n    )\n    return err\n}"
      },
      {
        "title": "Stale Job Recovery",
        "body": "func (q *JobQueue) RecoverStaleJobs(ctx context.Context, timeout time.Duration) (int, error) {\n    result, err := q.db.Exec(ctx, `\n        UPDATE jobs \n        SET status = 'pending',\n            worker_id = NULL,\n            claimed_at = NULL\n        WHERE status IN ('claimed', 'running')\n          AND claimed_at < NOW() - $1::interval\n          AND attempts < max_attempts`,\n        timeout.String(),\n    )\n    if err != nil {\n        return 0, err\n    }\n    return int(result.RowsAffected()), nil\n}"
      },
      {
        "title": "Decision Tree",
        "body": "ScenarioApproachNeed guaranteed deliveryPostgreSQL queueNeed sub-ms latencyUse Redis instead< 1000 jobs/secPostgreSQL is fine> 10000 jobs/secAdd Redis layerNeed strict orderingSingle worker per type"
      },
      {
        "title": "Related Skills",
        "body": "Related: service-layer-architecture — Service patterns for job handlers\nRelated: realtime/dual-stream-architecture — Event publishing from jobs"
      },
      {
        "title": "NEVER Do",
        "body": "NEVER use SELECT then UPDATE — Race condition. Use SKIP LOCKED.\nNEVER claim without SKIP LOCKED — Workers will deadlock.\nNEVER store large payloads — Store references only.\nNEVER forget partial index — Claiming is slow without it."
      }
    ],
    "body": "PostgreSQL Job Queue\n\nProduction-ready job queue using PostgreSQL with priority scheduling, batch claiming, and progress tracking.\n\nWhen to Use\nNeed job queue but want to avoid Redis/RabbitMQ dependencies\nJobs need priority-based scheduling\nLong-running jobs need progress visibility\nJobs should survive service restarts\nSchema Design\nCREATE TABLE jobs (\n    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),\n    job_type VARCHAR(50) NOT NULL,\n    priority INT NOT NULL DEFAULT 100,\n    status VARCHAR(20) NOT NULL DEFAULT 'pending',\n    data JSONB NOT NULL DEFAULT '{}',\n    \n    -- Progress tracking\n    progress INT DEFAULT 0,\n    current_stage VARCHAR(100),\n    events_count INT DEFAULT 0,\n    \n    -- Worker tracking\n    worker_id VARCHAR(100),\n    claimed_at TIMESTAMPTZ,\n    \n    -- Timing\n    created_at TIMESTAMPTZ DEFAULT NOW(),\n    started_at TIMESTAMPTZ,\n    completed_at TIMESTAMPTZ,\n    \n    -- Retry handling\n    attempts INT DEFAULT 0,\n    max_attempts INT DEFAULT 3,\n    last_error TEXT,\n    \n    CONSTRAINT valid_status CHECK (\n        status IN ('pending', 'claimed', 'running', 'completed', 'failed', 'cancelled')\n    )\n);\n\n-- Critical: Partial index for fast claiming\nCREATE INDEX idx_jobs_claimable ON jobs (priority DESC, created_at ASC) \n    WHERE status = 'pending';\nCREATE INDEX idx_jobs_worker ON jobs (worker_id) \n    WHERE status IN ('claimed', 'running');\n\nBatch Claiming with SKIP LOCKED\nCREATE OR REPLACE FUNCTION claim_job_batch(\n    p_worker_id VARCHAR(100),\n    p_job_types VARCHAR(50)[],\n    p_batch_size INT DEFAULT 10\n) RETURNS SETOF jobs AS $$\nBEGIN\n    RETURN QUERY\n    WITH claimable AS (\n        SELECT id\n        FROM jobs\n        WHERE status = 'pending'\n          AND job_type = ANY(p_job_types)\n          AND attempts < max_attempts\n        ORDER BY priority DESC, created_at ASC\n        LIMIT p_batch_size\n        FOR UPDATE SKIP LOCKED  -- Critical: skip locked rows\n    ),\n    claimed AS (\n        UPDATE jobs\n        SET status = 'claimed',\n            worker_id = p_worker_id,\n            claimed_at = NOW(),\n            attempts = attempts + 1\n        WHERE id IN (SELECT id FROM claimable)\n        RETURNING *\n    )\n    SELECT * FROM claimed;\nEND;\n$$ LANGUAGE plpgsql;\n\nGo Implementation\nconst (\n    PriorityExplicit   = 150  // User-requested\n    PriorityDiscovered = 100  // System-discovered\n    PriorityBackfill   = 30   // Background backfills\n)\n\ntype JobQueue struct {\n    db       *pgx.Pool\n    workerID string\n}\n\nfunc (q *JobQueue) Claim(ctx context.Context, types []string, batchSize int) ([]Job, error) {\n    rows, err := q.db.Query(ctx,\n        \"SELECT * FROM claim_job_batch($1, $2, $3)\",\n        q.workerID, types, batchSize,\n    )\n    if err != nil {\n        return nil, err\n    }\n    defer rows.Close()\n\n    var jobs []Job\n    for rows.Next() {\n        var job Job\n        if err := rows.Scan(&job); err != nil {\n            return nil, err\n        }\n        jobs = append(jobs, job)\n    }\n    return jobs, nil\n}\n\nfunc (q *JobQueue) Complete(ctx context.Context, jobID uuid.UUID) error {\n    _, err := q.db.Exec(ctx, `\n        UPDATE jobs \n        SET status = 'completed',\n            progress = 100,\n            completed_at = NOW()\n        WHERE id = $1`,\n        jobID,\n    )\n    return err\n}\n\nfunc (q *JobQueue) Fail(ctx context.Context, jobID uuid.UUID, errMsg string) error {\n    _, err := q.db.Exec(ctx, `\n        UPDATE jobs \n        SET status = CASE \n                WHEN attempts >= max_attempts THEN 'failed' \n                ELSE 'pending' \n            END,\n            last_error = $2,\n            worker_id = NULL,\n            claimed_at = NULL\n        WHERE id = $1`,\n        jobID, errMsg,\n    )\n    return err\n}\n\nStale Job Recovery\nfunc (q *JobQueue) RecoverStaleJobs(ctx context.Context, timeout time.Duration) (int, error) {\n    result, err := q.db.Exec(ctx, `\n        UPDATE jobs \n        SET status = 'pending',\n            worker_id = NULL,\n            claimed_at = NULL\n        WHERE status IN ('claimed', 'running')\n          AND claimed_at < NOW() - $1::interval\n          AND attempts < max_attempts`,\n        timeout.String(),\n    )\n    if err != nil {\n        return 0, err\n    }\n    return int(result.RowsAffected()), nil\n}\n\nDecision Tree\nScenario\tApproach\nNeed guaranteed delivery\tPostgreSQL queue\nNeed sub-ms latency\tUse Redis instead\n< 1000 jobs/sec\tPostgreSQL is fine\n> 10000 jobs/sec\tAdd Redis layer\nNeed strict ordering\tSingle worker per type\nRelated Skills\nRelated: service-layer-architecture — Service patterns for job handlers\nRelated: realtime/dual-stream-architecture — Event publishing from jobs\nNEVER Do\nNEVER use SELECT then UPDATE — Race condition. Use SKIP LOCKED.\nNEVER claim without SKIP LOCKED — Workers will deadlock.\nNEVER store large payloads — Store references only.\nNEVER forget partial index — Claiming is slow without it."
  },
  "trust": {
    "sourceLabel": "tencent",
    "provenanceUrl": "https://clawhub.ai/wpank/postgres-job-queue",
    "publisherUrl": "https://clawhub.ai/wpank/postgres-job-queue",
    "owner": "wpank",
    "version": "1.0.0",
    "license": null,
    "verificationStatus": "Indexed source record"
  },
  "links": {
    "detailUrl": "https://openagent3.xyz/skills/postgres-job-queue",
    "downloadUrl": "https://openagent3.xyz/downloads/postgres-job-queue",
    "agentUrl": "https://openagent3.xyz/skills/postgres-job-queue/agent",
    "manifestUrl": "https://openagent3.xyz/skills/postgres-job-queue/agent.json",
    "briefUrl": "https://openagent3.xyz/skills/postgres-job-queue/agent.md"
  }
}