🗄️ Databases

Transaction

Transaction

A logical unit of work. ACID properties. Commit/Rollback.

📖 Detailed Explanation

What Is a Transaction?

A transaction is a single logical unit of work that changes the state of a database. It has the "All or Nothing" property: multiple operations must either all succeed or all fail. It is essential for tasks where data integrity matters, such as bank transfers and order processing.

ACID Properties

  • Atomicity: All operations within a transaction are performed completely, or none are performed at all
  • Consistency: The database remains in a consistent state before and after the transaction
  • Isolation: Concurrently executing transactions do not affect each other
  • Durability: The results of a committed transaction are permanently reflected

Transaction Isolation Levels

  • READ UNCOMMITTED: Uncommitted data can be read (Dirty Read occurs)
  • READ COMMITTED: Only committed data is read (Non-Repeatable Read occurs)
  • REPEATABLE READ: Re-reading the same data within a transaction yields the same result (Phantom Read may occur)
  • SERIALIZABLE: Complete isolation, equivalent to sequential execution (performance degradation)

Concurrency Problems

  • Dirty Read: Reads uncommitted data of another transaction
  • Non-Repeatable Read: The same query returns different results (modified by another transaction)
  • Phantom Read: The results of a range query change (rows inserted/deleted by another transaction)
  • Lost Update: Two transactions modify the same data, and one update is lost

Distributed Transactions

  • 2PC (Two-Phase Commit): Guarantees atomicity across distributed nodes through the Prepare → Commit phases
  • Saga Pattern: Local transactions of each service + compensating transactions, achieving Eventual Consistency
  • TCC (Try-Confirm-Cancel): Reserve resources, then confirm/cancel

💻 Code Example

Basic SQL Transaction

SQL
-- 계좌 이체 트랜잭션
BEGIN TRANSACTION;

-- 출금 계좌에서 차감
UPDATE accounts
SET balance = balance - 100000
WHERE account_id = 'A001' AND balance >= 100000;

-- 영향받은 행이 0이면 잔액 부족
-- 입금 계좌에 추가
UPDATE accounts
SET balance = balance + 100000
WHERE account_id = 'A002';

-- 이체 내역 기록
INSERT INTO transfer_log (from_account, to_account, amount, created_at)
VALUES ('A001', 'A002', 100000, NOW());

-- 모든 작업 성공 시 커밋
COMMIT;

-- 실패 시 롤백
-- ROLLBACK;

Python (psycopg2) Transaction

Python
import psycopg2
from psycopg2 import sql

def transfer_money(from_account, to_account, amount):
    conn = psycopg2.connect(database="bank")
    try:
        with conn:
            with conn.cursor() as cur:
                # 출금 계좌 확인 및 차감 (FOR UPDATE로 행 잠금)
                cur.execute("""
                    SELECT balance FROM accounts
                    WHERE account_id = %s
                    FOR UPDATE
                """, (from_account,))

                balance = cur.fetchone()[0]
                if balance < amount:
                    raise ValueError("잔액 부족")

                # 출금
                cur.execute("""
                    UPDATE accounts SET balance = balance - %s
                    WHERE account_id = %s
                """, (amount, from_account))

                # 입금
                cur.execute("""
                    UPDATE accounts SET balance = balance + %s
                    WHERE account_id = %s
                """, (amount, to_account))

                # 로그 기록
                cur.execute("""
                    INSERT INTO transfer_log (from_acc, to_acc, amount)
                    VALUES (%s, %s, %s)
                """, (from_account, to_account, amount))

        # with 블록 종료 시 자동 COMMIT
        print("이체 완료")

    except Exception as e:
        # 예외 발생 시 자동 ROLLBACK
        print(f"이체 실패: {e}")
        raise

    finally:
        conn.close()

SQLAlchemy Transaction

Python
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine('postgresql://localhost/bank')
Session = sessionmaker(bind=engine)

def process_order(user_id, product_id, quantity):
    session = Session()
    try:
        # 재고 확인 및 감소
        product = session.query(Product).filter_by(id=product_id).with_for_update().one()

        if product.stock < quantity:
            raise ValueError("재고 부족")

        product.stock -= quantity

        # 주문 생성
        order = Order(
            user_id=user_id,
            product_id=product_id,
            quantity=quantity,
            total_price=product.price * quantity
        )
        session.add(order)

        # 결제 처리
        payment = Payment(order=order, status='completed')
        session.add(payment)

        session.commit()
        return order.id

    except Exception as e:
        session.rollback()
        raise

    finally:
        session.close()

Setting the Isolation Level

SQL
-- 세션 격리 수준 설정
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;

-- 트랜잭션별 설정
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;

-- PostgreSQL: 현재 격리 수준 확인
SHOW transaction_isolation;

-- MySQL: 격리 수준 확인
SELECT @@transaction_isolation;

Saga Pattern Example (Compensating Transaction)

Python
class OrderSaga:
    def __init__(self):
        self.compensations = []

    def execute(self, order_data):
        try:
            # Step 1: 재고 예약
            self.reserve_stock(order_data)
            self.compensations.append(lambda: self.release_stock(order_data))

            # Step 2: 결제 처리
            self.process_payment(order_data)
            self.compensations.append(lambda: self.refund_payment(order_data))

            # Step 3: 배송 요청
            self.request_shipping(order_data)
            self.compensations.append(lambda: self.cancel_shipping(order_data))

            # 모든 단계 성공
            return {"status": "success"}

        except Exception as e:
            # 실패 시 보상 트랜잭션 역순 실행
            for compensation in reversed(self.compensations):
                try:
                    compensation()
                except Exception as comp_error:
                    log.error(f"보상 실패: {comp_error}")

            raise SagaFailedException(str(e))

💬 Real-world conversation examples

Junior Developer
"Is it okay to call an external API inside a transaction? I'm planning to call the payment API first and then save to the DB."
Senior developer
"Absolutely not. Keep transactions as short as possible. Call the external API outside the transaction, and start the DB work depending on the result. If a timeout occurs during the transaction, locks are held for a long time and the entire system can freeze."
Backend developer
"When orders for the same product come in at the same time, there's a bug where the stock goes negative."
DBA
"That's a Race Condition. Lock the row with SELECT FOR UPDATE when reading the stock. Or add a WHERE stock >= quantity condition to the UPDATE statement to handle it atomically."
Architect
"How do you handle transactions that span multiple services in MSA? I heard 2PC is slow..."
Senior Architect
"2PC is a bottleneck in distributed environments. It's common to use the Saga pattern, with a local transaction in each service + compensation logic, to go with Eventual Consistency. And coordinate it in an event-driven way."

⚠️ Cautions

⚠️ Keep Transactions Short
Locks are held during a transaction. If they are held for a long time, other transactions have to wait, which degrades performance and increases the risk of deadlocks. Handle external API calls and complex calculations outside the transaction.
⚠️ Deadlock Prevention
When locking multiple tables/rows, always lock them in the same order. If a transaction that locks in A→B order and a transaction in B→A order run at the same time, a deadlock occurs. Setting a timeout is also essential.
⚠️ Choosing an Isolation Level
Higher isolation levels guarantee data consistency but reduce concurrency. In most cases READ COMMITTED is adequate, and only consider SERIALIZABLE where consistency is important, such as in finance.
⚠️ Limits of Distributed Transactions
Strong ACID is hard to achieve in microservices. It is important to use Eventually Consistent patterns such as Saga and TCC, and to design to guarantee idempotency.

🔗 Related Terms

📚 Learn More