How to Optimize Database Access in Go

Optimize Go database access by configuring connection pools, using prepared statements, and batching queries to reduce latency.

Optimize database access in Go by using connection pooling, prepared statements, and batching to reduce latency and overhead. Configure the pool size and timeouts in your database/sql driver to match your workload.

import (
    "database/sql"
    _ "github.com/lib/pq"
)

func initDB() (*sql.DB, error) {
    db, err := sql.Open("postgres", "user=postgres dbname=mydb sslmode=disable")
    if err != nil {
        return nil, err
    }
    db.SetMaxOpenConns(25)
    db.SetMaxIdleConns(25)
    db.SetConnMaxLifetime(5 * time.Minute)
    return db, nil
}
  1. Use db.SetMaxOpenConns to limit concurrent connections and prevent resource exhaustion.
  2. Use db.SetMaxIdleConns to keep a pool of ready connections for instant reuse.
  3. Use db.SetConnMaxLifetime to close old connections and prevent stale network issues.
  4. Use db.Prepare for repeated queries to avoid parsing overhead on every execution.
  5. Use db.Exec with multiple placeholders to batch inserts instead of looping single inserts.