Breaking the database: sqlite
Learning about sqlite while we break it
sqlite is a library that implements a lightweight relational database that doesn't need a server. It lives inside a file, and opening a sqlite database is equivalent to an fopen.
It's important to understand that sqlite isn't a replacement for Oracle or PostgreSQL; it's a replacement for fopen.
If your project needs a relational database but you don't want to deal with the complexity of managing a server, sqlite is the right choice.
On the other hand, you shouldn't use sqlite when building online platforms. Depending on the number of users it might even work, but the better option is a client-server database, designed to handle many concurrent connections and high volumes of reads and writes.
ACID
To be a reliable database, sqlite implements the ACID concept, an acronym for:
- ATOMICITY: Either all changes happen at once, or none of them do;
- CONSISTENCY: The database is never left in an invalid state;
- ISOLATION: Each transaction happens in isolation; one doesn't interfere with another;
- DURABILITY: At the end of the operation, the changes are saved to disk;
ACID is a set of rules a database promises to provide. Being ACID compliant means guaranteeing those rules will be respected. Keep in mind that each database has its own mechanisms to guarantee the ACID properties. In SQL databases, these guarantees are enforced through transactions, which are the foundation of the transactional model.
Before we go around breaking things, we'll spend some time understanding how transactions happen inside sqlite. For this explanation I'll lean heavily on the content in reference [3].
1. Initial state
sqlite needs three different environments to manage its transactions:
- User space, where the sqlite library manipulates the data (the block on the left).
- System buffer, an area of memory used to reduce the number of disk reads (the block in the middle).
- The disk, the physical storage where data is persisted (the block on the right).
For this example, let's assume a cold cache, where there's no information on the user side. That means every read request has to go all the way to the database on disk.

2. Acquiring a SHARED lock
Before writing anything to the database, you have to read the data first. To read, the connection needs a SHARED lock. A lock is a mechanism for controlling concurrent access to a database. The SHARED lock grants read access. Keep in mind that many connections can hold this level of lock at the same time.

3. Reading the data
Once it has the SHARED lock, the read can happen. Since we start from a cold cache, the data is first read from disk, then placed in the system buffer (cache), and finally reaches sqlite3. Later reads can get the data from the cache.

4. Acquiring a RESERVED lock
sqlite has to acquire the RESERVED lock before making any change. This lock can coexist with several connections holding SHARED locks, but only one connection can hold the RESERVED lock.
This lock signals that the connection intends to make changes but hasn't started yet. Other connections can keep reading.

5. Creating a rollback journal file
Before modifying any data in the original database file, sqlite creates a separate file called the "rollback journal". This file will hold the original state of the pages that are about to change.

6. Changing the data on the user side
The changes start being made in the process's private memory (user space). The database on disk and the system cache still hold the original data.

7. Flushing the journal to disk
To guarantee durability, sqlite forces the rollback journal file to be written to the physical disk. This is crucial so the database can recover if a failure happens right after.

8. Acquiring an exclusive lock
Now sqlite needs an EXCLUSIVE lock. With this lock, no other connection can even read the database. This is the moment when the actual write to the main file begins.

9. Changing the data in the cache
The modified data moves from user space to the system buffer (cache). It isn't on the physical disk yet, but it has left the application's private memory.

10. Changing the data on disk
sqlite now tells the operating system to persist the changes to the actual database file. This is the step where the bits are physically changed on disk.

11. Deleting the rollback journal
This is a critical point: if the power goes out before the journals are deleted, the database may be in an inconsistent state. That's why, when a new connection is opened, the rollback is performed with the data in the journal and then the journal is deleted.
If the power goes out after the journal has been deleted, the next connection won't find any journals and no rollback will happen.

12. Releasing the lock
The last step is releasing the EXCLUSIVE lock, so other connections can acquire a SHARED or RESERVED lock.

