# OperationalError: (pymysql.err.OperationalError) (1040, 'Too many connections')

- **ID:** `cloud/gcp-cloud-sql-connection-limit-exceeded`
- **Domain:** cloud
- **Category:** resource_error
- **Error Code:** `1040`
- **Verification:** ai_generated
- **Fix Rate:** 85%

## Root Cause

Cloud SQL instance has reached its max_connections limit, often due to connection leaks or insufficient instance tier.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| Cloud SQL for MySQL 8.0 | active | — | — |
| Cloud SQL for PostgreSQL 15 | active | — | — |
| Cloud SQL Proxy 2.0 | active | — | — |

## Workarounds

1. **Use a connection pool like HikariCP (Java) or SQLAlchemy pool_pre_ping=True with pool_size=10 and max_overflow=0. In Python: engine = create_engine('mysql+pymysql://user:pass@host/db', pool_size=10, max_overflow=0, pool_pre_ping=True)** (90% success)
   ```
   Use a connection pool like HikariCP (Java) or SQLAlchemy pool_pre_ping=True with pool_size=10 and max_overflow=0. In Python: engine = create_engine('mysql+pymysql://user:pass@host/db', pool_size=10, max_overflow=0, pool_pre_ping=True)
   ```
2. **Temporarily increase max_connections via Cloud SQL flags: gcloud sql instances patch INSTANCE_NAME --database-flags max_connections=500, then scale instance tier if needed.** (85% success)
   ```
   Temporarily increase max_connections via Cloud SQL flags: gcloud sql instances patch INSTANCE_NAME --database-flags max_connections=500, then scale instance tier if needed.
   ```
3. **Kill idle connections manually: SELECT CONCAT('KILL ', id, ';') FROM information_schema.processlist WHERE command = 'Sleep' AND time > 300; then execute the generated KILL statements.** (75% success)
   ```
   Kill idle connections manually: SELECT CONCAT('KILL ', id, ';') FROM information_schema.processlist WHERE command = 'Sleep' AND time > 300; then execute the generated KILL statements.
   ```

## Dead Ends

- **** — Restarting the instance resets connections but doesn't fix the leak; it recurs quickly. (95% fail)
- **** — Only increasing max_connections in flags without addressing connection pooling or instance memory leads to OOM or crash. (80% fail)
- **** — Adding more application instances without connection limits just multiplies the connections hitting the same limit. (90% fail)
