Sobes.tech
Middle

What are the transaction isolation levels, anomalies, and what does Serializable mean?

sobes.tech AI

Answer from AI

Transaction isolation levels determine how much one transaction can see the changes made by other concurrent transactions, and what anomalies may occur.

The main isolation levels (according to SQL standard):

  1. Read Uncommitted — a transaction can see uncommitted changes of other transactions (dirty read).
  2. Read Committed — a transaction only sees committed changes but can observe non-repeatable reads.
  3. Repeatable Read — guarantees that re-reading the same data within a transaction yields the same result, but allows phantom reads (new rows added by other transactions).
  4. Serializable — the strictest level, provides full transaction isolation, preventing all anomalies including phantom reads, as if transactions were executed sequentially.

Anomalies:

  • Dirty Read: reading uncommitted data.
  • Non-repeatable Read: data changes between two reads within the same transaction.
  • Phantom Read: new rows satisfying the query condition appear between two reads.

Serializable ensures that the result of parallel transaction execution is equivalent to some sequential order, preventing all the above anomalies.

Example in Go (simplified):

tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
if err != nil {
    // handle error
}
// operations with tx
err = tx.Commit()
What are the transaction isolation levels, anomalies… - sobes.tech