Agent skill

Pg Pool Cloudsql Reconnect

by divinevideo in divinevideo/divine-mobile

Fix Node.js pg-pool not reconnecting after CloudSQL connection reset (ECONNRESET).

MPL-2.0Auto-check passedDatabases

Install Pg Pool Cloudsql Reconnect

skills CLI
$ npx skills add divinevideo/divine-mobile --skill pg-pool-cloudsql-reconnect -a claude-code

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

GitHub CLI
$ gh skill install divinevideo/divine-mobile pg-pool-cloudsql-reconnect --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/pg-pool-cloudsql-reconnect .claude/skills/pg-pool-cloudsql-reconnect && 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
pg-pool-cloudsql-reconnect
GitHub stars
265
Token cost
~1.2k tokens
SKILL.md length
300 words
Files
1
Skills in repo
103
Repo updated
First seen
Licence
MPL-2.0

At a glance

Fix Node.js pg-pool not reconnecting after CloudSQL connection reset (ECONNRESET).

  • Works in 5 steps: Detect connection reset errors → Call pool.end() to close all connections → Create a new pool instance → …
  • Retries fail with same ECONNRESET error despite retry logic
  • SKILL.md covers Problem, Context / Trigger Conditions, Root Cause and Solution, plus 4 more sections
  • Calls gcloud

What it does

Pg Pool Cloudsql Reconnect is an agent skill from divinevideo/divine-mobile. Fix Node.js pg-pool not reconnecting after CloudSQL connection reset (ECONNRESET). Use when: (1) Retries fail with same ECONNRESET error despite retry logic, (2) "Connection terminated" or "connection already closed" errors persist across retries, (3) "remaining connection slots are reserved" errors in CloudSQL, (4) High-concurrency Node.js app with pg-pool and CloudSQL/managed PostgreSQL. The pool caches dead connections - you must recreate the pool, not just retry.

Its SKILL.md is about 1.2k 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 Error handling. It works with Node.js and PostgreSQL. The licence is MPL-2.0.

When your agent uses it

  • Retries fail with same ECONNRESET error despite retry logic
  • Connection terminated
  • Connection already closed errors persist across retries
  • Remaining connection slots are reserved errors in CloudSQL

Example prompts

  • “Connection terminated”
  • “connection already closed”
  • “remaining connection slots are reserved”
  • “/pg-pool-cloudsql-reconnect”

Requirements

  • Node.js

Workflow steps

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

  1. Detect connection reset errors
  2. Call pool.end() to close all connections
  3. Create a new pool instance
  4. Verify the new connection works
  5. Then retry the operation

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:

    • gcloud

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

  • Network

    No URLs in SKILL.md. Its commands use gcloud, which can reach the network depending on how they are called.

    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

Pg Pool Cloudsql Reconnect loads about 1.2k tokens when it runs. Until then it costs about 125 tokens; SKILL.md has 300 words of instructions outside code blocks.

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

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). 300 words, ~1,234 tokens.

