Middle+
What levels of transaction isolation do you know and what do they mean?
sobes.tech AI
Answer from AI
Main levels of transaction isolation:
- Read Uncommitted — the lowest isolation level, a transaction can see uncommitted changes of other transactions (dirty read).
- Read Committed — a transaction only sees data that has been committed by other transactions, preventing dirty reads, but non-repeatable reads are possible.
- Repeatable Read — guarantees that repeated reads of the same data within a transaction will be identical, preventing non-repeatable reads, but phantom reads are possible.
- Serializable — the highest isolation level, transactions are executed as if they were sequential, fully preventing phantom reads.
Example of usage in Node.js with PostgreSQL database via the pg library:
const { Client } = require('pg');
async function transactionExample() {
const client = new Client();
await client.connect();
try {
await client.query('BEGIN ISOLATION LEVEL SERIALIZABLE');
// database operations
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
await client.end();
}
}