Articles / Go

  • go
  • database-sql
  • transactions
  • connection-pooling
  • postgresql
  • debugging

A Forgotten Tx Rollback Leaks a Connection Until the Pool Stalls

If a function calls db.Begin() and returns early on an error without calling Rollback, that connection never goes back to the pool. Nothing logs and nothing panics. The service works fine until enough requests have hit the error path, and then every query hangs.

The failure is slow and far from its cause, which makes it miserable to debug. So here is the bug, how to see it happening, and the one-line habit that prevents it.

The bug, in a dozen lines

func transfer(ctx context.Context, db *sql.DB, from, to int, amt int64) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	if _, err := tx.ExecContext(ctx,
		"UPDATE accounts SET bal = bal - $1 WHERE id = $2", amt, from); err != nil {
		return err // tx still open: connection leaked
	}
	if _, err := tx.ExecContext(ctx,
		"UPDATE accounts SET bal = bal + $1 WHERE id = $2", amt, to); err != nil {
		return err // and again
	}
	return tx.Commit()
}

Both early returns skip Commit and Rollback. A *sql.Tx is pinned to one physical connection for its whole life, and only Commit or Rollback releases it. Returning from the function releases nothing, and a garbage collector will not save you, because the database/sql machinery still holds a reference to the transaction.

Why it stalls instead of failing loudly

The pool treats that connection as in use, so it cannot hand it to anyone else. Each leak shrinks the usable pool by one. What happens next depends on your settings:

  • With SetMaxOpenConns(n), once n connections are leaked, every new query blocks waiting for a free one. With a context that has no deadline, it waits forever.
  • With the default (unlimited open connections), the pool just opens more, and you hit the server's own limit instead. On Postgres that is max_connections, and the error arrives from the server, not from Go.

The nasty part is that the first leak happens on a rare error path, perhaps a unique constraint violation. Weeks of quiet, then a burst of bad input and the whole service freezes.

Seeing it happen

Reproducing it takes a pool of one. Set db.SetMaxOpenConns(1), call the leaky function with input that fails, then run any other query with a short timeout. It will not return an answer; it will return context deadline exceeded.

In a running service, db.Stats() tells you straight away:

s := db.Stats()
log.Printf("open=%d inuse=%d idle=%d waitcount=%d waitdur=%s",
	s.OpenConnections, s.InUse, s.Idle, s.WaitCount, s.WaitDuration)

A leak looks like InUse equal to MaxOpenConnections while the service is quiet, with WaitCount and WaitDuration climbing. Healthy load has InUse bouncing around. A leak has it stuck high at 3am.

The server sees it too

Quick detour, because this is the more useful clue on Postgres. A leaked transaction is not idle from the server's point of view; it is open. pg_stat_activity shows those sessions with state = 'idle in transaction' and an old xact_start.

SELECT pid, now() - xact_start AS age, query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY age DESC;

The query column shows the last statement the session ran, which usually points straight at the leaking function. Worse, an open transaction keeps row locks it took and holds back vacuum from cleaning up dead rows. So a Go bug becomes a database bloat and lock-contention problem too.

As a backstop, Postgres has idle_in_transaction_session_timeout, which kills sessions that sit in this state too long. It is a safety net, not a fix; the app would then see a broken connection on its next use of that Tx.

The fix: defer Rollback straight after Begin

func transfer(ctx context.Context, db *sql.DB, from, to int, amt int64) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback() // no-op after a successful Commit

	if _, err := tx.ExecContext(ctx,
		"UPDATE accounts SET bal = bal - $1 WHERE id = $2", amt, from); err != nil {
		return err
	}
	if _, err := tx.ExecContext(ctx,
		"UPDATE accounts SET bal = bal + $1 WHERE id = $2", amt, to); err != nil {
		return err
	}
	return tx.Commit()
}

Hang on, why is it fine to roll back after a commit? Because once a transaction is finished, Rollback just returns sql.ErrTxDone and touches nothing. That is why the deferred call is safe on the success path, and why ignoring its return value there is acceptable. Every other path, including a panic, now releases the connection.

Put the defer directly under the Begin error check. Not at the end, not inside a branch. If you have to scroll to find it, the next edit will add a return above it.

Context cancellation is a partial safety net

The documentation for BeginTx says that if the context is cancelled, the sql package rolls the transaction back. So a request-scoped context with a deadline eventually frees a leaked transaction when the request ends. That helps, but only if the context is actually cancelled.

  • Pass context.Background() and nothing ever cancels it.
  • Pass a long-lived context, such as one tied to the process, and the same applies.
  • Pass a request context and the connection returns when the request finishes, but it is still held for the rest of the request, and by then your handler may have gone on to do slow work.

So treat cancellation as a mitigation. The deferred rollback is the actual control.

The same shape elsewhere

An unclosed *sql.Rows pins a connection in exactly the same way, until you finish iterating or call Close. A leaked *sql.Conn from db.Conn(ctx) is the same again. If InUse is stuck high and your transactions all look correct, check these next, and always defer the Close too.

A cheap guard is a helper that takes a function, begins the transaction, defers the rollback, calls the function and commits. Then the forgetting happens once, in one reviewed place, rather than in every handler.