DevFlow logoDevFlow
ER_CON_COUNT_ERROR_1040Verified Production Fix

ERROR 1040 (08004): Too many connections

Resolve MySQL Error 1040: Too many connections. Audit unclosed connection pools, optimize max_connections, and prevent connection starvation in serverless environments.

Root Cause Mechanical Summary

Active client connections to the MySQL server have reached the configured `max_connections` ceiling. All subsequent TCP connection attempts are rejected with Error 1040.

MySQL allocates memory buffers per thread. When max_connections (default 151) is exhausted due to connection pooling leaks, long-running queries, or serverless lambda spin-ups, new sessions receive 1040 immediately.

Vulnerable / Problematic Syntax
Before
// Anti-pattern: creating a new connection on every serverless request
export async function handler() {
  const conn = await mysql.createConnection(DB_URL);
  return conn.query('SELECT 1');
}
Production-Safe Remediation
After
// Best practice: share connection pool across invocations
const pool = mysql.createPool({
  uri: DB_URL,
  connectionLimit: 10,
  idleTimeout: 60000,
});

export async function handler() {
  return pool.query('SELECT 1');
}

Resolution Note: Maintain a single pooled client singleton to avoid exhausting MySQL connections in serverless environments.

Step-by-Step Triage Checklist

  • Inspect current connections: `SHOW STATUS LIKE "Threads_connected";`.

  • Audit unclosed connections: `SHOW PROCESSLIST;` to identify sleeping queries.

  • If using Vercel/AWS Lambda, route connections through PlanetScale, AWS RDS Proxy, or Prisma Accelerate.

Serverless MySQL Pool Singleton

lib/db.ts

Prevent recurrence by enforcing this verification check in staging or pre-commit hooks:

import mysql from 'mysql2/promise';

const globalForDb = globalThis as unknown as { pool: mysql.Pool };

export const pool =
  globalForDb.pool ||
  mysql.createPool({
    uri: process.env.DATABASE_URL,
    waitForConnections: true,
    connectionLimit: 5,
    maxIdle: 2,
    idleTimeout: 30000,
  });

if (process.env.NODE_ENV !== 'production') globalForDb.pool = pool;

Quick CLI Fix / Diagnosis

mysql -u root -p -e 'SET GLOBAL max_connections = 500;'

Frequently Asked Questions

Can I set max_connections to 10,000?
Be cautious: each connection reserves thread stack and query buffer memory. Setting it too high without adequate RAM can trigger Linux OOM kills.
Was this guide / tool helpful to you?