← Back to SQL, page 19

sql-0363 · Medium mid

A small web app on SQLite returns 'database is locked' errors under concurrent requests. How would you fix it?

SQLite allows one writer at a time, and in the default rollback journal mode writers also block readers. Enable WAL mode so readers and the writer do not block each other, set a busy timeout so writers wait briefly instead of failing, and keep write transactions short. If write concurrency is truly high, move to a client-server database.

Full answer

Checklist:

  • PRAGMA journal_mode = WAL; once per database file. Readers then see a consistent snapshot while one writer appends to the WAL.
  • PRAGMA busy_timeout = 5000; (or the driver's timeout setting) so a second writer waits up to five seconds for the lock.
  • Short write transactions: do not hold a transaction open across network calls or template rendering.
  • Use BEGIN IMMEDIATE for transactions that will write, so they take the write lock at the start instead of failing on upgrade from a read lock mid-transaction.
  • One connection per thread or request, not a shared connection used concurrently.

Other items in this bank show the busy error with timeout=0 in runs on SQLite 3.46.1. SQLite handles many web apps well, but sustained parallel writes or several servers sharing the file call for PostgreSQL or MySQL.

Key points

  • SQLite has one writer at a time
  • WAL lets readers and the writer proceed together
  • busy_timeout makes writers wait
  • BEGIN IMMEDIATE avoids upgrade failures
  • High write concurrency needs a server database

Common mistakes

  • Retrying in a tight loop without a timeout
  • Sharing one connection across threads

Follow-ups

  • What does a WAL checkpoint do?
  • Can SQLite work on a network file system?

Tips

  • Mention WAL and busy timeout together