Database / SQLite Interview questions
How does SQLite handle database locking?
SQLite uses a small set of lock states applied to the whole database file to coordinate access between
connections: UNLOCKED, SHARED (for reading), RESERVED (a writer intends
to write soon but hasn't yet), PENDING, and EXCLUSIVE (actively writing).
flowchart LR
A[UNLOCKED] --> B[SHARED - readers]
B --> C[RESERVED - writer intends to commit]
C --> D[PENDING - waiting for readers to finish]
D --> E[EXCLUSIVE - actively writing]
E --> A
Multiple connections can hold a SHARED lock simultaneously (concurrent readers), but only one
connection at a time can hold RESERVED/EXCLUSIVE, and a write can't finalize until
existing readers release their SHARED locks. If a lock can't be acquired immediately, SQLite
returns a SQLITE_BUSY error (or waits, if a busy timeout is configured), which application code
needs to handle by retrying rather than treating it as a fatal error.
More Related questions...