Transactions and performance

Test SQLite locking with two connections

Use two shell connections to see one-writer locking, busy timeouts, and BEGIN IMMEDIATE in practice.

8 minute lesson

~~~

SQLite allows many readers, but only one connection can write at a time. Let’s see the lock instead of only reading about it.

Open notes.db in two terminals. In both shells, set a three-second busy timeout:

.timeout 3000

In terminal A, claim the write lock and keep the transaction open:

BEGIN IMMEDIATE;
UPDATE notes SET title = 'Held by terminal A' WHERE id = 1;

BEGIN IMMEDIATE asks for the write lock at the start. Do not commit yet.

In terminal B, try another write:

BEGIN IMMEDIATE;

Terminal B waits for up to three seconds, then reports database is locked. Return to terminal A and run COMMIT;. Terminal B can now retry and acquire the lock.

A busy timeout handles a brief conflict. It does not fix long transactions. Never wait for a network request or slow calculation while holding a write transaction open.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →