Senior · Network services

SQL pools, transactions and N+1

What does sql.DB own, and why can increasing its pool hurt?

Try explaining this aloud before opening the answer. State your assumptions and trace a boundary case.

Reveal a strong answer
  1. sql.DB is a concurrency-safe pool handle, not one connection. Reuse it for the application lifetime and size active/idle connections against database capacity across all replicas.

  2. Use a transaction handle consistently for operations that must share its transaction. Calling db.Query from inside transaction logic may use another connection and violate atomicity. Always commit or roll back and honor contexts.

  3. Pool waits, slow queries, lock contention and N+1 query patterns can dominate latency. More connections may move the queue into an already saturated database. Query count and execution plans matter as much as goroutine count.

Common trap

Beginning a transaction does not automatically attach unrelated db calls to it.

Try it

Fifty replicas each permit100 connections but the database safely handles300. What do you change?

Worked solution

Start from a global connection budget, reduce per-replica active limits with headroom, measure checkout wait and query duration, and fix inefficient access patterns. Autoscaling replicas must not accidentally multiply database pressure without a corresponding budget.

Change the constraint

Why might a slow transaction cause a pool-exhaustion incident even without a connection leak?

How did you do?

Self-assessment, not a compiler pass or interview score. Explain the reasoning unaided before marking understood.

Not marked. Progress stays on this browser, separate from course completion.

Primary references

Checked 2026-10-20. Use documentation for your pinned runtime, driver and tool version.