Mastering Go Transactions: Three Patterns and a Safer Defer‑Rollback Technique
This article compares three Go transaction implementations, explains their trade‑offs, and presents a refined pattern that uses defer tx.Rollback() to guarantee rollback while still allowing successful commits, covering both simple and loop‑based use cases.
First Approach
This straightforward method embeds transaction handling directly in the program flow, making the logic clear but prone to omissions that can cause serious issues.
func DoSomething() (err error) {
tx, err := db.Begin()
if err != nil {
return
}
defer func() {
if p := recover(); p != nil {
tx.Rollback()
panic(p) // re‑throw panic after Rollback
}
}()
if _, err = tx.Exec(...); err != nil {
tx.Rollback()
return
}
if _, err = tx.Exec(...); err != nil {
tx.Rollback()
return
}
// ...
err = tx.Commit()
return
}Second Approach
This version extracts transaction handling from the main logic, reducing the chance of omission, but the transaction scope spans the entire function, making the flow less clear.
func DoSomething() (err error) {
tx, err := db.Begin()
if err != nil {
return
}
defer func() {
if p := recover(); p != nil {
tx.Rollback()
panic(p) // re‑throw panic after Rollback
} else if err != nil {
tx.Rollback()
} else {
err = tx.Commit()
}
}()
if _, err = tx.Exec(...); err != nil {
return
}
if _, err = tx.Exec(...); err != nil {
return
}
// ...
return
}Third Approach
This pattern further abstracts the second method into a reusable helper, offering a more advanced encapsulation while sharing the same drawbacks.
func Transact(db *sql.DB, txFunc func(*sql.Tx) error) (err error) {
tx, err := db.Begin()
if err != nil {
return
}
defer func() {
if p := recover(); p != nil {
tx.Rollback()
panic(p) // re‑throw panic after Rollback
} else if err != nil {
tx.Rollback()
} else {
err = tx.Commit()
}
}()
err = txFunc(tx)
return
}
func DoSomething() error {
return Transact(db, func(tx *sql.Tx) error {
if _, err := tx.Exec(...); err != nil {
return err
}
if _, err := tx.Exec(...); err != nil {
return err
}
return nil
})
}My Preferred Pattern
After testing, I adopt the following style where defer tx.Rollback() ensures rollback is always executed; after a successful tx.Commit(), the deferred rollback simply closes the transaction, while any error before commit triggers a rollback.
Normal Scenario
func DoSomething() (err error) {
tx, _ := db.Begin()
defer tx.Rollback()
if _, err = tx.Exec(...); err != nil {
return
}
if _, err = tx.Exec(...); err != nil {
return
}
// ...
err = tx.Commit()
return
}Loop Scenario
(1) Small transactions: commit each iteration. Since defer cannot be used inside a loop, the transaction logic is moved to a separate function.
func DoSomething() (err error) {
tx, _ := db.Begin()
defer tx.Rollback()
if _, err = tx.Exec(...); err != nil {
return
}
if _, err = tx.Exec(...); err != nil {
return
}
// ...
err = tx.Commit()
return
}
for {
if err := DoSomething(); err != nil {
// handle error
}
}(2) Large transactions: batch commit, which follows the same pattern as the normal scenario without any special changes.
func DoSomething() (err error) {
tx, _ := db.Begin()
defer tx.Rollback()
for {
if _, err = tx.Exec(...); err != nil {
return
}
if _, err = tx.Exec(...); err != nil {
return
}
// ...
}
err = tx.Commit()
return
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
