Agent skill

Cloudsql Idle Connection Timeout

by divinevideo in divinevideo/divine-mobile

Fix psycopg2 "could not receive data from server: Operation timed out" or "connection already closed" errors when using Cloud SQL with long-running Python scripts.

MPL-2.0Auto-check passedDatabases

Install Cloudsql Idle Connection Timeout

skills CLI
$ npx skills add divinevideo/divine-mobile --skill cloudsql-idle-connection-timeout -a claude-code

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

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

At a glance

Fix psycopg2 "could not receive data from server: Operation timed out" or "connection already closed" errors when using Cloud SQL with long-running Python scripts.

  • Works in 3 steps: Run the script with the long non-DB phase → Confirm no OperationalError or… → Verify data is being written to the DB…
  • Psycopg2.OperationalError after a period of no DB activity
  • SKILL.md covers Problem, Context / Trigger Conditions, Solution and Verification, plus 2 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Cloudsql Idle Connection Timeout is an agent skill from divinevideo/divine-mobile. Fix psycopg2 "could not receive data from server: Operation timed out" or "connection already closed" errors when using Cloud SQL with long-running Python scripts. Use when: (1) psycopg2.OperationalError after a period of no DB activity, (2) DB connection works initially but fails after a non-DB phase (API calls, file processing, CDX scans), (3) Cloud SQL managed PostgreSQL kills idle connections. The fix is to defer DB connection opening until needed, or add reconnection logic for long-running batch processes.

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 SQL. It works with SQL, PostgreSQL and Python. The licence is MPL-2.0.

When your agent uses it

  • Psycopg2.OperationalError after a period of no DB activity
  • DB connection works initially but fails after a non-DB phase (API calls
  • File processing
  • Cloud SQL managed PostgreSQL kills idle connections

Example prompts

  • “could not receive data from server: Operation timed out”
  • “connection already closed”
  • “/cloudsql-idle-connection-timeout”

Requirements

  • Python 3

Workflow steps

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

  1. Run the script with the long non-DB phase
  2. Confirm no OperationalError or InterfaceError after the idle period
  3. Verify data is being written to the DB during the fetch phase

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

    No scripts in the folder and no shell commands in SKILL.md (its code samples are python and sql).

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

  • Network

    No URLs in SKILL.md.

    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

Cloudsql Idle Connection Timeout loads about 1.1k tokens when it runs. Until then it costs about 137 tokens; SKILL.md has 361 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~137
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). 361 words, ~1,130 tokens.

