What happened
A recent Real Python tutorial on persisting data across program runs with Python, SQLite, and SQLAlchemy is a good prompt to revisit a decision many of us make by default. The tutorial compares flat files (CSV, JSON, XML, custom formats) against SQLite, which stores a database in a single file without a server. It aims to help you learn how to decide which approach is right for your program.
That is not a new release or a breaking change. It is a reminder that the persistence layer you pick on day one shapes what your code can do later.
Why it matters to you
Most small Python tools start with a JSON file. It takes a couple of lines to read and write, and you can open it in an editor. That works until it doesn't. Two failure modes show up, and both are in your code, not in JSON.
The first is the read-modify-write race. Your code reads the whole file into a dict, changes one key, and writes the whole file back. If a second process does the same between your read and your write, one update disappears. No error is raised. The data is just gone. This is a lost update, and a flat file gives you nothing to prevent it.
The second is full-file rewrite cost. Every save serializes the entire structure and replaces the file. With ten records that is invisible. The cost grows linearly with dataset size, so the pain arrives at a size that depends on record size and save frequency — measure before migrating. It happens on every single change.
Here is the JSON version. It is short, and both problems are baked in:
import json
from pathlib import Path
STORE = Path("users.json")
def load():
if not STORE.exists():
return {}
return json.loads(STORE.read_text())
def save(data):
STORE.write_text(json.dumps(data, indent=2))
def add_user(user_id, email):
data = load() # read the whole file
data[user_id] = email # modify one entry
save(data) # rewrite the whole file
add_user("u1", "a@example.com")SQLite gives you transactions, page-level writes, and a query engine, all in one file. A write either lands or it doesn't. An UPDATE touches only the pages holding that row, not the whole dataset, and the change is committed atomically. You get SQL, so filtering happens in the database instead of in a Python loop. And you still ship a single file with no server to install, which is the property that made JSON attractive.
You do not need SQLAlchemy to start. The standard library ships sqlite3, and it is enough for the migration:
import sqlite3
conn = sqlite3.connect("users.db")
# journal_mode is a query pragma: it returns the mode actually in effect.
mode = conn.execute("PRAGMA journal_mode=WAL").fetchone()[0]
if mode.lower() != "wal":
print(f"WAL not active (mode={mode}); concurrency is limited")
conn.execute("""
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
email TEXT NOT NULL UNIQUE
)
""")
with conn: # commits on success, rolls back on exception
conn.execute(
"INSERT INTO users (id, email) VALUES (?, ?) "
"ON CONFLICT(id) DO UPDATE SET email=excluded.email",
("u1", "a@example.com"),
)
row = conn.execute("SELECT email FROM users WHERE id = ?", ("u1",)).fetchone()
print(row[0])
conn.close()Three details matter. The with conn: block commits on success and rolls back if an exception is raised, so a failed write does not leave a partial transaction. SQLite's journal (or the WAL file in WAL mode) handles crash recovery. The ? placeholders pass values as parameters, which keeps user input out of the SQL string and prevents SQL injection. And the PRAGMA journal_mode=WAL result is checked, because the pragma returns the mode actually in effect, which may not be WAL (e.g., on some network filesystems), so the code checks the returned value rather than assuming.
Write-ahead logging is a persistent database setting, not a per-connection one. Once it is set on a database file, later connections inherit it. WAL needs shared memory between connections, which most network filesystems do not provide. SQLite may refuse WAL and keep the prior journal mode (often delete), which is why the code checks the returned value. Even when WAL is active, readers can proceed alongside one writer, but writers still serialize against each other. WAL is not a license for many concurrent writers.
Now the costs you accept. A schema is a contract. Your JSON file accepted any key you added; the table rejects a column that does not exist. Changing the shape of your data now means a migration — a script that moves old rows forward, often by creating a new table, copying rows, and swapping it in, since SQLite's ALTER TABLE is limited. That is real work, and it is the main reason people delay this move. Tooling is also thinner: you query with SQL or a library, not with cat and jq. Debugging means opening the database, not reading a text file.
If you want the object-mapping layer on top, SQLAlchemy lets you work with rows as Python objects. That is a second decision, not a requirement, and it adds its own learning curve. The Real Python tutorial walks through the same flat-file-versus-SQLite decision in more depth.
What to do about it
Do one thing this week: find every code path that rewrites the whole JSON file, and note how often each runs and whether more than one process can write. If there is one writer and the file stays small, leave it alone. Flat files are the right tool for config, fixtures, and small single-process state.
If you find concurrent writers, or a save that has become slow, migrate that one store. Write a short script that reads the JSON, creates the table, and inserts each record. Keep the JSON file as a backup until the new path has run in production for a while. Then delete the old load and save functions so nothing calls them by accident.
Two habits carry over. Set a schema you can live with, and treat every later change as a migration with a script you keep in the repo. And wrap writes in a transaction, because that is the exact guarantee the JSON version never gave you.
The limit to state plainly: SQLite is a single-file database, and it is not designed for many machines writing to the same file over a network share. If you need that, you need a server database, and this migration is not the answer.
If this store backs a service that retries writes, see durable agent workflows for retry and idempotency patterns. For the project layout around the migration script, see setting up a Python project layout.
Further reading
- Setting Up a Python Project So Your AI Agent Stops Guessing
Further reading
- The SAST report nobody opens: a triage loop that survives week ten
- Setting Up a Python Project So Your AI Agent Stops Guessing