Databases

Go and MySQL: Building a High-Load Data Access Layer with Connection Pooling, Prepared Statements, and Migrations

Ruslan Ismailov Published 18 min read
G

Introduction: Why Avoid ORM Under High Load

ORM libraries like GORM speed up development, but on high-load Go services their cost becomes significant. Typical issues include hidden N+1 queries, excessive SELECT *, inability to fine-tune the connection pool, and reflection overhead during row mapping. At loads above 5,000 RPS, the difference between a "smart" ORM and a hand-written MySQL data access layer can reach 20–40% in latency and 15–25% in memory consumption.

In this article, we'll build a production-ready data access layer in Go and MySQL using the standard database/sql package, minimal wrappers, and proven patterns for 2026.

Choosing a Driver: go-sql-driver/mysql vs sqlx vs bun

The Go ecosystem has three main tools for working with MySQL.

  • go-sql-driver/mysql — a pure driver for database/sql. Zero abstractions, maximum control, actively maintained in 2026. Best choice when predictable behavior matters.
  • sqlx — a thin wrapper over database/sql that adds named parameters, StructScan, and In queries. Introduces no ORM magic and has virtually no performance impact.
  • bun — a query builder with MySQL 8+/9.x support, built-in migrations, and hooks. Convenient for moderate loads, but adds ~2–4 µs per query due to AST construction.

For a high-load service, the recommended stack is go-sql-driver/mysql + sqlx. Benchmarks on a server with MySQL 9.1 (1,000 concurrent goroutines, SELECT with JOIN):

  • database/sql + go-sql-driver: ~310 µs p99
  • sqlx: ~315 µs p99
  • bun (query builder): ~340 µs p99
  • GORM v2: ~480 µs p99

Proper Connection Pool Configuration

The connection pool is the primary optimization lever. The database/sql package manages the pool automatically, but default values are not suitable for production.

package db

import (
    "database/sql"
    "fmt"
    "time"

    _ "github.com/go-sql-driver/mysql"
)

type Config struct {
    DSN             string
    MaxOpenConns    int
    MaxIdleConns    int
    ConnMaxLifetime time.Duration
    ConnMaxIdleTime time.Duration
}

func NewPool(cfg Config) (*sql.DB, error) {
    db, err := sql.Open("mysql", cfg.DSN)
    if err != nil {
        return nil, fmt.Errorf("open db: %w", err)
    }

    db.SetMaxOpenConns(cfg.MaxOpenConns)
    db.SetMaxIdleConns(cfg.MaxIdleConns)
    db.SetConnMaxLifetime(cfg.ConnMaxLifetime)
    db.SetConnMaxIdleTime(cfg.ConnMaxIdleTime)

    if err := db.Ping(); err != nil {
        return nil, fmt.Errorf("ping db: %w", err)
    }
    return db, nil
}

// MaxOpenConns calculation formula:
// MaxOpenConns = (MySQL server CPU cores * 2) + number of disks
// For MySQL on 8 cores + 2 disks: 8*2+2 = 18
// Add 20% headroom: ~22
//
// MaxIdleConns should equal MaxOpenConns or be slightly lower
// to avoid recreating connections under load.
//
// ConnMaxLifetime: 5–10 minutes (less than MySQL wait_timeout).
// ConnMaxIdleTime: 2–3 minutes.

Key sizing rules:

  • SetMaxOpenConns: use the formula (MySQL CPUs × 2) + disks. Typical values are 20–50 for a single instance.
  • SetMaxIdleConns: equal to MaxOpenConns or 20–30% lower. Too small a value leads to constant connection re-opening.
  • SetConnMaxLifetime: always less than MySQL's wait_timeout (default 8 hours). 5 minutes is recommended.
  • SetConnMaxIdleTime: 2–3 minutes to release idle connections.

Prepared Statements: When to Use and How to Reuse

Prepared statements reduce load on the MySQL parser and protect against SQL injection. However, incorrect usage in Go leads to descriptor leaks on the server side.

package repository

import (
    "context"
    "database/sql"
    "fmt"
)

type UserRepository struct {
    db        *sql.DB
    stmtGet   *sql.Stmt
    stmtInsert *sql.Stmt
}

func NewUserRepository(db *sql.DB) (*UserRepository, error) {
    stmtGet, err := db.Prepare(
        `SELECT id, name, email, created_at FROM users WHERE id = ?`,
    )
    if err != nil {
        return nil, fmt.Errorf("prepare stmtGet: %w", err)
    }

    stmtInsert, err := db.Prepare(
        `INSERT INTO users (name, email) VALUES (?, ?)`,
    )
    if err != nil {
        stmtGet.Close() // close the already prepared statement
        return nil, fmt.Errorf("prepare stmtInsert: %w", err)
    }

    return &UserRepository{
        db:         db,
        stmtGet:    stmtGet,
        stmtInsert: stmtInsert,
    }, nil
}

// Close is called when the service shuts down
func (r *UserRepository) Close() {
    r.stmtGet.Close()
    r.stmtInsert.Close()
}

type User struct {
    ID        int64
    Name      string
    Email     string
    CreatedAt string
}

func (r *UserRepository) GetByID(ctx context.Context, id int64) (*User, error) {
    var u User
    err := r.stmtGet.QueryRowContext(ctx, id).Scan(
        &u.ID, &u.Name, &u.Email, &u.CreatedAt,
    )
    if err == sql.ErrNoRows {
        return nil, nil
    }
    if err != nil {
        return nil, fmt.Errorf("GetByID scan: %w", err)
    }
    return &u, nil
}

An anti-pattern is calling db.Prepare inside a request loop. Each call creates a new descriptor on the MySQL server. Prepare statements once during repository initialization and reuse them. When working with transactions, use tx.Stmt(stmt) to bind a prepared statement to a transaction.

Transactions in Go: Error Handling Patterns and Savepoints

The correct transaction pattern in Go always includes a defer-rollback:

func (r *UserRepository) TransferCredits(
    ctx context.Context,
    fromID, toID int64,
    amount int,
) error {
    tx, err := r.db.BeginTx(ctx, &sql.TxOptions{
        Isolation: sql.LevelReadCommitted,
    })
    if err != nil {
        return fmt.Errorf("begin tx: %w", err)
    }

    // defer rollback — safe: after Commit() it returns an error we ignore
    defer tx.Rollback() //nolint:errcheck

    if _, err = tx.ExecContext(ctx,
        `UPDATE accounts SET credits = credits - ? WHERE id = ? AND credits >= ?`,
        amount, fromID, amount,
    ); err != nil {
        return fmt.Errorf("debit: %w", err)
    }

    if _, err = tx.ExecContext(ctx,
        `UPDATE accounts SET credits = credits + ? WHERE id = ?`,
        amount, toID,
    ); err != nil {
        return fmt.Errorf("credit: %w", err)
    }

    // Savepoint for nested logic
    if _, err = tx.ExecContext(ctx, `SAVEPOINT sp_audit`); err != nil {
        return fmt.Errorf("savepoint: %w", err)
    }

    if _, err = tx.ExecContext(ctx,
        `INSERT INTO audit_log (from_id, to_id, amount) VALUES (?, ?, ?)`,
        fromID, toID, amount,
    ); err != nil {
        // Roll back only to the savepoint; the main transaction remains alive
        tx.ExecContext(ctx, `ROLLBACK TO SAVEPOINT sp_audit`) //nolint:errcheck
    }

    return tx.Commit()
}

MySQL has supported savepoints since version 5.5. Go has no built-in API for them — use direct SQL commands via ExecContext.

Working with NULL, Custom Types, and JSON in MySQL 9.x

MySQL 9.x has expanded JSON function support. In Go, handling nullable fields and JSON requires an explicit approach:

package model

import (
    "database/sql"
    "database/sql/driver"
    "encoding/json"
    "fmt"
)

// NullableString — wrapper for nullable VARCHAR
type NullableString struct {
    sql.NullString
}

