Transactions, concurrency and queries · 4 MIN READ
BEGIN IMMEDIATE and one writer: avoid SQLITE_BUSY_SNAPSHOT that no timeout can fix
Explain why a deferred transaction that reads and then writes can fail with SQLITE_BUSY_SNAPSHOT regardless of busy_timeout, and prevent it with BEGIN IMMEDIATE through _txlock and a single-writer pool.
A plain BEGIN in SQLite is deferred: it takes no lock until the first statement, starts as a read transaction and tries to upgrade to a write transaction at the first write. If another connection committed in between, the reader's snapshot is stale and cannot be upgraded. SQLite reports that immediately as SQLITE_BUSY_SNAPSHOT, extended code 517, without calling the busy handler, so the busy_timeout from the previous lesson does nothing for it. Starting write transactions with BEGIN IMMEDIATE avoids the problem entirely.
sqlite · A MAP OF THE IDEA
- _txlock=immediate
- Writer pool of one
- query_only reader pool
- Retry whole tx on BUSY
Useful when
- Read-modify-write transactions become exact under concurrency.
- Writers queue in Go where context deadlines apply.
Watch out
- Immediate transactions hold the write lock from the start.
- Other processes or deferred code can still return SQLITE_BUSY.
Implementation & operation cost: Two *sql.DB values and a retry helper; every write path must use the writer pool.
Why waiting cannot help a stale snapshot
In WAL mode a read transaction pins a snapshot. To write, a connection must hold the write lock and be reading the latest version of the database. If another writer committed after the snapshot was taken, waiting for the lock would not make the snapshot current, because the values the transaction already read may be out of date. SQLite therefore fails the write at once with SQLITE_BUSY_SNAPSHOT. The only correct response is to roll back and run the whole transaction again, including its reads. In rollback-journal mode the same read-then-write pattern can deadlock two connections, and SQLite returns SQLITE_BUSY without invoking the busy handler for the same reason.
The failure, the fix, and a read-only pool
The program first reproduces the failure deterministically with two pinned connections running raw BEGIN statements: A reads, B reads, writes and commits, then A tries to write. It then runs a read-modify-write counter from eight goroutines on a pool opened with _txlock=immediate, so every BeginTx issues BEGIN IMMEDIATE. Finally it splits work into a writer pool limited to one connection and a reader pool opened with query_only.
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"os"
"path/filepath"
"sync"
"time"
"modernc.org/sqlite"
sqlite3 "modernc.org/sqlite/lib"
)
const common = "&_pragma=busy_timeout(1000)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)"
func open(path, params string) *sql.DB {
db, err := sql.Open("sqlite", "file:"+path+"?"+params+common)
if err != nil {
log.Fatal(err)
}
return db
}
func code(err error) int {
var se *sqlite.Error
if errors.As(err, &se) {
return se.Code()
}
return 0
}
func exec(ctx context.Context, c *sql.Conn, query string) error {
_, err := c.ExecContext(ctx, query)
return err
}
// increment is a read-modify-write in Go: read n, compute, write it back.
func increment(ctx context.Context, db *sql.DB) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
var n int
if err := tx.QueryRowContext(ctx, "SELECT n FROM counter").Scan(&n); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, "UPDATE counter SET n = ?", n+1); err != nil {
return err
}
return tx.Commit()
}
func main() {
ctx := context.Background()
dir, err := os.MkdirTemp("", "immediate")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "app.db")
deferred := open(path, "_txlock=deferred")
defer deferred.Close()
if _, err := deferred.ExecContext(ctx, "CREATE TABLE counter (n INTEGER NOT NULL); INSERT INTO counter VALUES (0)"); err != nil {
log.Fatal(err)
}
// Two deferred transactions both read, then both try to write.
a, _ := deferred.Conn(ctx)
b, _ := deferred.Conn(ctx)
defer a.Close()
defer b.Close()
var n int
_ = exec(ctx, a, "BEGIN")
_ = a.QueryRowContext(ctx, "SELECT n FROM counter").Scan(&n)
fmt.Println("A read n =", n)
_ = exec(ctx, b, "BEGIN")
_ = b.QueryRowContext(ctx, "SELECT n FROM counter").Scan(&n)
fmt.Println("B read n =", n)
fmt.Println("B update:", exec(ctx, b, "UPDATE counter SET n = 1"), "| B commit:", exec(ctx, b, "COMMIT"))
start := time.Now()
err = exec(ctx, a, "UPDATE counter SET n = 1")
fmt.Printf("A update: code %d, BUSY_SNAPSHOT=%v, waited for the busy timeout=%v\n",
code(err), code(err) == sqlite3.SQLITE_BUSY_SNAPSHOT, time.Since(start) >= 900*time.Millisecond)
fmt.Println("A must roll back and start over:", exec(ctx, a, "ROLLBACK") == nil)
a.Close()
b.Close()
// The same read-modify-write from 8 goroutines, with BEGIN IMMEDIATE.
immediate := open(path, "_txlock=immediate")
defer immediate.Close()
if _, err := immediate.ExecContext(ctx, "UPDATE counter SET n = 0"); err != nil {
log.Fatal(err)
}
var wg sync.WaitGroup
var mu sync.Mutex
failures := 0
for range 8 {
wg.Go(func() {
for range 25 {
if err := increment(ctx, immediate); err != nil {
mu.Lock()
failures++
mu.Unlock()
}
}
})
}
wg.Wait()
_ = immediate.QueryRowContext(ctx, "SELECT n FROM counter").Scan(&n)
fmt.Printf("immediate: 200 increments -> n=%d, failures=%d\n", n, failures)
// One writer connection, a separate read-only pool for queries.
writer := open(path, "_txlock=immediate")
writer.SetMaxOpenConns(1)
defer writer.Close()
readers := open(path, "_pragma=query_only(1)")
readers.SetMaxOpenConns(4)
defer readers.Close()
if err := increment(ctx, writer); err != nil {
log.Fatal(err)
}
_ = readers.QueryRowContext(ctx, "SELECT n FROM counter").Scan(&n)
fmt.Println("reader pool sees n =", n)
_, err = readers.ExecContext(ctx, "UPDATE counter SET n = 0")
fmt.Printf("reader pool write: code %d (%v)\n", code(err), err)
}A and B both read n = 0. B updates and commits without error. A's update fails with code 517, SQLITE_BUSY_SNAPSHOT, without waiting for the one-second busy timeout, and A can only roll back. With BEGIN IMMEDIATE, 8 goroutines times 25 increments end at exactly n=200 with no failures, because each transaction takes the write lock before it reads. The reader pool sees 201 after the writer's increment, and its write attempt fails with code 8, SQLITE_READONLY.
Make write transactions immediate
BEGIN IMMEDIATE takes the write lock at the start of the transaction. If another writer holds it, the begin itself waits under busy_timeout, which is exactly where waiting is safe, because nothing has been read yet. modernc.org/sqlite and mattn/go-sqlite3 both accept _txlock=immediate in the DSN to make BeginTx issue BEGIN IMMEDIATE, and ncruces/go-sqlite3 has the same option. In modernc.org/sqlite a BeginTx with sql.TxOptions{ReadOnly: true} still issues a plain deferred BEGIN on such a pool, so read-only transactions do not queue for the write lock. The read-only flag does not make the connection refuse writes; query_only does.
writer, _ := sql.Open("sqlite", "file:"+path+
"?_txlock=immediate&_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)")
writer.SetMaxOpenConns(1) // one writer, so writes queue in Go, not in SQLite
readers, _ := sql.Open("sqlite", "file:"+path+
"?_pragma=query_only(1)&_pragma=busy_timeout(5000)")
readers.SetMaxOpenConns(4)All writes go through the writer pool, whose single connection makes database/sql queue concurrent writers in Go instead of letting them contend for SQLite's lock. The reader pool serves queries in parallel under WAL and refuses accidental writes with SQLITE_READONLY.
One writer pool and one reader pool
SQLite permits one writer at a time no matter how many connections you open, so a large pool of writers only creates contention. A common service layout is a writer *sql.DB with SetMaxOpenConns(1) and immediate transactions, and a reader *sql.DB with several connections and query_only. A request waiting for the writer then waits on database/sql's pool, where the context deadline applies, rather than sleeping in the busy handler. Keep transactions on the writer short; one slow transaction delays every write behind it.
Still be ready to retry
Immediate transactions remove SQLITE_BUSY_SNAPSHOT from your own write paths, but SQLITE_BUSY can still appear when busy_timeout expires, when another process writes to the same file, or when a deferred transaction from code you do not control upgrades. Treat code 5 and its extended forms, such as 517, as retryable: roll back, wait briefly with jitter, and run the whole function again, reads included, a bounded number of times. Never retry only the failing statement inside the same transaction.
TAKE THIS WITH YOU
A deferred transaction that reads then writes can fail with SQLITE_BUSY_SNAPSHOT, which busy_timeout cannot fix. Begin write transactions with BEGIN IMMEDIATE via _txlock=immediate, route writes through a one-connection pool, read from a query_only pool and retry whole transactions.
Check your understanding
Two deferred transactions read a counter; one commits an update, then the other tries to update. With busy_timeout set to 5 s, what does the second get?
Go to the source
Progress stays in this browser. No account needed.