Download SKILL.mdSave it as .claude/skills/cloudsql-idle-connection-timeout/SKILL.md (or your agent's skills folder).
name
cloudsql-idle-connection-timeout
description
Fix psycopg2 "could not receive data from server: Operation timed out" or "connection already closed" errors when using Cloud SQL with long-running Python scripts. Use when: (1) psycopg2.OperationalError after a period of no DB activity, (2) DB connection works initially but fails after a non-DB phase (API calls, file processing, CDX scans), (3) Cloud SQL managed PostgreSQL kills idle connections. The fix is to defer DB connection opening until needed, or add reconnection logic for long-running batch processes.
author
Claude Code
version
1.0.0
date
2025-05-15

Cloud SQL Idle Connection Timeout Fix

Problem

Cloud SQL (and other managed PostgreSQL services) kill idle connections after a timeout (typically 10 minutes). Long-running scripts that open a DB connection early, then perform non-DB work (HTTP requests, file I/O, CDX scanning), then try to use the DB connection again will get a misleading error.

Context / Trigger Conditions

  • psycopg2.OperationalError: could not receive data from server: Operation timed out
  • psycopg2.InterfaceError: connection already closed
  • Script has phases: DB setup → long non-DB work → DB writes
  • Using Google Cloud SQL, AWS RDS, or Azure Database for PostgreSQL
  • Connection was working initially, fails after idle period
  • The error appears AFTER a phase that doesn't use the DB (e.g., API crawling, file processing)

Solution

Pattern 1: Defer DB Connection (Preferred)

Structure code so the DB connection opens AFTER the non-DB phase:

python
# BAD: Connection opens before long CDX scan
with VineDatabase() as db:
    ensure_schema(db)
    results = long_running_api_scan()  # 5-10 minutes, no DB needed
    process_results(db, results)  # Connection dead here!

# GOOD: CDX scan first, then fresh DB connection
results = long_running_api_scan()  # No DB connection open

with VineDatabase() as db:  # Fresh connection when actually needed
    ensure_schema(db)
    process_results(db, results)
Pattern 2: Reconnection Logic (For Long Batch Operations)

For operations that DO use the DB but might exceed the idle timeout between writes:

python
import psycopg2

def reconnect_db():
    """Create a fresh database connection."""
    db = VineDatabase()
    cursor = db._cursor()
    return db, cursor

def process_batch(db, cursor, items):
    for item in items:
        data = fetch_from_api(item)  # Slow network call
        try:
            cursor.execute("INSERT INTO ...", data)
            db.conn.commit()
        except (psycopg2.OperationalError, psycopg2.InterfaceError):
            # Connection died, reconnect and retry
            try:
                db.close()
            except Exception:
                pass
            db, cursor = reconnect_db()
            cursor.execute("INSERT INTO ...", data)
            db.conn.commit()
Pattern 3: TCP Keepalive (Alternative)

Configure psycopg2 to send TCP keepalive packets:

python
conn = psycopg2.connect(
    database_url,
    keepalives=1,
    keepalives_idle=60,
    keepalives_interval=10,
    keepalives_count=5
)

Note: This may not work with all Cloud SQL proxy configurations.

Verification

  1. Run the script with the long non-DB phase
  2. Confirm no OperationalError or InterfaceError after the idle period
  3. Verify data is being written to the DB during the fetch phase:
    sql
    SELECT COUNT(*) FROM your_table WHERE created_at > NOW() - INTERVAL '5 minutes';
Show full SKILL.md (148 more words)Show less

Example

A Vine archive crawler that:

  1. Scans Wayback Machine CDX for archived profiles (107 pages, ~6 minutes)
  2. Then fetches and stores each profile in Cloud SQL

The CDX scan doesn't need the DB, so opening the connection before it means the connection sits idle for 6 minutes and gets killed by Cloud SQL. Fix: run CDX scan first, then open DB connection for the fetch-and-store phase.

Notes

  • Cloud SQL default idle timeout is ~10 minutes but can vary
  • The error message "could not receive data from server: Operation timed out" is misleading—it sounds like a network issue but is actually an idle timeout
  • psycopg2.InterfaceError: connection already closed often follows the OperationalError
  • For very long batch operations (hours), combine Pattern 1 and Pattern 2
  • Also check Cloud SQL authorized networks if connection fails immediately (different error)
  • When using nohup or background processes, ensure output is unbuffered (PYTHONUNBUFFERED=1)

© 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/cloudsql-idle-connection-timeout of divinevideo/divine-mobile.

Open the folder on GitHubat commit 8d5fbf2

Compare with similar skills

Cloudsql Idle Connection Timeout 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.

Cloudsql Idle Connection Timeout compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Cloudsql Idle Connection Timeout this skilldivinevideo/divine-mobile265—~1.1kAutomated safety check: PassMPL-2.0
Chdb SQLvemetric/vemetric3941 repos~1.2kAutomated safety check: PassApache-2.0
SQL Database Support for pRESTprest/prest4.6k—~1.6kAutomated safety check: PassMIT
Schema Explorationtimescale/pg-aiguide1.9k—~1.1kAutomated safety check: PassApache-2.0
Mz BenchmarkMaterializeInc/materialize6.4k—~2.8kAutomated safety check: PassCustom licence
Dingtalk AitableDingTalk-Real-AI/dingtalk-workspace-cli3.2k—~5.4kAutomated safety check: PassApache-2.0

Similar skills

  • Chdb SQL

    vemetric/vemetric

    A skill your agent uses when the user wants to run SQL — especially analytical SQL — on local files (parquet/csv/json), URLs, S3 paths, or remote databases (Postgres, MySQL, MongoDB, ClickHouse…

    394 GitHub starsUsed in 1 repo~1.2k tokens
    DatabasesAuto-check passed
  • Guides classifying, gap-analyzing and scaffolding support for a new SQL database in pREST, from Postgres-compatible variants to entirely new dialects.

    4.6k GitHub stars~1.6k tokensUpdated yesterday
    DatabasesAuto-check passed
  • Schema Exploration

    timescale/pg-aiguide

    Explore an existing PostgreSQL database before answering questions about its data or writing SQL.

    1.9k GitHub stars~1.1k tokensUpdated 6 days ago
    DatabasesAuto-check passed
  • Mz Benchmark

    MaterializeInc/materialize

    Add/modify/debug Materialize perf benchmark scenarios. An agent skill from MaterializeInc/materialize.

    6.4k GitHub stars~2.8k tokensUpdated today
    DatabasesAuto-check passed
  • Dingtalk Aitable

    DingTalk-Real-AI/dingtalk-workspace-cli

    钉钉 AI 表格(多维表)业务操作。Use when 用户需要操作 AI 表格/多维表/Base/Table、应用模式/App 页面/Widget、建表、查写记录、字段、记录评论、评论回复、访问密钥(API Key)、SQL/PostgreSQL/SELECT/JOIN、筛选、排序、公式、模板、批量导入 CSV 或 JSON、导出、仪表盘、图表、上传附件、数据源配置与同步、按任务 ID…

    3.2k GitHub stars~5.4k tokensUpdated 2 days ago
    DatabasesAuto-check passed
  • Sql2er

    ystemsrx/sql_to_ER

    A skill your agent uses when the user wants a Chen-model ER diagram from SQL CREATE TABLE statements or DBML, wants to rearrange or clean up an existing sql2er state, wants a skeleton-only overview…

    188 GitHub stars~1.1k tokensUpdated 6 days ago
    DatabasesAuto-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

Categories

Questions about Cloudsql Idle Connection Timeout

What does Cloudsql Idle Connection Timeout do?

Fix psycopg2 "could not receive data from server: Operation timed out" or "connection already closed" errors when using Cloud SQL with long-running Python scripts. Cloudsql Idle Connection Timeout is an agent skill from divinevideo/divine-mobile. Fix psycopg2 "could not receive data from server: Operation timed out" or "connection already closed" errors when using Cloud SQL with long-running Python scripts.

When should I use Cloudsql Idle Connection Timeout?

Cloudsql Idle Connection Timeout fits situations like: psycopg2.OperationalError after a period of no DB activity; DB connection works initially but fails after a non-DB phase (API calls; file processing; cloud SQL managed PostgreSQL kills idle connections.

How do I install Cloudsql Idle Connection Timeout in Claude Code?

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

How do I install Cloudsql Idle Connection Timeout in Codex?

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

Can I use Cloudsql Idle Connection Timeout 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 cloudsql-idle-connection-timeout -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/cloudsql-idle-connection-timeout, .gemini/skills/cloudsql-idle-connection-timeout, .github/skills/cloudsql-idle-connection-timeout and .opencode/skills/cloudsql-idle-connection-timeout in your project.

What does Cloudsql Idle Connection Timeout need to run?

SKILL.md names no scripts, command-line tools or credentials: Cloudsql Idle Connection Timeout is instructions for the agent only. Our summary lists: Python 3.

Does Cloudsql Idle Connection Timeout 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 Cloudsql Idle Connection Timeout 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 Cloudsql Idle Connection Timeout use?

Cloudsql Idle Connection Timeout 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 Cloudsql Idle Connection Timeout use?

About 1.1k tokens (SKILL.md is roughly 4.5k 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 Cloudsql Idle Connection Timeout?

Skills that share tags, products or a category with Cloudsql Idle Connection Timeout: Chdb SQL (vemetric/vemetric, 394 stars), SQL Database Support for pREST (prest/prest, 4.6k stars), Schema Exploration (timescale/pg-aiguide, 1.9k stars) and Mz Benchmark (MaterializeInc/materialize, 6.4k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Cloudsql Idle Connection Timeout?

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.