Agent skill

Postgres Concurrent Schema Init Deadlock

by divinevideo in divinevideo/divine-mobile

Fix PostgreSQL deadlock errors caused by concurrent schema initialization in worker processes.

MPL-2.0Auto-check passedDatabases

Install Postgres Concurrent Schema Init Deadlock

skills CLI
$ npx skills add divinevideo/divine-mobile --skill postgres-concurrent-schema-init-deadlock -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install divinevideo/divine-mobile postgres-concurrent-schema-init-deadlock --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/divinevideo/divine-mobile.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.agents/skills/postgres-concurrent-schema-init-deadlock .claude/skills/postgres-concurrent-schema-init-deadlock && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
postgres-concurrent-schema-init-deadlock
GitHub stars
265
Token cost
~1.1k tokens
SKILL.md length
281 words
Files
1
Skills in repo
103
Repo updated
First seen
Licence
MPL-2.0

At a glance

Fix PostgreSQL deadlock errors caused by concurrent schema initialization in worker processes.

  • Works in 3 steps: CREATE INDEX IF NOT EXISTS still… → Multiple processes acquiring locks on… → Even "safe" DDL can conflict when…
  • Psycopg2.errors.DeadlockDetected during CREATE INDEX/TABLE IF NOT EXISTS
  • SKILL.md covers Problem, Context / Trigger Conditions, Why This Happens and Solution, plus 4 more sections
  • Calls python and gcloud

What it does

Postgres Concurrent Schema Init Deadlock is an agent skill from divinevideo/divine-mobile. Fix PostgreSQL deadlock errors caused by concurrent schema initialization in worker processes. Use when: (1) psycopg2.errors.DeadlockDetected during CREATE INDEX/TABLE IF NOT EXISTS, (2) Multiple Cloud Run jobs, Kubernetes pods, or worker processes start simultaneously, (3) Error shows "Process X waits for RowExclusiveLock... blocked by process Y", (4) initschema() or migration code runs at worker startup. The key insight: "IF NOT EXISTS" is NOT truly concurrent-safe - PostgreSQL still acquires locks that can…

Its SKILL.md is about 1.1k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Databases, covering Container orchestration. It works with PostgreSQL, Cloud Run and Kubernetes. The licence is MPL-2.0.

When your agent uses it

  • Psycopg2.errors.DeadlockDetected during CREATE INDEX/TABLE IF NOT EXISTS
  • Multiple Cloud Run jobs
  • Kubernetes pods
  • Worker processes start simultaneously

Example prompts

  • “Process X waits for RowExclusiveLock... blocked by process Y”
  • “IF NOT EXISTS”
  • “/postgres-concurrent-schema-init-deadlock”

Requirements

  • Python 3

Workflow steps

3 steps, taken from the first numbered list in SKILL.md.

  1. CREATE INDEX IF NOT EXISTS still acquires locks before checking existence
  2. Multiple processes acquiring locks on different objects can deadlock
  3. Even "safe" DDL can conflict when executed concurrently

What it can do on your machine

Read from SKILL.md and the folder at commit 8d5fbf2. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • python
    • gcloud

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • postgresql.org

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Postgres Concurrent Schema Init Deadlock loads about 1.1k tokens when it runs. Until then it costs about 142 tokens; SKILL.md has 281 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~142
When it runs · the whole SKILL.md, loaded when a task matches
~1.1k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from divinevideo/divine-mobile at commit 8d5fbf2, republished under its MPL-2.0 licence (© divinevideo). 281 words, ~1,067 tokens.

