An API behind a phone app runs on Node and Express, with mysql2 connection pools. It has three pm2 workers, each with a pool of 20 connections and queueLimit set to 0. The app's main feature is a lookup that runs on every scan. One afternoon that lookup hung for everyone, for about four hours. The API served 2 lookups in that time, against a normal of about 1,000 an hour. The route that broke it was a different one: login.

Key facts

  • One bad login leaked one database connection. The handler took a connection first and returned early without giving it back.
  • About 60 bad logins from a bot were enough to take the whole pool: 20 connections in each of 3 workers.
  • With queueLimit 0, every later query waited forever. No error, no timeout, no log line.
  • Health checks stayed green, because the routes that need no database still answered.
  • The fix: check the fields, check the captcha with a timeout, then run the query with pool.query. No connection is held, so none can leak.

What did users see?

A scan in the app spun and never finished. There was no error message, because the server never sent one.

From the outside, the API looked healthy. The health checks called a route that does not touch the database, and that route answered at once. So no alert fired. The process was alive; it just could not get a database connection for anything else.

A reload of the processes brought everything back at once. When a restart fixes a problem instantly, look for something the old processes were holding.

What did the logs show?

The access log, written by morgan, printed - - ms - - for every hung request. That means no status and no response time: the request came in and never got an answer.

The database told the rest. MySQL showed 61 connections from the API's host in the Sleep state, idle for about 100 minutes. Idle, but checked out, so the API could not use them. The statement history for each of those connections showed the same last statement: the user lookup from the login route.

The app logs gave the trigger. Within one minute, a bot had posted 56 bad logins to /auth/login, plus a few bad sign-ups. Every one of them got a 400 with "Captcha error". That is about the size of the pool.

How does one bad login leak a connection?

Each bad login takes a connection and never gives it back:

Bad login from a botPOST /auth/login, wrong captcha
takes a connection first
Connection checked outheld while the captcha check runs
captcha says no
400 returnedearly return, the connection is never released
about 60 times in a minute
Pool emptyevery other request queues forever (queueLimit 0)

The handler shape that leaks

The login and sign-up handlers did things in this order. First, take a connection from the pool. Then call the captcha service over HTTP and wait for its answer, still holding the connection. Then run the query, and release the connection in the .finally of that query.

The release only ran if the query ran. The early returns, "captcha failed" and "missing fields", sent a 400 and left the function. The connection stayed checked out, with nothing left that would ever release it. Here is the shape, simplified (verifyCaptcha and check stand in for the real code):

// Before: connection taken first, held across an HTTP call
router.post("/auth/login", (req, res) => {
  pool.getConnection(async (err, conn) => {
    const ok = await verifyCaptcha(req.body.captcha);
    if (!ok) return res.status(400).send("Captcha error"); // conn never released
    if (!req.body.email) return res.status(400).send("Missing fields"); // same
    conn.promise().query("SELECT ... WHERE email = ?", [req.body.email])
      .then(([rows]) => res.json(check(rows)))
      .finally(() => conn.release());
  });
});

// After: validate, then captcha with a timeout, then pool.query
router.post("/auth/login", async (req, res) => {
  if (!req.body.email || !req.body.password) return res.status(400).send("Missing fields");
  const ok = await verifyCaptcha(req.body.captcha, { timeoutMs: 8000 }).catch(() => false);
  if (!ok) return res.status(400).send("Captcha error");
  const [rows] = await pool.promise().query("SELECT ... WHERE email = ?", [req.body.email]);
  res.json(check(rows));
});

The new shape has no connection object at all. pool.query takes a connection, runs one statement and gives it back by itself, so there is nothing to forget. Nothing is held while the captcha call runs, and the 8 second timeout means a slow or broken captcha service answers 400 instead of hanging.

The fix went in the same evening. The same change went into every handler with that shape: password update, admin login, and a token step that waited on a third-party SDK call while holding a connection. The same review also removed a log line that printed the full user row, password hash included.

How do you find a leak like this?

Start with the database. Count the idle ones per host: SELECT host, COUNT(*), SUM(time > 120) FROM information_schema.processlist WHERE user = 'api_user' AND command = 'Sleep' GROUP BY host. Look only at the API's own host. Other services often share the same database user, and their idle connections hide the pattern in a total.

Then find what each held connection did last. Join performance_schema.events_statements_history to performance_schema.threads on thread_id; the processlist_id column in threads matches the id in the processlist. If every held connection ends on the same statement, you have found the route.

One small trap: pm2's out logs have no timestamps. To line them up with the burst, read them by line position around the bad logins, not by time.

Five rules

  • Never hold a pooled connection across a network call you do not control. Take the connection after the call, or use pool.query for single statements.
  • Every early return while holding a resource is a leak until proven otherwise. Put the release in one place, or do not take an explicit handle at all.
  • queueLimit 0 turns a slow leak into a silent total outage. Set a queue limit or an acquire timeout, so requests fail loudly instead of waiting forever.
  • A bot on a public login is the normal case. Bad logins arrive every day, so a leak on that path is the first one to show up.
  • Watch Sleep connections per host, not in total. When several services share one database user, only the per-host count shows which one is leaking.

Common questions

Why did the health checks stay green?

They called a route that never touches the database. The process was alive and answering, so the check passed. Only the routes that needed a connection were stuck.

Is a bigger pool the fix?

No. A leak fills a pool of any size. A bigger pool only means the bot needs to send more bad logins before everything stops.

Why did a reload fix it at once?

A reload starts new processes with new, empty pools, and the old held connections close with the old processes. The leak itself is still there, and the next burst of bad logins brings the outage back.

Melta is free; get it on the App Store or Google Play.

Sources