database runtime_error ai_generated true

sqlite3.OperationalError: database is locked (background: SQLite busy timeout of 5000ms exceeded)

ID: database/sqlite-busy-timeout-exceeded

Also available as: JSON · Markdown · 中文
85%Fix Rate
85%Confidence
1Evidence
2023-11-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
SQLite 3.40 active
SQLite 3.41 active
SQLite 3.42 active

Root Cause

A write transaction is held by another connection for longer than the busy timeout, causing concurrent writes to fail.

generic

中文

另一个连接持有写事务的时间超过忙超时时间,导致并发写入失败。

Official Documentation

https://www.sqlite.org/lockingv3.html

Workarounds

  1. 90% success Set a higher busy timeout: PRAGMA busy_timeout = 30000; (30 seconds) to allow longer waits for locks.
    Set a higher busy timeout: PRAGMA busy_timeout = 30000; (30 seconds) to allow longer waits for locks.
  2. 85% success Switch to WAL mode: PRAGMA journal_mode=WAL; This allows concurrent reads while a write is in progress.
    Switch to WAL mode: PRAGMA journal_mode=WAL; This allows concurrent reads while a write is in progress.
  3. 80% success Use a connection pool with retry logic: from sqlite3 import connect; import time; for i in range(5): try: conn.execute(...); break; except sqlite3.OperationalError: time.sleep(1)
    Use a connection pool with retry logic: from sqlite3 import connect; import time; for i in range(5): try: conn.execute(...); break; except sqlite3.OperationalError: time.sleep(1)

中文步骤

  1. Set a higher busy timeout: PRAGMA busy_timeout = 30000; (30 seconds) to allow longer waits for locks.
  2. Switch to WAL mode: PRAGMA journal_mode=WAL; This allows concurrent reads while a write is in progress.
  3. Use a connection pool with retry logic: from sqlite3 import connect; import time; for i in range(5): try: conn.execute(...); break; except sqlite3.OperationalError: time.sleep(1)

Dead Ends

Common approaches that don't work:

  1. Set PRAGMA busy_timeout to 0 to disable timeout 80% fail

    Disabling timeout causes immediate failure on lock contention, making the problem worse instead of better.

  2. Use WAL mode but keep journal_mode=DELETE 50% fail

    WAL mode improves concurrency for readers but does not eliminate write contention; the lock still exists.