Download SKILL.mdSave it as .claude/skills/postgres-concurrent-schema-init-deadlock/SKILL.md (or your agent's skills folder).
name
postgres-concurrent-schema-init-deadlock
description
Fix PostgreSQL deadlock errors caused by concurrent schema initialization in worker processes. Use when: (1) psycopg2.errors.DeadlockDetected during CREATE INDEX/TABLE IF NOT EXISTS, (2) Multiple Cloud Run jobs, Kubernetes pods, or worker processes start simultaneously, (3) Error shows "Process X waits for RowExclusiveLock... blocked by process Y", (4) init_schema() or migration code runs at worker startup. The key insight: "IF NOT EXISTS" is NOT truly concurrent-safe - PostgreSQL still acquires locks that can deadlock.
author
Claude Code
version
1.0.0
date
2026-01-29

PostgreSQL Concurrent Schema Init Deadlock

Problem

Multiple worker processes (Cloud Run jobs, K8s pods, serverless functions) starting simultaneously all try to run schema initialization code, causing PostgreSQL deadlocks even when using "IF NOT EXISTS" clauses.

Context / Trigger Conditions

  • Error: psycopg2.errors.DeadlockDetected: deadlock detected
  • Log shows: Process X waits for RowExclusiveLock on relation... blocked by process Y
  • Multiple workers/jobs starting at roughly the same time
  • Each worker calls init_schema() or runs migrations at startup
  • Using CREATE TABLE IF NOT EXISTS or CREATE INDEX IF NOT EXISTS

Why This Happens

PostgreSQL's IF NOT EXISTS is not concurrent-safe:

  1. CREATE INDEX IF NOT EXISTS still acquires locks before checking existence
  2. Multiple processes acquiring locks on different objects can deadlock
  3. Even "safe" DDL can conflict when executed concurrently

Solution

Schema already exists - don't run init_schema() in workers:

python
with Database() as db:
    # Schema already exists in production - skip to avoid deadlocks
    # db.init_schema()

    # ... worker code
Option 2: Use Advisory Locks

Serialize schema init with PostgreSQL advisory locks:

python
def init_schema_safe(self):
    cursor = self._cursor()
    # Acquire advisory lock (blocks other processes)
    cursor.execute("SELECT pg_advisory_lock(12345)")
    try:
        self.init_schema()
    finally:
        cursor.execute("SELECT pg_advisory_unlock(12345)")
        self.conn.commit()
Option 3: Separate Migration Step

Run migrations as a separate job before starting workers:

bash
# In deployment pipeline
python -m src.migrate  # Single process, runs first
# Then start workers
gcloud run jobs execute worker-job
Option 4: Lock Timeout + Retry

Set lock timeout and retry on deadlock:

python
def init_schema_with_retry(self, max_retries=3):
    for attempt in range(max_retries):
        try:
            cursor = self._cursor()
            cursor.execute("SET lock_timeout = '5s'")
            self.init_schema()
            return
        except psycopg2.errors.DeadlockDetected:
            self.conn.rollback()
            if attempt == max_retries - 1:
                raise
            time.sleep(random.uniform(1, 3))

Verification

After applying fix:

  1. Start multiple workers simultaneously
  2. Check logs for absence of deadlock errors
  3. Verify all workers start successfully

Example

Before (deadlocks with 6 concurrent Cloud Run jobs):

python
# src/download.py
with VineDatabase() as db:
    db.init_schema()  # DEADLOCK when multiple jobs start!
    # ... download logic

After (no deadlocks):

python
# src/download.py
with VineDatabase() as db:
    # Schema already exists in production - skip to avoid deadlocks
    # db.init_schema()
    # ... download logic

Notes

  • This applies to any concurrent worker pattern: Cloud Run, Celery, Kubernetes, Lambda
  • The deadlock can be intermittent - depends on exact timing of worker starts
  • CREATE TABLE IF NOT EXISTS is generally safer than CREATE INDEX IF NOT EXISTS
  • Cloud Run jobs often start simultaneously when triggered, making this common
  • Consider using database migration tools (Alembic, Flyway) with proper locking

References

© divinevideo, MPL-2.0. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in .agents/skills/postgres-concurrent-schema-init-deadlock of divinevideo/divine-mobile.

Open the folder on GitHubat commit 8d5fbf2

Compare with similar skills

Postgres Concurrent Schema Init Deadlock next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Postgres Concurrent Schema Init Deadlock compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Postgres Concurrent Schema Init Deadlock this skilldivinevideo/divine-mobile265—~1.1kAutomated safety check: PassMPL-2.0
Archestra Dev Investigatearchestra-ai/archestra4.3k—~831Automated safety check: PassCustom licence
Devopsnicepkg/auto-company1922 repos~814Automated safety check: PassMIT
Opensourcefaqdigoal/blog8.6k—~966Automated safety check: PassGPL-2.0
Google Cloud Solution Guided Gke AI Migrationgoogle/skills21k—~8.3kAutomated safety check: PassApache-2.0
Azure Cloud Migratemicrosoft/GitHub-Copilot-for-Azure2551 repos~1.1kAutomated safety check: PassMIT

Similar skills

  • Archestra Dev Investigate

    archestra-ai/archestra

    A skill your agent uses when investigating Archestra bugs or incidents — staging issues, backend 50x errors, Drizzle failed queries, DB connection pressure, deploy regressions, or Kubernetes/runtime…

    4.3k GitHub stars~831 tokensUpdated today
    DevOps & CloudAuto-check passed
  • Devops

    nicepkg/auto-company

    Deploy to Cloudflare (Workers, R2, D1), Docker, GCP (Cloud Run, GKE), Kubernetes (kubectl, Helm).

    192 GitHub starsUsed in 2 repos~814 tokens
    DevOps & CloudAuto-check passed
  • Opensourcefaq

    digoal/blog

    解答与开源产品有关的深度技术问题,输出图文并茂的 Markdown 技术文章。触发条件:用户提出与开源项目(如 PostgreSQL、Redis、Kafka、Kubernetes、ClickHouse、Flink 等)相关的技术问题,并提供源码目录或 URL、deepwiki repo 名称。即使用户只说"帮我解答这个开源问题"或"分析一下这个项目的某个机制",也应使用本…

    8.6k GitHub stars~966 tokensUpdated 9 days ago
    DatabasesAuto-check passed
  • Guides the migration of existing AI workloads (Cloud Run, Gemini API, Gemini Enterprise Agent Platform) to self-hosted GKE inference using gcloud and kubectl.

    21k GitHub stars~8.3k tokensUpdated today
    DevOps & CloudAuto-check passed
  • Azure Cloud Migrate

    microsoft/GitHub-Copilot-for-Azure

    Official

    Assess and migrate cross-cloud workloads to Azure with reports and code conversion.

    255 GitHub starsUsed in 1 repo~1.1k tokens
    DevOps & CloudAuto-check passed
  • Dt Obs GCP

    Dynatrace/dynatrace-for-ai

    GCP cloud resources including Compute Engine, GKE, Cloud Run, Pub/Sub, VPC networking, DNS, IAM, Secret Manager, and monitoring.

    161 GitHub stars~2.5k tokensUpdated 6 days ago
    DevOps & CloudAuto-check passed

More from divinevideo/divine-mobile

All 103 skills in this repo
  • Fix ArgoCD ExternalSecret deployment failing with "namespace X is not permitted in project Y".

    265 GitHub stars~931 tokensUpdated today
    Auto-check passed
  • Art Direct

    divinevideo/divine-mobile

    Art direction for any content — reads text, PDF, Word, HTML, PPT, then proposes 2-3 creative directions with photography style, mood, and visual language.

    265 GitHub stars~4.8k tokensUpdated today
    Auto-check passed
  • Async Await Null Race Condition

    divinevideo/divine-mobile

    Fix "Null check operator used on a null value" errors when an object is set to null during an async await.

    265 GitHub stars~881 tokensUpdated today
    Auto-check passed
  • AWS V4 Signing Custom Headers Gcs

    divinevideo/divine-mobile

    Add custom metadata headers (x-amz-meta-) to AWS v4 signed requests for GCS S3-compatible API.

    265 GitHub stars~1k tokensUpdated today
    Auto-check passed
  • Bash Herestring Newline Secrets

    divinevideo/divine-mobile

    Fix password/secret authentication failures caused by trailing newlines when creating Google Cloud secrets (or similar) with bash here-strings.

    265 GitHub stars~791 tokensUpdated today
    Auto-check passed
  • Fix silent video/media processing failures caused by URL extraction code that filters on file extensions (.mp4, .webm, .webp).

    265 GitHub stars~1.1k tokensUpdated today
    Auto-check passed

Questions about Postgres Concurrent Schema Init Deadlock

What does Postgres Concurrent Schema Init Deadlock do?

Fix PostgreSQL deadlock errors caused by concurrent schema initialization in worker processes. Postgres Concurrent Schema Init Deadlock is an agent skill from divinevideo/divine-mobile. Fix PostgreSQL deadlock errors caused by concurrent schema initialization in worker processes.

When should I use Postgres Concurrent Schema Init Deadlock?

Postgres Concurrent Schema Init Deadlock fits situations like: psycopg2.errors.DeadlockDetected during CREATE INDEX/TABLE IF NOT EXISTS; multiple Cloud Run jobs; Kubernetes pods; worker processes start simultaneously.

How do I install Postgres Concurrent Schema Init Deadlock in Claude Code?

Run `npx skills add divinevideo/divine-mobile --skill postgres-concurrent-schema-init-deadlock -a claude-code`. Or copy the skill folder (.agents/skills/postgres-concurrent-schema-init-deadlock in divinevideo/divine-mobile) into .claude/skills/postgres-concurrent-schema-init-deadlock in your project. Claude Code loads it when a task matches its description.

How do I install Postgres Concurrent Schema Init Deadlock in Codex?

Run `npx skills add divinevideo/divine-mobile --skill postgres-concurrent-schema-init-deadlock -a codex`. Or copy the skill folder (.agents/skills/postgres-concurrent-schema-init-deadlock in divinevideo/divine-mobile) into .agents/skills/postgres-concurrent-schema-init-deadlock in your project. Codex loads it when a task matches its description.

Can I use Postgres Concurrent Schema Init Deadlock in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add divinevideo/divine-mobile --skill postgres-concurrent-schema-init-deadlock -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/postgres-concurrent-schema-init-deadlock, .gemini/skills/postgres-concurrent-schema-init-deadlock, .github/skills/postgres-concurrent-schema-init-deadlock and .opencode/skills/postgres-concurrent-schema-init-deadlock in your project.

What does Postgres Concurrent Schema Init Deadlock need to run?

Going by SKILL.md and its folder, Postgres Concurrent Schema Init Deadlock needs the command-line tools its instructions call (python and gcloud). Our summary lists: Python 3.

Does Postgres Concurrent Schema Init Deadlock access the network?

SKILL.md names 1 domain. As links in the text: postgresql.org. This is read from the text; nothing was executed.

Is Postgres Concurrent Schema Init Deadlock safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Postgres Concurrent Schema Init Deadlock use?

Postgres Concurrent Schema Init Deadlock is published under the MPL-2.0 licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Postgres Concurrent Schema Init Deadlock use?

About 1.1k tokens (SKILL.md is roughly 4.3k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Postgres Concurrent Schema Init Deadlock?

Skills that share tags, products or a category with Postgres Concurrent Schema Init Deadlock: Archestra Dev Investigate (archestra-ai/archestra, 4.3k stars), Devops (nicepkg/auto-company, 192 stars), Opensourcefaq (digoal/blog, 8.6k stars) and Google Cloud Solution Guided Gke AI Migration (google/skills, 21k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Postgres Concurrent Schema Init Deadlock?

divinevideo (a GitHub organization) maintains it in divinevideo/divine-mobile, which has 265 GitHub stars. The repository holds 103 skills in this directory. The repository was last updated on October 7, 2026.

Source: divinevideo/divine-mobile on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.