database/sql: pools, contexts and timeouts

What *sql.DB really is, opening and sizing the pool, the three query methods, placeholders and NULLs, and putting every query under a 500 ms deadline.

Learning outcomes

  • Explain why *sql.DB is a pool opened once in main, and why sql.Open does not prove MySQL is reachable.
  • Write the DSN with parseTime and loc, and size the pool with the four Set methods.
  • Use QueryContext, QueryRowContext and ExecContext correctly, closing rows and checking rows.Err.
  • Keep SQL injection out with placeholders, and scan NULL columns safely.
  • Put each read under a 500 ms deadline derived from the request context.
Prerequisite conceptsDatabase migration

Why database/sql matters

Your backend now has a MySQL schema containing restaurants, menu items, sizes, and configurable options. The next step is giving your Go application a reliable way to communicate with that database.

Go provides the standard library package database/sql for working with relational databases.

It provides a common interface for executing queries, retrieving rows, managing transactions, and controlling database connections. It does not implement MySQL communication itself. A database driver provides that functionality.

For this project, you'll use:

  • Go 1.25.
  • github.com/go-sql-driver/mysql v1.10.
  • MySQL 8.4 running through Docker Compose.
  • database/sql as the application-facing database API.

Understanding this package is important because almost every backend feature you'll build depends on database access: restaurant listings, menu retrieval, order creation, and order history.

Understanding sql.DB

The most important type in database/sql is *sql.DB.

Despite its name, it is not a single database connection.

It is a handle representing a managed connection pool.

A pool maintains multiple connections to MySQL and distributes database operations across them. When one operation finishes, its connection can be reused by another operation.

This matters because opening a new TCP connection for every database query would be unnecessarily expensive.

Consider a backend receiving 20 concurrent requests:

Concurrent request goroutines each borrow a connection from the single *sql.DB pool and return it after the query; an idle connection stays open for the next request, so the number of connections MySQL sees stays bounded.Concurrent request goroutines each borrow a connection from the single *sql.DB pool and return it after the query; an idle connection stays open for the next request, so the number of connections MySQL sees stays bounded.

Each request borrows a connection when it needs to execute a database operation. The connection is returned to the pool when the operation finishes and its resources are released.

Why open the pool only once?

*sql.DB is safe for concurrent use by multiple goroutines.

You should:

  1. Open it once when the API starts.
  2. Configure its connection pool.
  3. Verify connectivity.
  4. Pass the same *sql.DB to the components that need database access.
  5. Close it during application shutdown.

Do not create a new sql.DB inside every HTTP handler.

That would create multiple independent pools, making connection usage difficult to control and potentially exhausting MySQL's available connections.

Also, do not confuse the pool with an individual connection. A *sql.Conn represents a connection reserved for a particular operation or workflow, whereas *sql.DB manages the entire pool.

Connecting to MySQL

First, understand how the MySQL driver is registered.

Your backend imports:

go
import (
	"database/sql"

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

The blank import registers the MySQL driver with database/sql.

You can then open a database handle using the driver name mysql.

Understanding the DSN

A Data Source Name describes how your application connects to MySQL.

For local development, your connection string is:

root:dev@tcp(127.0.0.1:3306)/zomato?parseTime=true&loc=UTC

Let's break it down:

ComponentMeaning
rootMySQL username
devLocal development password
tcp(127.0.0.1:3306)TCP connection to localhost, port 3306
zomatoDatabase name
parseTime=trueParse MySQL DATE and DATETIME values into Go time.Time
loc=UTCUse UTC as the location when interpreting MySQL time values

Your application should read this DSN from the MYSQL_DSN environment variable rather than hardcoding credentials.

Why parseTime=true?

Without parseTime=true, the MySQL driver normally returns DATE and DATETIME values as byte slices.

This means a query returning created_at might need manual conversion before your application can work with it as a Go time value.

With:

parseTime=true

the driver can scan supported date and datetime columns directly into time.Time.

This becomes particularly useful when working with the created_at DATETIME(3) columns from your Week 2 schema.

Why loc=UTC?

Your application needs a consistent interpretation of timestamps.

Using UTC avoids accidentally interpreting database values according to the machine's local timezone.

There is an important distinction: loc=UTC controls the Go location used by the driver for time values. It does not change MySQL's session-level time_zone.

Also, MySQL DATETIME does not store timezone information. Your application should consistently treat these values as UTC by convention and configure database sessions appropriately.

Opening and configuring the pool

There is a subtle but important behaviour in sql.Open.

sql.Open does not establish a database connection immediately.

It validates the driver name and configuration and returns a database handle. The actual connection may be established later when the application executes its first query.

Therefore, your application should explicitly check connectivity during startup using PingContext.

backend/internal/database/mysql.go
package database

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

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

func Open(ctx context.Context, dsn string) (*sql.DB, error) {
	db, err := sql.Open("mysql", dsn)
	if err != nil {
		return nil, fmt.Errorf("open mysql: %w", err)
	}

	db.SetMaxOpenConns(20)
	db.SetMaxIdleConns(10)
	db.SetConnMaxLifetime(5 * time.Minute)
	db.SetConnMaxIdleTime(time.Minute)

	pingCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
	defer cancel()

	if err := db.PingContext(pingCtx); err != nil {
		_ = db.Close()
		return nil, fmt.Errorf("ping mysql: %w", err)
	}

	return db, nil
}

The startup ping checks that MySQL is reachable before the application starts accepting requests.

If the connection fails, close the database handle and return the error instead of starting an API that cannot serve database-backed requests.

Understanding pool settings

There are four important configuration methods.

MethodExamplePurpose
SetMaxOpenConns20Maximum simultaneous open connections
SetMaxIdleConns10Maximum connections kept idle for reuse
SetConnMaxLifetime5 minutesMaximum age of a connection
SetConnMaxIdleTime1 minuteMaximum time an unused connection remains idle

These are reasonable starting values for a small service, not universal production settings.

Maximum open connections

Without a limit, a sudden increase in concurrent database operations can cause your application to create many connections.

MySQL has a server-wide max_connections limit. Exhausting it can prevent new connections from being established.

Maximum idle connections

Idle connections are kept available so that the application doesn't need to establish a fresh connection for every request.

Too few idle connections can cause unnecessary connection creation during repeated bursts of traffic.

Maximum connection lifetime

Connections should not remain open indefinitely.

A load balancer, proxy, network device, or MySQL server may close connections independently. Recycling connections periodically reduces the chance of reusing stale connections.

Maximum idle time

This allows the pool to release connections that have been sitting unused for too long.

It is particularly useful when traffic is bursty and the service becomes idle between requests.

The Go driver recommends configuring connection lifetime to remain below relevant infrastructure timeouts. Adjust these values according to your actual deployment environment.

You can inspect pool behaviour using:

go
stats := db.Stats()

Useful statistics include open connections, idle connections, in-use connections, and the number of operations that waited for a connection.

Querying data with database/sql

You will primarily use three methods:

  • QueryContext for queries returning multiple rows.
  • QueryRowContext for queries expected to return one row.
  • ExecContext for statements that don't return rows.

Notice that all three accept a context.Context as their first argument.

This is intentional.

Every function performing database I/O in your project must accept a context as its first parameter and pass an appropriate context to the database operation.

QueryContext: retrieving multiple rows

Suppose you want to list active restaurants.

go
queryCtx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
defer cancel()

rows, err := db.QueryContext(
	queryCtx,
	`SELECT id, name FROM restaurants WHERE is_active = ?`,
	true,
)
if err != nil {
	return nil, err
}
defer rows.Close()

var restaurants []Restaurant

for rows.Next() {
	var restaurant Restaurant

	if err := rows.Scan(&restaurant.ID, &restaurant.Name); err != nil {
		return nil, err
	}

	restaurants = append(restaurants, restaurant)
}

if err := rows.Err(); err != nil {
	return nil, err
}

return restaurants, nil

There are several important details.

1. QueryContext returns rows

The query doesn't immediately return a collection of Go structs. It returns a *sql.Rows object that you iterate over.

2. Scan retrieves column values

Each call to Next() prepares the next row. You then call Scan() to copy the column values into your variables.

The destination order must match the selected column order.

3. Always close rows

Call rows.Close() when you finish consuming the result set.

4. Check rows.Err()

A query may fail during iteration, even if the initial QueryContext call succeeded.

Rows.Err() allows you to detect these errors.

QueryRowContext: retrieving one row

Use QueryRowContext when the query is expected to return at most one record.

For example, retrieving a restaurant by its ID:

go
var restaurant Restaurant

err := db.QueryRowContext(
	ctx,
	`SELECT id, name FROM restaurants WHERE id = ?`,
	id,
).Scan(&restaurant.ID, &restaurant.Name)

if errors.Is(err, sql.ErrNoRows) {
	return Restaurant{}, ErrNotFound
}
if err != nil {
	return Restaurant{}, err
}

An important difference is that QueryRowContext always returns a non-nil *sql.Row.

Errors are deferred until Scan() is called.

When no matching row exists, Scan() returns sql.ErrNoRows.

Use errors.Is to identify this condition rather than comparing error strings.

ExecContext: inserting and updating records

Use ExecContext for statements such as:

  • INSERT
  • UPDATE
  • DELETE

For example:

go
writeCtx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()

result, err := db.ExecContext(
	writeCtx,
	`INSERT INTO restaurants (name, lat, lng) VALUES (?, ?, ?)`,
	"Central Kitchen",
	12.9352,
	77.6245,
)
if err != nil {
	return err
}

id, err := result.LastInsertId()
if err != nil {
	return err
}

affected, err := result.RowsAffected()
if err != nil {
	return err
}

The sql.Result returned by ExecContext provides two useful methods:

  • LastInsertId() returns the generated identifier when supported by the driver.
  • RowsAffected() returns the number of rows affected by the operation.

For an UPDATE operation, RowsAffected() can help determine whether any matching rows were modified.

Some database configurations report changed rows rather than matched rows, so understand your driver's configuration when relying on this distinction.

Parameterized queries and SQL injection

Notice the question marks in the previous examples:

sql
SELECT id, name FROM restaurants WHERE id = ?

These are parameter placeholders.

You provide the actual values separately:

go
db.QueryRowContext(ctx, query, id)

The driver handles parameter binding rather than treating the supplied value as part of the SQL statement.

This protects values from being interpreted as SQL syntax.

Consider the dangerous alternative:

go
query := fmt.Sprintf(
	"SELECT id, name FROM restaurants WHERE name = '%s'",
	userInput,
)

If userInput contains specially crafted SQL, the resulting query can behave differently from what you intended.

This creates a SQL injection vulnerability.

Never build SQL statements by concatenating or formatting untrusted values. Use placeholders and pass values as separate arguments.

A limitation with IN clauses

A common mistake is assuming that one placeholder automatically expands a Go slice:

sql
SELECT id, name
FROM restaurants
WHERE id IN (?);

Passing []int64{1, 2, 3} as the argument does not make this equivalent to three placeholders.

The driver expects individual parameter values.

You need one placeholder per value, or a query-generation mechanism that creates the appropriate placeholders.

In Lesson 2.5, you'll learn how sqlc's sqlc.slice directive handles this case.

Handling NULL values

MySQL allows columns to contain NULL when they are declared nullable.

Every column in this week's schema is NOT NULL, but week 3's users table has one that is not:

sql
restaurant_id BIGINT UNSIGNED NULL

Only restaurant accounts have a restaurant, so for customers and riders the value is absent.

You cannot safely scan a SQL NULL into an ordinary Go int64 or string variable.

Use nullable SQL types such as:

go
var restaurantID sql.NullInt64
var description sql.NullString

After scanning:

go
if restaurantID.Valid {
	fmt.Println(restaurantID.Int64)
}

The Valid field indicates whether the database value was non-NULL.

Alternatively, you can use pointer destinations when you want NULL to become nil.

Choose a representation that makes the nullable nature of the field explicit in your application model.

Contexts, deadlines and query timeouts

A database query should not run indefinitely.

Suppose a restaurant-listing query becomes unexpectedly slow. Without a deadline, the request may keep a connection occupied while the application waits for MySQL.

Under heavy traffic, enough slow operations can exhaust the pool and cause unrelated requests to wait.

A query timeout places an upper bound on how long an operation should take.

For reads in this course, the requirement is 500 milliseconds.

Use:

go
queryCtx, cancel := context.WithTimeout(
	ctx,
	500*time.Millisecond,
)
defer cancel()

Then pass queryCtx into the database operation.

The deadline applies not only to query execution but also to waiting for a connection from the pool.

What happens when the deadline expires?

When the deadline is reached:

  1. The context is cancelled.
  2. The database operation receives the cancellation.
  3. The driver attempts to stop the operation.
  4. The operation returns an error.

With the MySQL driver, cancellation can cause the underlying connection to be closed if necessary to interrupt the operation safely.

The returned error may be context.DeadlineExceeded or wrap it. Use errors.Is(err, context.DeadlineExceeded) rather than comparing error strings.

Request cancellation propagates automatically

There is another important advantage of passing request contexts into database functions.

When an HTTP client disconnects or cancels its request, Go cancels the request context.

Any child context derived from it is cancelled as well.

For example:

A request derives a 500 ms context from r.Context(), borrows a connection from the sql.DB pool and runs the query; if it finishes in time the connection goes back to the pool, and if the deadline passes or the client disconnects the driver cancels the query and returns an error wrapping context.DeadlineExceeded.A request derives a 500 ms context from r.Context(), borrows a connection from the sql.DB pool and runs the query; if it finishes in time the connection goes back to the pool, and if the deadline passes or the client disconnects the driver cancels the query and returns an error wrapping context.DeadlineExceeded.

This means the database operation can stop because either the client no longer needs the result or the operation exceeds its own timeout.

Context must be the first parameter

Make this a consistent convention across the entire backend:

go
func GetRestaurant(
	ctx context.Context,
	db *sql.DB,
	id int64,
) (Restaurant, error)

The context is always the first parameter of a function that performs I/O.

Never store a request context inside a struct.

Bad:

go
type RestaurantStore struct {
	db  *sql.DB
	ctx context.Context
}

Good:

go
type RestaurantStore struct {
	db *sql.DB
}

func (s *RestaurantStore) Get(
	ctx context.Context,
	id int64,
) (Restaurant, error)

The database handle is a long-lived dependency. The context belongs to an individual operation.

Also, always call the cancellation function returned by context.WithTimeout. It releases resources associated with the derived context.

A complete store function and HTTP handler

Let's put these ideas together.

The store function retrieves one restaurant and returns a sentinel error when it doesn't exist.

backend/internal/restaurant/store.go
package restaurant

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

var ErrNotFound = errors.New("restaurant not found")

type Restaurant struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

func GetRestaurant(
	ctx context.Context,
	db *sql.DB,
	id int64,
) (Restaurant, error) {
	queryCtx, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
	defer cancel()

	var restaurant Restaurant

	err := db.QueryRowContext(
		queryCtx,
		`SELECT id, name FROM restaurants WHERE id = ?`,
		id,
	).Scan(&restaurant.ID, &restaurant.Name)

	if errors.Is(err, sql.ErrNoRows) {
		return Restaurant{}, fmt.Errorf("%w: id=%d", ErrNotFound, id)
	}
	if err != nil {
		return Restaurant{}, fmt.Errorf("get restaurant: %w", err)
	}

	return restaurant, nil
}

Notice that the function:

  • Receives its context first.
  • Creates its own bounded read context.
  • Uses QueryRowContext.
  • Handles sql.ErrNoRows.
  • Wraps errors with %w.

The HTTP handler can then distinguish a missing restaurant from an unexpected database failure.

backend/internal/restaurant/handler.go
package restaurant

import (
	"database/sql"
	"errors"
	"net/http"
	"strconv"

	"github.com/go-chi/chi/v5"

	"github.com/yashdagar/zomato-prep/backend/internal/httpx"
)

func GetByIDHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
		if err != nil || id <= 0 {
			httpx.WriteJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_id"})
			return
		}

		restaurant, err := GetRestaurant(r.Context(), db, id)
		if errors.Is(err, ErrNotFound) {
			httpx.WriteJSON(w, http.StatusNotFound, map[string]string{"error": "not_found"})
			return
		}
		if err != nil {
			httpx.WriteJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal_error"})
			return
		}

		httpx.WriteJSON(w, http.StatusOK, restaurant)
	}
}

