Isolation levels
Isolation levels decide what one transaction can see of another's uncommitted or concurrent work. From weakest to strongest: Read Uncommitted, Read Committed, Repeatable Read, Serializable.
Detailed Explanation
Atomicity says a transaction commits whole. Isolation says whether you can see someone else's in-flight or just-committed rows while you are still running. Weaker isolation means more concurrency and more anomalies. Stronger isolation means more locks or more retries.
Read Uncommitted can see dirty data (another transaction's uncommitted writes). Almost nobody wants this for money. Read Committed, the Postgres default, sees only committed rows, but two SELECTs in the same transaction can return different values if another commit landed between them (a non-repeatable read). Phantom reads are new rows that appear in a second query with the same predicate.
Repeatable Read (and Postgres's Repeatable Read, which is snapshot-based) gives you a stable snapshot for the transaction. You will not see later commits. You can still write conflicts: a commit may fail with a serialization error. Serializable is the strongest: the database tries to make the outcome identical to some serial order of transactions. You write retry loops.
In Python you set the level on the connection or session: conn.isolation_level, SQLAlchemy session.connection().execution_options(isolation_level="SERIALIZABLE"), Django transaction.atomic(durable=True) plus database defaults. sqlite has a simpler locking story (DEFERRED, IMMEDIATE, EXCLUSIVE) that is not the full ANSI menu.
Application-level "SELECT then UPDATE" under Read Committed is a race. Use SELECT ... FOR UPDATE, a single UPDATE ... WHERE, or Serializable plus retry. Do not assume the ORM made it safe.
Retries must be idempotent. A serialization failure is a 40001 (Postgres) or an OperationalError. Catch, backoff, rerun the whole transaction, not a single statement.
Code Examples
# sqlite: default is DEFERRED. IMMEDIATE takes a write lock on first write.
import sqlite3
conn = sqlite3.connect(":memory:")
print(conn.isolation_level) # "" or "DEFERRED" depending on version
conn.isolation_level = "IMMEDIATE"# Application pattern: update in one statement, not check-then-set.
SQL = "update accounts set cents = cents - ? where id = ? and cents >= ?"
# cur.execute(SQL, (40, "a", 40))
# if cur.rowcount != 1: raise ValueError("insufficient")Common Gotchas
Read-then-write under Read Committed
two tickets sell the last seat. Lock the row or use a conditional update.
Serializable without a retry loop
the first conflict raises and the user sees 500. Retry the transaction.
Assuming sqlite is Postgres
isolation names and behaviour differ. Test on the engine you ship.
"I used a transaction" is not "I used Serializable"
the default is often Read Committed.