There's still a lot more to learn about sqlite. Take a look at the references below if you're curious, but what we know is already enough to figure out what we can break.
Breaking things
To have some rows in a table, all the experiments below use a snippet similar to the one below. In the examples I'll leave out the init_db calls and focus on the experiment itself.
import sqlite3
import os
DB_PATH = "test_lock.db"
def init_db():
if os.path.exists(DB_PATH): # Check whether the database already exists
os.remove(DB_PATH) # If it does, delete it
conn = sqlite3.connect(DB_PATH) # sqlite creates the database the first time we open a connection
conn.execute("CREATE TABLE items (id INTEGER PRIMARY KEY, name TEXT)")
for i in range(5):
conn.execute("INSERT INTO items (name) VALUES (?)", (f"item-{i}",))
conn.commit()
conn.close()
Holding a SHARED lock for too long
What happens if a reader "forgets" an open transaction? Since sqlite prevents new writers from getting in while there are active readers, a single badly written query can cause a write bottleneck (SQLITE_BUSY) across the whole application.
I want to start by seeing a timeout when the connection stays open too long during a read:
def reader():
print("[Reader] Connecting...")
conn = sqlite3.connect(DB_PATH, timeout=1) # Open the connection with a 1-second timeout.
cursor = conn.cursor()
cursor.execute("SELECT * FROM items")
time.sleep(5) # Pause the process for 5 seconds
tasks = cursor.fetchall()
conn.close() # Close the connection only 5 seconds after opening it
print(tasks)
Output:
[Reader] Connecting...
[(1, 'item-0'), (2, 'item-1'), (3, 'item-2'), (4, 'item-3'), (5, 'item-4')]
"Where's the timeout, Rodrigo?" This shows a very important point: the timeout isn't about how long a connection stays open, it's about how long a lock can wait. To confirm that, we need to run the code below after starting the read.
import sqlite3
import time
DB_PATH = "test_lock.db"
def writer():
print("[Writer] Connecting...")
time.sleep(1) # Wait 1 second so the reader has time to take the SHARED lock.
conn = sqlite3.connect(DB_PATH, timeout=1)
conn.execute("INSERT INTO items (name) VALUES ('new-item')")
conn.commit()
Output:
[Reader] Connecting...
[Writer] Connecting...
sqlite3.OperationalError: database is locked
[(1, 'item-0'), (2, 'item-1'), (3, 'item-2'), (4, 'item-3'), (5, 'item-4')]
To write to the database, the connection needs an EXCLUSIVE lock, but that can only happen when there's no active SHARED lock. In this experiment we saw sqlite managing concurrency: in practice, it didn't grant the EXCLUSIVE lock because there was an active SHARED one.
Taking two RESERVED locks at the same time
sqlite allows many readers, but only one "would-be" writer. Let's simulate what happens when two processes try to start a write at the same time, and how the database decides who wins and who gets the error.
def writer_1():
print("[Writer 1] Connecting...")
time.sleep(1)
conn = sqlite3.connect(DB_PATH, timeout=1)
conn.execute("BEGIN IMMEDIATE") # Acquire a RESERVED lock manually.
time.sleep(10)
conn.close()
print("[Writer 1] Closing...")
def writer_2():
print("[Writer 2] Connecting...")
conn = sqlite3.connect(DB_PATH, timeout=1)
conn.execute("BEGIN IMMEDIATE") # Acquire a RESERVED lock manually.
conn.close()
print("[Writer 2] Closing...")
Output:
[Writer 1] Connecting...
[Writer 2] Connecting...
sqlite3.OperationalError: database is locked
[Writer 1] Closing...
There are 3 ways to ask sqlite for a lock:
- DEFERRED: the default; this mode doesn't acquire any lock;
- IMMEDIATE: this mode acquires a RESERVED lock. You might use it when you're sure you'll modify something and want to secure write priority;
- EXCLUSIVE: this mode acquires an EXCLUSIVE lock.
In the example above we took the lock manually, and since there can't be two RESERVED locks at the same time, the second one failed when it hit the timeout.
Reading before a commit
Let's see in practice how sqlite fully isolates the file during the critical moment of persisting to disk.
def writer():
print("[Writer] Connecting...")
time.sleep(1)
conn = sqlite3.connect(DB_PATH, timeout=1)
conn.execute("INSERT INTO items (name) VALUES ('new-item')")
cursor = conn.cursor()
cursor.execute("SELECT * FROM items")
tasks = cursor.fetchall()
print(tasks)
time.sleep(10)
conn.commit()
conn.close()
print("[Writer] Closing...")
def reader():
print("[Reader] Connecting...")
time.sleep(1)
conn = sqlite3.connect(DB_PATH, timeout=1)
cursor = conn.cursor()
cursor.execute("SELECT * FROM items")
tasks = cursor.fetchall()
print(tasks)
conn.close()
print("[Reader] Closing...")
Output:
[Writer] Connecting...
[(1, 'item-0'), (2, 'item-1'), (3, 'item-2'), (4, 'item-3'), (5, 'item-4'), (6, 'new-item')]
[Reader] Connecting...
[(1, 'item-0'), (2, 'item-1'), (3, 'item-2'), (4, 'item-3'), (5, 'item-4')]
[Reader] Closing...
[Writer] Closing...
There we saw isolation during a commit in practice: connection 2 didn't see item 6 until connection 1 committed.
Orphaned journal
Simulating a kill -9 on the process after the journal is created but before the final commit.
The goal is to watch sqlite's automatic recovery kick in on the next connection, using the journal to restore the database.
def writer():
print("[Writer] Connecting...")
time.sleep(1)
conn = sqlite3.connect(DB_PATH, timeout=1)
conn.execute("INSERT INTO items (name) VALUES ('new-item')")
time.sleep(10)
# This is where I closed the terminal
conn.commit()
conn.close()
print("[Writer] Closing...")
Before the commit, I closed the terminal that had the open connection. My plan was to see whether the journal would stay there until the next connection opened.

When a new connection opened, sqlite saw there was an active rollback journal, checked whether anything needed to be rolled back, and deleted the file.
Conclusion
In this article we saw what ACID is and how databases use transactions to guarantee atomicity, consistency, isolation and durability.
We also explored how this works in SQLite and ran a few hands-on experiments to validate the theory.
I thought about going further and testing scenarios with concurrency and race conditions, but this post is already long enough — so I'll leave that for another one.