Skip to content

Neo4j ACID Transactions ​

Native ACID Support ​

Neo4j is fully ACID:

  • ✅ Atomicity: All-or-nothing
  • ✅ Consistency: Constraints enforced
  • ✅ Isolation: Read committed (by default; use explicit locks for stronger guarantees)
  • ✅ Durability: Write-ahead log (WAL)

Automatic transactions:

cypher
// cypher-shell; id mẫu 123 phải chưa có nếu đã tạo ràng buộc unique:
// CREATE CONSTRAINT user_id_unique IF NOT EXISTS FOR (u:User) REQUIRE u.id IS UNIQUE;
// Single Cypher statement = automatic transaction
CREATE (u:User {id: 123, name: 'John'});

// Each auto-commit statement in a session is its own transaction; use an explicit/managed transaction to group statements
MATCH (u:User {id: 123})
SET u.lastLogin = timestamp()
RETURN u;

Explicit transactions (JavaScript):

javascript
// Node.js (neo4j-driver 5); chạy trong hàm async
const neo4j = require('neo4j-driver')
const driver = neo4j.driver('bolt://localhost:7687', neo4j.auth.basic('neo4j', 'your-password'))
const session = driver.session()
const tx = session.beginTransaction()

try {
  // All operations in same transaction (id 124/456 không trùng với 123 ở khối trên khi có unique constraint)
  await tx.run('CREATE (u:User {id: $id, name: $name})', {
    id: 124,
    name: 'John'
  })

  await tx.run('CREATE (p:Product {id: $id, name: $name})', {
    id: 456,
    name: 'Laptop'
  })

  await tx.run(`
    MATCH (u:User {id: $userId}), (p:Product {id: $productId})
    CREATE (u)-[:PURCHASED {date: $date}]->(p)
  `, {
    userId: 124,
    productId: 456,
    date: new Date().toISOString()
  })

  await tx.commit()
  console.log('Transaction committed')
} catch (error) {
  await tx.rollback()
  console.log('Transaction rolled back:', error)
} finally {
  await session.close()
}

Lock Mechanisms ​

Reads (MATCH … RETURN):

cypher
// READ COMMITTED mặc định: đọc thuần KHÔNG lấy khoá, không chặn writer và không bị writer chặn
// Chỉ thấy dữ liệu đã commit
MATCH (u:User {id: 123})
RETURN u;

Write locks (exclusive locks):

cypher
// Chỉ MỘT giao dịch giữ khoá ghi trên node tại một thời điểm
MATCH (u:User {id: 123})
SET u.balance = u.balance - 100;
// Giao dịch khác ghi cùng node phải chờ tới khi khoá được nhả (đo: writer chờ ~3 s)

Deadlock detection:

text
Transaction A: giữ khoá User 1, chờ User 2
Transaction B: giữ khoá User 2, chờ User 1
→ Neo4j phát hiện deadlock và huỷ MỘT giao dịch với lỗi tạm Neo.TransientError.Transaction.DeadlockDetected

Giảm deadlock: cập nhật các node theo CÙNG thứ tự (A rồi B), thử lại giao dịch có giới hạn số lần và nghỉ giữa các lần. MERGE lấy khoá không theo thứ tự đó: dùng CREATE nếu không cần unique.

Isolation Levels ​

Neo4j uses READ COMMITTED (default):

text
Dirty reads:        ❌ Prevented
Non-repeatable reads: ✅ Possible
Phantom reads:      ✅ Possible

Example of non-repeatable read:

javascript
// Node.js (neo4j-driver 5); chạy trong hàm async, `driver` tạo như ở mục Native ACID Support
const session1 = driver.session()
const session2 = driver.session()

// Transaction 1
const tx1 = session1.beginTransaction()
const result1 = await tx1.run('MATCH (u:User {id: 123}) RETURN u.balance AS balance')
// balance = 1000

// Transaction 2 (commits)
await session2.run('MATCH (u:User {id: 123}) SET u.balance = 500')

// Transaction 1 (reads again)
const result2 = await tx1.run('MATCH (u:User {id: 123}) RETURN u.balance AS balance')
// balance = 500 (changed!), đo trên neo4j:5.26
await tx1.commit()

Workaround for repeatable read:

javascript
// Node.js (neo4j-driver 5); chạy trong hàm async, dùng `driver` ở trên
const session = driver.session()
const tx = session.beginTransaction()

// Lấy khoá ghi bằng thuộc tính tạm rồi xoá ngay (Cypher không có lệnh khoá riêng)
await tx.run('MATCH (u:User {id: 123}) SET u._dummy_ = true REMOVE u._dummy_')

// Giao dịch khác không ghi được node này tới khi commit (đo: writer chờ ~2 s), nên hai lần đọc giống nhau
const result1 = await tx.run('MATCH (u:User {id: 123}) RETURN u.balance AS balance')
const result2 = await tx.run('MATCH (u:User {id: 123}) RETURN u.balance AS balance')
// Same value (locked)

await tx.commit()
await session.close()

Phải nhớ

  • Neo4j: ACID, mặc định READ COMMITTED; đọc thuần không lấy khoá nên đọc lại có thể thấy giá trị mới.
  • Deadlock cho lỗi tạm Neo.TransientError.Transaction.DeadlockDetected: cập nhật theo cùng thứ tự và thử lại.
  • db.transaction.timeout mặc định 0s (tắt, đo bằng SHOW SETTINGS trên 5.26): đặt giá trị để giao dịch treo không giữ khoá mãi.