Every error response is JSON with an error field, written with the httpx.WriteJSON helper from week 1; that is a requirement for the whole week. The HTTP handler does not need to know how the store queries MySQL. It only needs to understand the result and decide which HTTP response to return.

This separation will become increasingly valuable when your restaurant and menu endpoints grow.

Knowledge assessment

Question 1 of 4

What is the fundamental difference between *sql.DB and an individual MySQL connection?

Pick an answer, then say how sure you are.

Practical applications

Exercise 2.6: Generate the restaurant and menu queries

In the next lesson, you'll introduce sqlc and generate type-safe Go methods from SQL queries.

Those generated methods use the same database/sql operations you've learned here, including QueryContext, QueryRowContext, and ExecContext.

Understanding the underlying behaviour will help you reason about generated code rather than treating it as a black box.

Exercise 2.7: Seed 50 restaurants and one full menu

You'll use database writes to populate the restaurant and menu schema with realistic data.

You'll also rely on connection pooling, parameterized SQL, and proper resource management.

Modules 3 and 4: Restaurant listing and menu endpoints

These endpoints will retrieve multiple restaurants, apply cursor pagination, and assemble menu responses from related tables.

The 500 ms read timeout, context-first function signatures, connection-pool discipline, and correct handling of query results will become consistent requirements throughout the backend.

By the end of this module, database access should feel like a deliberate application layer rather than scattered SQL calls inside HTTP handlers.

References

Everything above is explained on this page; these are where it comes from (Go 1.25 database/sql, go-sql-driver/mysql v1.10, MySQL 8.4).

Finished Lesson 2.4?