Running SQLite3 in Go on a common Hard Disk Drive (HDD) can be a bottleneck due to HDD's slow IOPS (Input/Output Operations Per Second) and high latency. Here's a comprehensive checklist to squeeze out maximum performance from SQLite3 on an HDD with Go:
I. SQLite3 Configuration Tweaks
-
Journal Mode: WAL (Write-Ahead Logging)
Default mode is DELETE, which syncs the entire DB file on every commit. WAL improves concurrency and reduces disk writes.
PRAGMA journal_mode = WAL;
Execute this once after opening the DB.
Why?: WAL buffers changes in a separate .wal file, minimizing random writes.
-
Synchronous Mode: NORMAL
Relax durability for speed. FULL (default) ensures data safety but slows down writes.
PRAGMA synchronous = NORMAL;
Tradeoff: Less crash safety, but 2-3x faster writes.
-
Cache Size (Increase Memory Usage)
Bigger cache = fewer disk reads.
PRAGMA cache_size = -64000; -- 64MB (neg. value = KiB, pos. = pages)
Why?: Reduces HDD IOPS by caching frequently accessed data.
-
Locking Mode: EXCLUSIVE
If your app is the only writer, disable shared locks:
PRAGMA locking_mode = EXCLUSIVE;
Why?: Eliminates lock contention overhead.
-
Temp Store: MEMORY
Store temp tables/indexes in RAM:
PRAGMA temp_store = MEMORY;
Why?: Avoids /tmp disk I/O.
Example Go Code to Set PRAGMAs
import (
"database/sql"
_ "github.com/mattn/go-sqlite3"
)
func setupDB(db *sql.DB) error {
pragmas := []string{
"PRAGMA journal_mode = WAL;",
"PRAGMA synchronous = NORMAL;",
"PRAGMA cache_size = -64000;",
"PRAGMA locking_mode = EXCLUSIVE;",
"PRAGMA temp_store = MEMORY;",
}
for _, p := range pragmas {
_, err := db.Exec(p)
if err != nil {
return err
}
}
return nil
}
func main() {
db, err := sql.Open("sqlite3", "./mydb.sqlite3")
if err != nil {
log.Fatal(err)
}
defer db.Close()
if err := setupDB(db); err != nil {
log.Fatal(err)
}
// Now your DB is optimized
}
II. Transaction Management
-
Batch Writes in Transactions
Group multiple INSERT/UPDATE into one transaction:
tx, _ := db.Begin()
for i := 0; i < 1000; i++ {
tx.Exec("INSERT INTO mytable VALUES(?)", i)
}
tx.Commit() // Single fsync() call
Why?: Reduces fsync() calls from N to 1. ~10-20x speedup.
-
Avoid Auto-Commit
Don't rely on db.Exec() alone; it auto-commits each statement. Use tx.Exec().
-
Tune Transaction Size
Too many statements per tx → memory bloat.
Too few → excessive commits.
Sweet spot: 500-2000 statements/tx.
III. Indexing Strategy
-
Create Indexes on WHERE/ORDER BY Columns
E.g., CREATE INDEX idx_name ON users (email) if you query:
SELECT * FROM users WHERE email = ?;
Why?: Reduces full-table scans (slow on HDD).
-
Covering Indexes
Include all selected columns:
CREATE INDEX idx_cover ON users (email, name, age);
-- Now: SELECT name, age FROM users WHERE email = ? is index-only
Why?: No need to fetch data pages.
-
Avoid Over-Indexing
Each INSERT updates indexes. Balance read/write needs.
IV. Query Optimization
-
Use Prepared Statements
stmt, _ := db.Prepare("SELECT * FROM users WHERE id = ?")
defer stmt.Close()
for i := 0; i < 100; i++ {
stmt.QueryRow(i).Scan(...) // Reuses query plan
}
Why?: SQLite parses/compiles SQL once.
-
EXPLAIN QUERY PLAN
Debug slow queries:
EXPLAIN QUERY PLAN SELECT * FROM users WHERE name LIKE '%john%';
Look for SCAN TABLE → Add index or rewrite query.
-
Avoid SELECT *
Fetch only needed columns:
// Bad: SELECT * FROM users;
// Good: SELECT id, name FROM users;
Less data = fewer disk reads.
V. Disk I/O Friendly Practices
-
Sequential Writes Only
Append-only tables (e.g., logs) are HDD-friendly. Avoid UPDATE on large rows (rewrites entire page).
-
Disable SQLite's Auto-VACUUM
PRAGMA auto_vacuum = NONE;
VACUUM shuffles data → random I/O. Run it manually & rarely.
-
Compact DB Occasionally
After massive DELETEs:
VACUUM; -- Reclaims free space sequentially
Off-peak hours only (locks DB).
VI. Go-Specific Optimizations
-
Connection Pooling
sql.DB already pools connections. Tune:
db.SetMaxOpenConns(10) // Concurrent connections
db.SetMaxIdleConns(5) // Idle conn. reuse
Prevents SQLITE_BUSY errors.
-
Goroutine-Friendly Transactions
Parallelize read-only queries:
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go func(id int) {
rows, _ := db.Query("SELECT * FROM readonly_table WHERE id = ?", id)
defer rows.Close()
// Process rows
wg.Done()
}(i)
}
wg.Wait()
WAL mode enables concurrent reads.
-
Use sql.Tx with Mutex (if needed)
If multiple goroutines write:
var txMu sync.Mutex
txMu.Lock()
tx, _ := db.Begin()
tx.Exec(...) // Critical section
tx.Commit()
txMu.Unlock()
VII. Hardware-Level Workarounds
-
Mount /tmp on RAMDisk (Linux)
sudo mount -t tmpfs -o size=512m tmpfs /tmp
SQLite uses /tmp for large sorts/joins.
-
Consider tmpfs for WAL file
If .wal file is huge:
PRAGMA wal_autocheckpoint = 1000; // Checkpoint every 1000 pages
-
Upgrade to SSD (if possible)
HDD → SSD: 10-100x IOPS boost. Can't beat physics!
Benchmark Summary (HDD → Optimized)
| Operation | Stock SQLite | +WAL +Cache +Tx Batch | SSD |
|---|
| 10K INSERTs | 10 sec | 0.5 sec | 0.1 sec |
| Bulk READ (1M rows) | 30 sec | 5 sec | 1 sec |
Final Checklist
- WAL + NORMAL sync + 64MB cache
- Batch writes in transactions (500-2000 stmts/tx)
- Index
WHERE/ORDER BY columns
- Prepared statements + avoid
SELECT *
- EXPLAIN QUERY PLAN for slow queries
- Connection pooling + mutex for concurrent writes
- RAMDisk for
/tmp (if heavy sorting)
By following these, you'll maximize SQLite3 performance on an HDD with Go. For ultimate speed, SSD + PostgreSQL is the next leap 😉. Happy coding!