Transactions, concurrency and queries · 4 MIN READ
WAL mode, synchronous and busy_timeout: readers that never wait and writers that queue
Switch a database to write-ahead logging, explain which settings persist in the file and which are per connection, and turn SQLITE_BUSY into a bounded wait with busy_timeout.
In SQLite's default rollback-journal mode a writer must wait for readers to finish and readers wait while a writer commits. Write-ahead logging changes that: writers append to a separate -wal file, readers keep reading a consistent snapshot, and the two no longer block each other. There is still exactly one writer at a time, so a second writer either fails at once with SQLITE_BUSY or, with busy_timeout, waits its turn.
sqlite · A MAP OF THE IDEA
- journal_mode=WAL once
- busy_timeout in DSN
- synchronous per need
- Close readers promptly
Useful when
- Readers never block the writer and the writer never blocks readers.
- Lock conflicts become bounded waits instead of errors.
Watch out
- Still a single writer; WAL does not add write concurrency.
- Needs a local file system; -wal and -shm travel with the file.
Implementation & operation cost: Two side files, periodic checkpoints and a DSN that configures every connection; long readers can make the log grow.
Settings that live in the file and settings that do not
PRAGMA journal_mode=WAL is persistent: once set, the database stays in WAL mode for every later connection and process until another journal mode is chosen. Almost everything else you configure is per connection and lasts only as long as that connection: busy_timeout, synchronous, foreign_keys, cache_size and query_only. With a pool you therefore set them in the DSN, which modernc.org/sqlite applies to every new connection, rather than with a one-off db.Exec that reaches only one of the pooled connections.
dsn := "file:" + path +
"?_pragma=busy_timeout(5000)" +
"&_pragma=journal_mode(WAL)" +
"&_pragma=synchronous(NORMAL)"
db, err := sql.Open("sqlite", dsn)Each _pragma runs on every connection the pool opens, busy_timeout first. journal_mode(WAL) is idempotent once the file is in WAL mode, and synchronous(NORMAL) must be repeated per connection because it is not stored in the file.
Snapshots, persistence and lock waits in one program
The program opens an application pool with WAL, NORMAL and a five-second busy timeout, writes a row and checks the side files. A second pool with no parameters shows what persisted. A read transaction on that pool then watches a writer commit, and finally one connection holds the write lock with BEGIN IMMEDIATE while two other pools try to insert: one with busy_timeout 0 and one with 2000 ms, released by a goroutine after 100 ms.
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"log"
"os"
"path/filepath"
"time"
"modernc.org/sqlite"
)
func open(path, params string) *sql.DB {
db, err := sql.Open("sqlite", "file:"+path+params)
if err != nil {
log.Fatal(err)
}
return db
}
func scalar[T any](ctx context.Context, q interface {
QueryRowContext(context.Context, string, ...any) *sql.Row
}, query string) T {
var v T
if err := q.QueryRowContext(ctx, query).Scan(&v); err != nil {
log.Fatal(err)
}
return v
}
func exists(path string) bool { _, err := os.Stat(path); return err == nil }
func main() {
ctx := context.Background()
dir, err := os.MkdirTemp("", "wal")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
path := filepath.Join(dir, "app.db")
// The application pool: WAL, NORMAL sync and a 5 s busy timeout on every connection.
app := open(path, "?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)")
defer app.Close()
fmt.Println("journal_mode:", scalar[string](ctx, app, "PRAGMA journal_mode"))
if _, err := app.ExecContext(ctx, "CREATE TABLE events (id INTEGER PRIMARY KEY, name TEXT)"); err != nil {
log.Fatal(err)
}
if _, err := app.ExecContext(ctx, "INSERT INTO events (name) VALUES ('boot')"); err != nil {
log.Fatal(err)
}
fmt.Println("-wal and -shm files exist:", exists(path+"-wal"), exists(path+"-shm"))
// A pool with no parameters: journal_mode is stored in the file, synchronous is not.
plain := open(path, "")
defer plain.Close()
fmt.Println("plain pool journal_mode:", scalar[string](ctx, plain, "PRAGMA journal_mode"))
fmt.Println("synchronous app/plain:", scalar[int](ctx, app, "PRAGMA synchronous"), scalar[int](ctx, plain, "PRAGMA synchronous"))
// Readers keep a snapshot; the writer does not wait for them.
reader, err := plain.BeginTx(ctx, &sql.TxOptions{ReadOnly: true})
if err != nil {
log.Fatal(err)
}
fmt.Println("reader sees rows:", scalar[int](ctx, reader, "SELECT count(*) FROM events"))
if _, err := app.ExecContext(ctx, "INSERT INTO events (name) VALUES ('login')"); err != nil {
log.Fatal(err)
}
fmt.Println("writer committed while the reader was open")
fmt.Println("reader still sees rows:", scalar[int](ctx, reader, "SELECT count(*) FROM events"))
if err := reader.Commit(); err != nil {
log.Fatal(err)
}
fmt.Println("a new read sees rows:", scalar[int](ctx, plain, "SELECT count(*) FROM events"))
// Writers do wait for each other. Hold the write lock on one connection.
holder, err := app.Conn(ctx)
if err != nil {
log.Fatal(err)
}
defer holder.Close()
if _, err := holder.ExecContext(ctx, "BEGIN IMMEDIATE"); err != nil {
log.Fatal(err)
}
impatient := open(path, "?_pragma=busy_timeout(0)")
defer impatient.Close()
_, err = impatient.ExecContext(ctx, "INSERT INTO events (name) VALUES ('impatient')")
var se *sqlite.Error
if errors.As(err, &se) {
fmt.Printf("busy_timeout=0: code %d, %v\n", se.Code(), err)
}
release := make(chan struct{})
go func() {
time.Sleep(100 * time.Millisecond)
if _, err := holder.ExecContext(ctx, "COMMIT"); err != nil {
log.Fatal(err)
}
close(release)
}()
patient := open(path, "?_pragma=busy_timeout(2000)")
defer patient.Close()
start := time.Now()
_, err = patient.ExecContext(ctx, "INSERT INTO events (name) VALUES ('patient')")
waited := time.Since(start)
<-release
fmt.Println("busy_timeout=2000: err =", err, "| waited at least 80ms:", waited >= 80*time.Millisecond)
fmt.Println("rows now:", scalar[int](ctx, app, "SELECT count(*) FROM events"))
}journal_mode reports wal and both app.db-wal and app.db-shm exist. The plain pool also reports wal, but synchronous is 1 (NORMAL) on the app pool and 2 (FULL, the default) on the plain one. The reader sees 1 row, the writer commits without waiting, the reader still sees 1, and a fresh read sees 2. With busy_timeout 0 the insert fails at once with code 5, SQLITE_BUSY; with 2000 ms it waits until the holder commits, succeeds, and the table ends with 3 rows.
What WAL changes and what it costs
A reader in WAL mode sees the database as of the moment its read transaction started and keeps that snapshot until it ends, while a writer appends new page versions to the -wal file. A checkpoint copies those pages back into the main file; SQLite runs one automatically when the log passes about 1000 pages. A reader that never finishes stops the checkpoint from reaching the end of the log, so the -wal file keeps growing, which is one more reason to close rows promptly. WAL needs shared memory through the -shm file, so every process using the database must be on the same host; it does not work on network file systems. The database, -wal and -shm belong together: copy a live database with VACUUM INTO or the backup API, not by copying the main file.
synchronous=NORMAL in WAL mode
synchronous controls how often SQLite waits for the disk with fsync. FULL syncs the log on every commit. In WAL mode NORMAL syncs only at checkpoints, and the SQLite documentation states that the database stays consistent and uncorrupted: an application crash loses nothing that was committed, but a power failure or operating system crash may roll back the most recent transactions. That is the usual choice for application databases where a few seconds of lost writes after a power cut is acceptable. Keep FULL when every acknowledged commit must survive power loss, such as a ledger that has already told a client yes.
busy_timeout turns a lock conflict into a bounded wait
When a connection needs a lock another connection holds, SQLite calls its busy handler. With busy_timeout 0, the default, there is no handler and the statement fails immediately with SQLITE_BUSY, code 5, reported by modernc.org/sqlite as database is locked. busy_timeout(ms) installs a handler that sleeps and retries until the lock frees or the time runs out. Five seconds is a common starting point for services. Set it in the DSN so that every pooled connection has it, and still handle SQLITE_BUSY: under sustained write load a timeout can expire, and some conflicts, covered in the next lesson, are reported without waiting at all.
TAKE THIS WITH YOU
Set journal_mode=WAL once, and busy_timeout and synchronous on every connection through the DSN. WAL lets readers and the single writer proceed together, NORMAL trades the last commits on power loss for speed, and busy_timeout makes writers queue instead of failing.
Check your understanding
You run db.Exec("PRAGMA busy_timeout = 5000") once at startup on a pool. Why do some requests still fail at once with SQLITE_BUSY?
Go to the source
Progress stays in this browser. No account needed.