Transactions
Commit and roll back.
Transactions is a free Go Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Transactions
A transaction groups several statements so they all succeed or all fail together. This keeps data consistent, for example moving money between two accounts without losing it midway.
- Atomic: all or nothing
- Consistent state
- Isolated from other transactions
db.Begin
Begin starts a transaction and returns a *sql.Tx. You run statements on the Tx, not on the pool, so they share one connection and one transaction.
tx, err := db.Begin()
if err != nil {
log.Fatal(err)
}Statements on the Tx
Call tx.Exec and tx.Query just like on the db, but everything runs inside the transaction until you commit or roll back.
_, err = tx.Exec("UPDATE accounts SET balance = balance - $1 WHERE id = $2", 100, 1)Commit
tx.Commit() makes every change permanent and visible to others. If it returns an error, the transaction was not applied.
if err := tx.Commit(); err != nil {
log.Fatal(err)
}Rollback
If any step fails, call tx.Rollback() to discard all changes since Begin. The database returns to its prior state as if nothing happened.
if err != nil {
tx.Rollback()
return err
}The defer Rollback Pattern
A robust idiom defers Rollback right after Begin. Rollback after a successful Commit is a harmless no-op, so this guarantees cleanup on any error path.
tx, err := db.Begin()
if err != nil { return err }
defer tx.Rollback()
// ... do work ...
return tx.Commit()Atomic Transfer Example
Two updates form one logical operation: subtract from one account, add to another. Both must commit together or neither should apply.
A Runnable Transaction Simulation
Real transactions need a database. This runnable example simulates begin, two updates, and commit-or-rollback with an in-memory map.
package main
import (
"errors"
"fmt"
)
func transfer(bal map[string]int, from, to string, amt int) error {
if bal[from] < amt {
return errors.New("insufficient funds")
}
snapshot := map[string]int{from: bal[from], to: bal[to]}
bal[from] -= amt
bal[to] += amt
if bal[from] < 0 {
bal[from], bal[to] = snapshot[from], snapshot[to]
return errors.New("rolled back")
}
return nil
}
func main() {
bal := map[string]int{"alice": 100, "bob": 20}
if err := transfer(bal, "alice", "bob", 30); err != nil {
fmt.Println("error:", err)
} else {
fmt.Println("committed:", bal)
}
}Isolation Levels
db.BeginTx accepts options including an isolation level, like sql.LevelSerializable. Higher isolation prevents more anomalies but can reduce concurrency.
tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})Keep Transactions Short
A transaction holds a connection and may hold locks. Do all the SQL quickly, avoid network calls or user input inside it, and commit promptly to reduce contention.
Never Mix db and tx
Inside a transaction, run statements only on the tx. Calling db.Exec there uses a different connection outside the transaction, so those changes are not part of it and will not roll back.
Quick Check
Test your transaction knowledge.
Recap
You learned transactions:
- Begin returns a *sql.Tx; run statements on it
- Commit persists; Rollback discards all changes
- defer tx.Rollback() guarantees cleanup on error
- BeginTx sets isolation; keep transactions short
- Never mix db and tx within one transaction
Frequently asked questions
Is the “Transactions” lesson free?
Yes — the full text of “Transactions” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “Transactions”?
Commit and roll back. You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Transactions” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.