// JSONMap — custom type for a MySQL JSON column
type JSONMap map[string]interface{}

func (j JSONMap) Value() (driver.Value, error) {
    if j == nil {
        return nil, nil
    }
    b, err := json.Marshal(j)
    return string(b), err
}

func (j *JSONMap) Scan(src interface{}) error {
    if src == nil {
        *j = nil
        return nil
    }
    var b []byte
    switch v := src.(type) {
    case []byte:
        b = v
    case string:
        b = []byte(v)
    default:
        return fmt.Errorf("JSONMap: unsupported type %T", src)
    }
    return json.Unmarshal(b, j)
}

// Example struct with a JSON field and a nullable field
type Product struct {
    ID         int64
    Name       string
    Attributes JSONMap
    DeletedAt  sql.NullTime // nullable DATETIME
}

// Query using JSON_EXTRACT (MySQL 9.x)
const queryProductByAttr = `
    SELECT id, name, attributes, deleted_at
    FROM products
    WHERE JSON_EXTRACT(attributes, '$.category') = ?
    LIMIT ?
`

Using sql.NullTime requires Go 1.15+. In MySQL 9.x, the JSON_TABLE, JSON_SCHEMA_VALID functions and the improved JSON_OVERLAPS enable complex queries directly in SQL, reducing application-side load.

Migrations Without ORM: golang-migrate and goose

The two leading migration tools for Go in 2026 are golang-migrate and goose.

  • golang-migrate: paired up/down files, embed support, CLI and Go API. Strict version control via the schema_migrations table.
  • goose: more flexible — supports Go migrations (when business logic is needed), sequential and timestamp versioning. Better suited for complex schemas.
// Initializing golang-migrate from embed in Go
package migrate

import (
    "database/sql"
    "embed"
    "fmt"

    "github.com/golang-migrate/migrate/v4"
    "github.com/golang-migrate/migrate/v4/database/mysql"
    "github.com/golang-migrate/migrate/v4/source/iofs"
)

//go:embed migrations/*.sql
var migrationsFS embed.FS

func RunMigrations(db *sql.DB) error {
    sourceDriver, err := iofs.New(migrationsFS, "migrations")
    if err != nil {
        return fmt.Errorf("iofs source: %w", err)
    }

    dbDriver, err := mysql.WithInstance(db, &mysql.Config{})
    if err != nil {
        return fmt.Errorf("mysql driver: %w", err)
    }

    m, err := migrate.NewWithInstance("iofs", sourceDriver, "mysql", dbDriver)
    if err != nil {
        return fmt.Errorf("migrate instance: %w", err)
    }

    if err := m.Up(); err != nil && err != migrate.ErrNoChange {
        return fmt.Errorf("migrate up: %w", err)
    }
    return nil
}

CI/CD integration: run migrations as a separate step before deploying the application. In GitHub Actions, this is a dedicated job with needs: [test] and MySQL readiness checked via mysqladmin ping. Use MySQL advisory locks (GET_LOCK) to prevent concurrent migration runs in multi-replica environments.

Testing the Data Layer: testcontainers-go and Mocks

Integration tests against a real MySQL instance are more reliable than mocks for the repository layer. The testcontainers-go library spins up a container directly from the test:

package repository_test

import (
    "context"
    "testing"

    "github.com/testcontainers/testcontainers-go"
    "github.com/testcontainers/testcontainers-go/modules/mysql"
)

func TestUserRepository_GetByID(t *testing.T) {
    ctx := context.Background()

    mysqlC, err := mysql.RunContainer(ctx,
        testcontainers.WithImage("mysql:9.1"),
        mysql.WithDatabase("testdb"),
        mysql.WithUsername("root"),
        mysql.WithPassword("secret"),
    )
    if err != nil {
        t.Fatalf("start container: %v", err)
    }
    defer mysqlC.Terminate(ctx) //nolint:errcheck

    dsn, _ := mysqlC.ConnectionString(ctx, "parseTime=true")

    db, err := NewPool(Config{
        DSN:             dsn,
        MaxOpenConns:    5,
        MaxIdleConns:    5,
        ConnMaxLifetime: 5 * 60 * 1000000000,
    })
    if err != nil {
        t.Fatalf("pool: %v", err)
    }
    defer db.Close()

    // Run migrations
    if err := RunMigrations(db); err != nil {
        t.Fatalf("migrations: %v", err)
    }

    repo, _ := NewUserRepository(db)
    defer repo.Close()

    // Insert test data and verify
    _, err = db.ExecContext(ctx,
        `INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')`,
    )
    if err != nil {
        t.Fatalf("insert: %v", err)
    }

    user, err := repo.GetByID(ctx, 1)
    if err != nil || user == nil {
        t.Fatalf("GetByID: %v, user: %v", err, user)
    }
    if user.Name != "Alice" {
        t.Errorf("expected Alice, got %s", user.Name)
    }
}

For unit-testing the service layer, define a repository interface and mock it using github.com/stretchr/testify/mock or go.uber.org/mock. The interface should only expose the methods actually used by the service.

Observability: OpenTelemetry and Slow Query Monitoring

Tracing SQL queries through OpenTelemetry lets you see the exact time of each query within distributed traces. Use OTELSQL — a wrapper around database/sql:

package db

import (
    "database/sql"

    "github.com/XSAM/otelsql"
    semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
    _ "github.com/go-sql-driver/mysql"
)

func NewTracedPool(dsn string, maxOpen int) (*sql.DB, error) {
    // Register the driver with OTel instrumentation
    driverName, err := otelsql.Register("mysql",
        otelsql.WithAttributes(
            semconv.DBSystemMySQL,
        ),
        otelsql.WithSpanOptions(otelsql.SpanOptions{
            Ping:           true,
            RowsNext:       false, // don't trace every row
            DisableErrSkip: true,
        }),
    )
    if err != nil {
        return nil, err
    }

    db, err := sql.Open(driverName, dsn)
    if err != nil {
        return nil, err
    }
    db.SetMaxOpenConns(maxOpen)

    // Export connection pool metrics to OTel
    otelsql.ReportDBStatsMetrics(db)
    return db, nil
}

Additionally, configure the slow query log on the MySQL side: slow_query_log = ON, long_query_time = 0.1 (100 ms). For aggregation, use Percona Monitoring and Management (PMM) or parse the slow log with pt-query-digest. Export connection pool metrics (db.Stats()) to Prometheus every 15 seconds — this lets you detect pool exhaustion before errors appear in the application.

Final Recommendations and Anti-Patterns

Best Practices

  • Use go-sql-driver/mysql with the DSN parameters parseTime=true and loc=UTC.
  • Calculate MaxOpenConns using the formula and validate it with load tests (wrk, k6).
  • Prepare statements once at startup and close them on service shutdown.
  • Always use context-aware methods: QueryContext, ExecContext.
  • Run migrations atomically, with locks, as a dedicated CI/CD step.
  • Write integration tests with testcontainers-go against a real MySQL instance.

Anti-Patterns

  • db.Query without Rows.Close() — connection leak; the pool will be exhausted quickly.
  • Prepare inside a goroutine/loop — explosive growth of descriptors on the MySQL server.
  • Ignoring the Rollback error — use defer tx.Rollback(), but log the error after Commit.
  • MaxIdleConns = 0 — every request opens a new TCP connection, latency increases 3–5x.
  • Storing *sql.Tx in context — complicates testing and breaks encapsulation.
  • No query timeouts — a single slow query blocks goroutines and exhausts the pool.

A high-load Go MySQL service is not magic. It's a properly configured pool, reusable statements, observability from day one, and tests against a real database.

Technologies

Tags

Ruslan Ismailov

Senior Web / Backend Developer. Senior web/backend developer with 9 years of experience. Stack: PHP, Laravel, PostgreSQL, Redis, Docker, Kubernetes, REST, microservices, CI/CD. More about me →