ACID
Atomicity, Consistency, Isolation, Durability
The four core properties of database transactions. Atomicity, Consistency, Isolation, and Durability guarantee data integrity and reliability.
Atomicity, Consistency, Isolation, Durability
The four core properties of database transactions. Atomicity, Consistency, Isolation, and Durability guarantee data integrity and reliability.
Atomicity is the "All or Nothing" principle. Either all operations in a transaction complete, or if even one fails, the entire transaction is canceled (rolled back). For example, in a bank transfer, if the withdrawal succeeds but the deposit fails, the withdrawal is also canceled, preventing the money from disappearing.
Consistency means the database must remain in a consistent state before and after a transaction. All constraints (Primary Key, Foreign Key, Check, etc.) must be satisfied, and business rules (e.g., a balance cannot be negative) must also be upheld.
Isolation ensures that concurrently running transactions do not affect one another. Isolation levels include Read Uncommitted, Read Committed, Repeatable Read, and Serializable; the higher the isolation level, the lower the concurrency but the higher the data integrity.
Durability guarantees that once a transaction is committed, its result is permanently preserved even if a system failure occurs. It is implemented with techniques such as WAL (Write-Ahead Logging) and checkpoints, and forms the basis of data recovery.
Relational databases (PostgreSQL, MySQL, Oracle) fully support ACID. By contrast, some NoSQL databases relax parts of ACID for performance and scalability and adopt BASE (Basically Available, Soft state, Eventually consistent).
# ACID 트랜잭션 예제 - Python + PostgreSQL
import psycopg2
from psycopg2 import sql
from decimal import Decimal
class BankService:
"""계좌 이체 서비스 - ACID 보장"""
def __init__(self, connection_string: str):
self.conn_string = connection_string
def transfer(self, from_account: str, to_account: str, amount: Decimal) -> bool:
"""
계좌 이체 - 원자성(Atomicity) 보장
출금과 입금이 모두 성공하거나, 모두 롤백됨
"""
conn = psycopg2.connect(self.conn_string)
try:
# autocommit=False가 기본값 (트랜잭션 시작)
with conn.cursor() as cur:
# 1. 출금 계좌 잔액 확인 (일관성 체크)
cur.execute(
"SELECT balance FROM accounts WHERE id = %s FOR UPDATE",
(from_account,)
)
result = cur.fetchone()
if not result:
raise ValueError(f"계좌 {from_account}가 존재하지 않습니다")
balance = result[0]
if balance < amount:
raise ValueError("잔액이 부족합니다")
# 2. 출금 (잔액 차감)
cur.execute(
"UPDATE accounts SET balance = balance - %s WHERE id = %s",
(amount, from_account)
)
# 3. 입금 (잔액 증가)
cur.execute(
"UPDATE accounts SET balance = balance + %s WHERE id = %s",
(amount, to_account)
)
# 4. 이체 기록 저장
cur.execute(
"""INSERT INTO transfers (from_account, to_account, amount, created_at)
VALUES (%s, %s, %s, NOW())""",
(from_account, to_account, amount)
)
# 모든 작업 성공 시 커밋 (지속성 보장)
conn.commit()
print(f"✅ 이체 완료: {from_account} → {to_account}, {amount}원")
return True
except Exception as e:
# 오류 발생 시 롤백 (원자성 보장)
conn.rollback()
print(f"❌ 이체 실패, 롤백됨: {e}")
return False
finally:
conn.close()
# 격리 수준 설정 예제
def set_isolation_level(conn, level: str):
"""
격리 수준 설정
- READ UNCOMMITTED: Dirty Read 허용 (거의 사용 안함)
- READ COMMITTED: PostgreSQL 기본값
- REPEATABLE READ: 반복 읽기 보장
- SERIALIZABLE: 완벽한 격리, 낮은 동시성
"""
isolation_levels = {
'read_committed': psycopg2.extensions.ISOLATION_LEVEL_READ_COMMITTED,
'repeatable_read': psycopg2.extensions.ISOLATION_LEVEL_REPEATABLE_READ,
'serializable': psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE,
}
conn.set_isolation_level(isolation_levels.get(level, 1))
# 사용 예시
if __name__ == "__main__":
bank = BankService("postgresql://localhost/bank")
# ACID가 보장되는 이체
bank.transfer("ACC001", "ACC002", Decimal("50000"))
// ACID 트랜잭션 예제 - Node.js + PostgreSQL
const { Pool } = require('pg');
class BankService {
constructor(connectionString) {
this.pool = new Pool({ connectionString });
}
/**
* 계좌 이체 - ACID 보장
* @param {string} fromAccount - 출금 계좌
* @param {string} toAccount - 입금 계좌
* @param {number} amount - 이체 금액
*/
async transfer(fromAccount, toAccount, amount) {
const client = await this.pool.connect();
try {
// 트랜잭션 시작
await client.query('BEGIN');
// 1. 출금 계좌 잔액 확인 (FOR UPDATE로 락)
const { rows } = await client.query(
'SELECT balance FROM accounts WHERE id = $1 FOR UPDATE',
[fromAccount]
);
if (rows.length === 0) {
throw new Error(`계좌 ${fromAccount}가 존재하지 않습니다`);
}
const balance = parseFloat(rows[0].balance);
if (balance < amount) {
throw new Error('잔액이 부족합니다');
}
// 2. 출금
await client.query(
'UPDATE accounts SET balance = balance - $1 WHERE id = $2',
[amount, fromAccount]
);
// 3. 입금
await client.query(
'UPDATE accounts SET balance = balance + $1 WHERE id = $2',
[amount, toAccount]
);
// 4. 이체 기록
await client.query(
`INSERT INTO transfers (from_account, to_account, amount, created_at)
VALUES ($1, $2, $3, NOW())`,
[fromAccount, toAccount, amount]
);
// 커밋 - 지속성(Durability) 보장
await client.query('COMMIT');
console.log(`✅ 이체 완료: ${fromAccount} → ${toAccount}, ${amount}원`);
return true;
} catch (error) {
// 롤백 - 원자성(Atomicity) 보장
await client.query('ROLLBACK');
console.error(`❌ 이체 실패, 롤백됨: ${error.message}`);
return false;
} finally {
client.release();
}
}
/**
* 격리 수준 설정
*/
async withIsolationLevel(level, callback) {
const client = await this.pool.connect();
try {
// 격리 수준 설정
await client.query(`SET TRANSACTION ISOLATION LEVEL ${level}`);
await client.query('BEGIN');
const result = await callback(client);
await client.query('COMMIT');
return result;
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
}
// 사용 예시
const bank = new BankService('postgresql://localhost/bank');
// SERIALIZABLE 격리 수준으로 조회
bank.withIsolationLevel('SERIALIZABLE', async (client) => {
const { rows } = await client.query(
'SELECT SUM(balance) as total FROM accounts'
);
return rows[0].total;
});
-- ACID 속성 SQL 예제
-- ============================================
-- 1. 원자성 (Atomicity) - 트랜잭션
-- ============================================
BEGIN; -- 트랜잭션 시작
UPDATE accounts SET balance = balance - 50000
WHERE id = 'ACC001';
UPDATE accounts SET balance = balance + 50000
WHERE id = 'ACC002';
-- 둘 다 성공하면 커밋
COMMIT;
-- 실패 시 롤백
-- ROLLBACK;
-- ============================================
-- 2. 일관성 (Consistency) - 제약조건
-- ============================================
CREATE TABLE accounts (
id VARCHAR(20) PRIMARY KEY,
name VARCHAR(100) NOT NULL,
balance DECIMAL(15,2) NOT NULL DEFAULT 0,
-- 일관성 제약: 잔액은 음수 불가
CONSTRAINT positive_balance CHECK (balance >= 0)
);
-- 잔액이 부족하면 제약조건 위반으로 실패
UPDATE accounts SET balance = balance - 1000000
WHERE id = 'ACC001'; -- ERROR: check constraint 위반
-- ============================================
-- 3. 격리성 (Isolation) - 격리 수준
-- ============================================
-- 격리 수준 확인
SHOW TRANSACTION ISOLATION LEVEL;
-- 세션별 격리 수준 설정
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
-- PostgreSQL 격리 수준별 특징
-- READ COMMITTED (기본): Dirty Read 방지
-- REPEATABLE READ: Non-repeatable Read 방지
-- SERIALIZABLE: Phantom Read 방지, 완벽한 격리
-- ============================================
-- 4. 지속성 (Durability) - WAL 확인
-- ============================================
-- WAL 설정 확인 (PostgreSQL)
SHOW wal_level;
SHOW synchronous_commit;
-- fsync 설정 (데이터 디스크 동기화)
SHOW fsync;
-- ============================================
-- 락(Lock)을 이용한 격리
-- ============================================
-- 행 레벨 락 (다른 트랜잭션의 수정 방지)
SELECT * FROM accounts
WHERE id = 'ACC001'
FOR UPDATE;
-- 공유 락 (읽기는 허용, 수정 방지)
SELECT * FROM accounts
WHERE id = 'ACC001'
FOR SHARE;
-- ============================================
-- 데드락 예방
-- ============================================
-- 잠금 타임아웃 설정
SET lock_timeout = '5s';
-- 데드락 감지 시 자동 롤백됨
"Payment processing must always be wrapped in an ACID transaction. Stock deduction, order creation, and payment recording have to be processed atomically. If any one of them fails, everything must roll back, which prevents the situation where a customer was charged but no order exists."
"Raising the isolation level to SERIALIZABLE greatly reduces concurrency. In most cases READ COMMITTED is enough, so use SERIALIZABLE only for financial transactions where consistency is critical. It's best to use different isolation levels depending on the situation."
"The reason there was no data loss even though the server suddenly died is PostgreSQL's WAL. Because durability is guaranteed, committed transactions get recovered. However, if synchronous_commit is off, the last few transactions can be lost."
When a transaction runs long, locks are held for a long time and other requests have to wait. Keep transactions as short as possible and include only the necessary operations.
A deadlock occurs when two transactions wait for each other's locks. Keep the lock order consistent and set lock_timeout.
Some NoSQL databases such as MongoDB and Cassandra do not fully support ACID. If you need transactions, check the extent of their support.
Minimize transaction scope, use explicit locks with FOR UPDATE, choose an appropriate isolation level, implement retry logic, and detect long-running transactions through monitoring.