Joins, transactions, and the N+1 problem
A performance bug that turns up in almost any codebase that talks to a database.
By devskills editorial team · Last updated
N+1: one query, then one per row
You list twenty notes. For each one you fetch its attachment count. That is 1 + 20 = 21 round trips to the database. At two hundred notes it is 201. At a few milliseconds per round trip, the endpoint takes most of a second, and nothing in the Go code looks slow.
// SLOW — a query per notenotes, _ := repo.List(ctx, userID, limit, offset)for i := range notes { notes[i].Attachments, _ = attRepo.CountByNote(ctx, notes[i].ID) // N queries}// FAST — one query`SELECT n.id, n.title, n.body, COUNT(a.id) AS attachments FROM notes n LEFT JOIN attachments a ON a.note_id = n.id WHERE n.user_id = $1 GROUP BY n.id ORDER BY n.created_at DESC LIMIT $2 OFFSET $3`The other fix: fetch in one batch
When a join is awkward, collect the ids and do a second query for all of them at once. Two queries total, no matter how many rows.
ids := make([]int64, len(notes))for i, n := range notes { ids[i] = n.ID}rows, err := db.QueryContext(ctx, `SELECT note_id, id, filename FROM attachments WHERE note_id = ANY($1)`, ids) // pgx encodes a Go slice as a Postgres array// then group them into a map[int64][]Attachment and attach in one passMySQL and SQLite: build the IN (...) placeholders
ANY($1) with a slice is Postgres only. MySQL and SQLite have no array parameter, so you write one ? per id and pass the ids as separate arguments. Never paste the ids into the SQL string yourself.
if len(ids) == 0 { return nil, nil // "IN ()" is a syntax error, so skip the query}marks := make([]string, len(ids))args := make([]any, len(ids))for i, id := range ids { marks[i] = "?" args[i] = id}q := `SELECT note_id, id, filename FROM attachments WHERE note_id IN (` + strings.Join(marks, ",") + `)`rows, err := db.QueryContext(ctx, q, args...)Catch N+1 in a test: count the queries
Let the repository take a small interface instead of *sql.DB. In the test, wrap the real database in a type that counts calls. If someone puts a query back inside the loop, the count jumps and the test fails.
type DBTX interface { QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)}type countingDB struct { DBTX n int}func (c *countingDB) QueryContext(ctx context.Context, q string, args ...any) (*sql.Rows, error) { c.n++ return c.DBTX.QueryContext(ctx, q, args...)}func TestListIsNotNPlusOne(t *testing.T) { db := &countingDB{DBTX: testDB} // testDB: a real *sql.DB with 20 seeded notes repo := &Repository{db: db} if _, err := repo.ListWithAttachments(context.Background(), 1); err != nil { t.Fatal(err) } if db.n > 2 { t.Errorf("ListWithAttachments ran %d queries, want at most 2", db.n) }}Transactions: all of it, or none of it
Some operations must not half-happen. Creating a note and its first attachment row is one unit: if the second insert fails, the first must be undone.
func (r *Repository) CreateWithAttachment(ctx context.Context, n *Note, a *Attachment) (err error) { tx, err := r.db.BeginTx(ctx, nil) if err != nil { return err } defer func() { if p := recover(); p != nil { tx.Rollback() panic(p) // roll back, then let the panic continue } if err != nil { tx.Rollback() // named return: this sees the real error } }() if err = tx.QueryRowContext(ctx, insertNote, n.UserID, n.Title, n.Body).Scan(&n.ID); err != nil { return err } a.NoteID = n.ID if _, err = tx.ExecContext(ctx, insertAttachment, a.NoteID, a.Filename); err != nil { return err } return tx.Commit()}Transaction rules
- Keep them short. A transaction holds a pooled connection for its whole life. A few slow ones at once can use up the pool.
- Never make an HTTP call inside one. A slow third party then ties up a database connection that other requests need.
- Take row locks in a consistent order across the codebase, or two transactions grabbing the same two rows in opposite orders will deadlock.
- Do not wrap reads in a transaction out of habit. A single
SELECTis already atomic.
Read your query plan
EXPLAIN ANALYZESELECT id, title FROM notes WHERE user_id = 1 ORDER BY created_at DESC LIMIT 20;-- "Seq Scan on notes" means no index is being used. Add one.-- "Index Scan using notes_user_id_created_at_idx" is what you want.- Spot an N+1 query loop and fix it with a join or one batch query.
- Write a transaction with a deferred rollback that commits only on success.
- Read an
EXPLAIN ANALYZEplan to find a missing index.
- A query inside a loop is N+1. Fix it with a JOIN, or one batched
WHERE id = ANY($1). - A transaction is all-or-nothing. Use a named return so the deferred rollback sees the error.
- Transactions hold a connection: keep them short, and never call an external service inside one.
EXPLAIN ANALYZEevery query on a growing table. A sequential scan on a large table usually means a missing index.
EXPLAIN ANALYZE on the list query and confirm it uses your index.- 1Build the N+1 version with 200 rows and time it. Then do it with one JOIN and time that.
- 2Run
EXPLAIN ANALYZEon your list query before and after adding the index. - 3Write a two-statement transaction where the second fails, and confirm the first was rolled back.
- 4Open a transaction and sleep for 30 seconds inside it while running other requests. Watch the pool.