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.
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/mysqlv1.10.- MySQL 8.4 running through Docker Compose.
database/sqlas 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:


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:
- Open it once when the API starts.
- Configure its connection pool.
- Verify connectivity.
- Pass the same
*sql.DBto the components that need database access. - 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:
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=UTCLet's break it down:
| Component | Meaning |
|---|---|
root | MySQL username |
dev | Local development password |
tcp(127.0.0.1:3306) | TCP connection to localhost, port 3306 |
zomato | Database name |
parseTime=true | Parse MySQL DATE and DATETIME values into Go time.Time |
loc=UTC | Use 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=truethe 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.
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.
| Method | Example | Purpose |
|---|---|---|
SetMaxOpenConns | 20 | Maximum simultaneous open connections |
SetMaxIdleConns | 10 | Maximum connections kept idle for reuse |
SetConnMaxLifetime | 5 minutes | Maximum age of a connection |
SetConnMaxIdleTime | 1 minute | Maximum 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:
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:
QueryContextfor queries returning multiple rows.QueryRowContextfor queries expected to return one row.ExecContextfor 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.
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, nilThere 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:
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:
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:
SELECT id, name FROM restaurants WHERE id = ?These are parameter placeholders.
You provide the actual values separately:
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:
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:
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:
restaurant_id BIGINT UNSIGNED NULLOnly 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:
var restaurantID sql.NullInt64
var description sql.NullStringAfter scanning:
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:
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:
- The context is cancelled.
- The database operation receives the cancellation.
- The driver attempts to stop the operation.
- 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:


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:
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:
type RestaurantStore struct {
db *sql.DB
ctx context.Context
}Good:
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.
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.
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
What is the fundamental difference between *sql.DB and an individual MySQL connection?
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).