Download SKILL.mdSave it as .claude/skills/pg-pool-cloudsql-reconnect/SKILL.md (or your agent's skills folder).
name
pg-pool-cloudsql-reconnect
description
Fix Node.js pg-pool not reconnecting after CloudSQL connection reset (ECONNRESET). Use when: (1) Retries fail with same ECONNRESET error despite retry logic, (2) "Connection terminated" or "connection already closed" errors persist across retries, (3) "remaining connection slots are reserved" errors in CloudSQL, (4) High-concurrency Node.js app with pg-pool and CloudSQL/managed PostgreSQL. The pool caches dead connections - you must recreate the pool, not just retry.
author
Claude Code
version
1.0.0
date
2026-01-30

pg-pool CloudSQL Reconnection

Problem

Node.js applications using pg-pool with CloudSQL (or other managed PostgreSQL) fail to recover from connection resets. Retry logic appears to work but keeps failing with the same ECONNRESET error because the pool caches dead connections.

Context / Trigger Conditions

  • ECONNRESET errors that persist despite retry logic
  • Error messages like:
    • read ECONNRESET
    • Connection terminated
    • connection already closed
    • remaining connection slots are reserved for non-replication superuser connections
  • High-concurrency applications (parallel batch processing)
  • CloudSQL with small instance tiers (db-f1-micro, db-g1-small)
  • Long-running scripts with periods of inactivity followed by bursts

Root Cause

pg-pool maintains a pool of database connections. When CloudSQL resets connections (due to timeout, maintenance, or connection limits), the pool still holds references to those dead connections. Simply retrying the operation uses the same dead connection from the pool.

Solution

Instead of just retrying, recreate the entire pool on connection reset errors:

typescript
export class PostgresDatabase {
  private pool: Pool;
  private config: PostgresConfig;

  constructor(config: PostgresConfig) {
    this.config = config;
    this.pool = this.createPool();
  }

  private createPool(): Pool {
    const pool = new Pool({
      ...this.config,
      max: 25,                          // Adequate for concurrency
      idleTimeoutMillis: 30000,         // Close idle connections
      connectionTimeoutMillis: 10000,   // Timeout for new connections
      keepAlive: true,                  // TCP keepalive
    });

    pool.on('error', (err) => {
      console.error('Pool error:', err.message);
    });

    return pool;
  }

  private async reconnect(): Promise<void> {
    console.log("Reconnecting to database...");
    try {
      await this.pool.end();
    } catch {
      // Ignore cleanup errors
    }
    this.pool = this.createPool();
    await this.pool.query("SELECT 1"); // Verify connection
    console.log("Database reconnected");
  }

  private async withRetry<T>(
    operation: () => Promise<T>,
    maxRetries = 3
  ): Promise<T> {
    for (let attempt = 0; attempt < maxRetries; attempt++) {
      try {
        return await operation();
      } catch (error) {
        const msg = error instanceof Error ? error.message : String(error);
        const needsReconnect =
          msg.includes("ECONNRESET") ||
          msg.includes("Connection terminated") ||
          msg.includes("connection already closed") ||
          msg.includes("remaining connection slots");

        if (!needsReconnect || attempt === maxRetries - 1) {
          throw error;
        }

        const delay = 1000 * Math.pow(2, attempt);
        console.log(`Connection error, reconnecting in ${delay}ms...`);
        await new Promise(r => setTimeout(r, delay));

        // KEY: Recreate the pool, don't just retry
        await this.reconnect();
      }
    }
    throw new Error("Max retries exceeded");
  }
}

Key Insight

Retrying with the same pool uses cached dead connections. The fix is to:

  1. Detect connection reset errors
  2. Call pool.end() to close all connections
  3. Create a new pool instance
  4. Verify the new connection works
  5. Then retry the operation

CloudSQL-Specific Considerations

  1. Instance tier matters: db-f1-micro only supports ~25 connections. Use db-g1-small or larger for concurrent workloads.

  2. Check max_connections:

    bash
    gcloud sql instances describe INSTANCE --format='value(settings.tier)'
  3. Cloud SQL Proxy: Doesn't help with connection pooling - it just tunnels TCP. Consider PgBouncer for true connection pooling.

Verification

After implementing:

  1. Run high-concurrency workload
  2. Intentionally cause connection reset (restart proxy, wait for idle timeout)
  3. Verify operations resume with "Reconnecting to database..." log
  4. No more cascading failures

Notes

  • This pattern applies to any managed PostgreSQL, not just CloudSQL
  • Consider PgBouncer for production workloads with very high concurrency
  • The pool.on('error') handler prevents uncaught exceptions from crashing the app
  • Set max pool size to match your concurrency level plus headroom

© 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/pg-pool-cloudsql-reconnect of divinevideo/divine-mobile.

Open the folder on GitHubat commit 8d5fbf2

Compare with similar skills

Pg Pool Cloudsql Reconnect 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.

Pg Pool Cloudsql Reconnect compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Pg Pool Cloudsql Reconnect this skilldivinevideo/divine-mobile265—~1.2kAutomated safety check: PassMPL-2.0
Database Migrationsaffaan-m/ECC274k4 repos~3kAutomated safety check: PassMIT
Azure Postgres TSmicrosoft/skills3.1k5 repos~3.3kAutomated safety check: PassMIT
Flox Environmentsaffaan-m/ECC274k—~2.8kAutomated safety check: PassMIT
Sap Cap Capiresecondsky/sap-skills460—~4.4kAutomated safety check: PassGPL-3.0
Full Stack Developertheneoai/awesome-skills183—~2.2kAutomated safety check: PassMIT

Similar skills

  • Safe, reversible database migration patterns: forward-only production changes, expand-contract zero-downtime renames, concurrent indexes, batched backfills, and per-tool workflows for PostgreSQL…

    274k GitHub starsUsed in 4 repos~3k tokens
    DatabasesAuto-check passed
  • Azure Postgres TS

    microsoft/skills

    Official

    Connect to Azure Database for PostgreSQL Flexible Server from Node.js/TypeScript using the pg (node-postgres) package.

    3.1k GitHub starsUsed in 5 repos~3.3k tokens
    DatabasesAuto-check passed
  • Flox Environments

    affaan-m/ECC

    Floxで再現可能なクロスプラットフォーム開発環境を作成します — Nixに基づく宣言的な環境マネージャー。次の場合は必ずこのスキルを使用してください: システムレベルの依存関係(コンパイラー、データベース、openssl・libvips・BLAS・LAPACKなどのネイティブライブラリー)を持つプロジェクトを設定する場合…

    274k GitHub stars~2.8k tokensUpdated 2 days ago
    DatabasesAuto-check passed
  • Sap Cap Capire

    secondsky/sap-skills

    SAP Cloud Application Programming Model (CAP) development skill using Capire documentation.

    460 GitHub stars~4.4k tokensUpdated 2 days ago
    DatabasesAuto-check passed
  • Full Stack Developer

    theneoai/awesome-skills

    Elite Full-Stack Developer skill with mastery of modern frontend frameworks (React, Vue, TypeScript), backend systems (Node.js, Python, Go), databases (PostgreSQL, MongoDB, Redis), and DevOps…

    183 GitHub stars~2.2k tokensUpdated 4 mo ago
    DatabasesAuto-check passed
  • cmux Backend Rules

    manaflow-ai/cmux

    Sets the backend TypeScript and Cloud VM rules for cmux: Effect-based services, thin route handlers, Postgres as source of truth, migrations and provider secrets.

    28k GitHub starsUsed in 1 repo~682 tokens
    Backend & APIsAuto-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 Pg Pool Cloudsql Reconnect

What does Pg Pool Cloudsql Reconnect do?

Fix Node.js pg-pool not reconnecting after CloudSQL connection reset (ECONNRESET). Pg Pool Cloudsql Reconnect is an agent skill from divinevideo/divine-mobile.js pg-pool not reconnecting after CloudSQL connection reset (ECONNRESET).

When should I use Pg Pool Cloudsql Reconnect?

Pg Pool Cloudsql Reconnect fits situations like: retries fail with same ECONNRESET error despite retry logic; connection terminated; connection already closed errors persist across retries; remaining connection slots are reserved errors in CloudSQL.

How do I install Pg Pool Cloudsql Reconnect in Claude Code?

Run `npx skills add divinevideo/divine-mobile --skill pg-pool-cloudsql-reconnect -a claude-code`. Or copy the skill folder (.agents/skills/pg-pool-cloudsql-reconnect in divinevideo/divine-mobile) into .claude/skills/pg-pool-cloudsql-reconnect in your project. Claude Code loads it when a task matches its description.

How do I install Pg Pool Cloudsql Reconnect in Codex?

Run `npx skills add divinevideo/divine-mobile --skill pg-pool-cloudsql-reconnect -a codex`. Or copy the skill folder (.agents/skills/pg-pool-cloudsql-reconnect in divinevideo/divine-mobile) into .agents/skills/pg-pool-cloudsql-reconnect in your project. Codex loads it when a task matches its description.

Can I use Pg Pool Cloudsql Reconnect 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 pg-pool-cloudsql-reconnect -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/pg-pool-cloudsql-reconnect, .gemini/skills/pg-pool-cloudsql-reconnect, .github/skills/pg-pool-cloudsql-reconnect and .opencode/skills/pg-pool-cloudsql-reconnect in your project.

What does Pg Pool Cloudsql Reconnect need to run?

Going by SKILL.md and its folder, Pg Pool Cloudsql Reconnect needs the command-line tools its instructions call (gcloud). Our summary lists: Node.js.

Does Pg Pool Cloudsql Reconnect access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Pg Pool Cloudsql Reconnect 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 Pg Pool Cloudsql Reconnect use?

Pg Pool Cloudsql Reconnect 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 Pg Pool Cloudsql Reconnect use?

About 1.2k tokens (SKILL.md is roughly 4.9k 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 Pg Pool Cloudsql Reconnect?

Skills that share tags, products or a category with Pg Pool Cloudsql Reconnect: Database Migrations (affaan-m/ECC, 274k stars), Azure Postgres TS (microsoft/skills, 3.1k stars), Flox Environments (affaan-m/ECC, 274k stars) and Sap Cap Capire (secondsky/sap-skills, 460 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Pg Pool Cloudsql Reconnect?

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.