Isolation levels
Isolation is how much one transaction sees of others that have not committed. sql.TxOptions.Isolation sets the level when you BeginTx. The database still enforces the real rules; Go only sends the request.
Detailed Explanation
Four ANSI levels show up in APIs: Read Uncommitted, Read Committed, Repeatable Read, Serializable. Each forbids more anomalies. Lower isolation means more concurrency and more surprises (dirty reads, non-repeatable reads, phantoms). Higher isolation means more waits and serialization failures you must retry.
Go constants. sql.LevelDefault (driver default), LevelReadUncommitted, LevelReadCommitted, LevelRepeatableRead, LevelSnapshot, LevelSerializable, LevelLinearizable. Not every database supports every level. Postgres default is Read Committed. A BeginTx with an unsupported level returns an error or silently upgrades, depending on the driver — check the driver docs.
What you actually pick. Read Committed is the usual default for request-scoped work. Serializable (or snapshot) is for money movement and inventory when you cannot express the invariant in a single constraint. If you choose Serializable, write a retry loop on serialization errors (40001 on Postgres).
ReadOnly. TxOptions{ReadOnly: true} lets the database optimize and refuse writes. Use it for reporting queries that still need a consistent snapshot.
What it costs. Serializable is not free: retries under contention can amplify load. Holding a Repeatable Read while you HTTP-call is how you stall writers. Keep transactions short regardless of level.
Code Examples
package main
import (
"context"
"database/sql"
)
func beginStrict(ctx context.Context, db *sql.DB) (*sql.Tx, error) {
return db.BeginTx(ctx, &sql.TxOptions{
Isolation: sql.LevelSerializable,
ReadOnly: false,
})
}
func beginRead(ctx context.Context, db *sql.DB) (*sql.Tx, error) {
return db.BeginTx(ctx, &sql.TxOptions{
Isolation: sql.LevelReadCommitted,
ReadOnly: true,
})
}
func main() {}Common Gotchas
`LevelDefault` is not portable
Postgres and MySQL defaults differ.
Serializable failures are not logic bugs
retry the whole transaction.
Isolation is not the same as a mutex in process
two app instances still need the database's rules.
`LevelSnapshot` is for engines that name it (SQL Server, some Postgres features)
do not assume it exists.