C.W.K.
Stream
Lesson 03 of 10 · published

Isolation Level

~14 min · transactions, isolation

Level 0스키마 새싹
0 XP0/86 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Isolation 이 실제 제어하는 거

Isolation level 이 트랜잭션이 다른 트랜잭션의 in-progress 작업을 어떻게 보는지 결정. 더 엄격한 isolation = 강한 보장 + 더 많은 잠재 충돌. 더 느슨한 isolation = 더 좋은 동시성 + 이상한 중간 상태 볼 가능성 더.

네 가지 표준 레벨

레벨Dirty readNon-repeatable readPhantom read
READ UNCOMMITTED가능 (PG 엔 없음)가능가능
READ COMMITTED (PG default)없음가능가능
REPEATABLE READ없음없음없음 (PG)
SERIALIZABLE없음없음없음

PostgreSQL 특이사항

PostgreSQL 에서 READ UNCOMMITTED 가 READ COMMITTED 와 동일하게 동작 — dirty read 없음. PostgreSQL 의 REPEATABLE READ 가 phantom read 방지 (실제로는 snapshot isolation). SERIALIZABLE 이 SSI 알고리즘으로 진정한 serializability 추가 — 잠재 직렬화 실패 비용으로, 앱에서 retry 해야.

Code

Isolation 명시 설정·sql
BEGIN ISOLATION LEVEL REPEATABLE READ;
-- 이 트랜잭션 모든 statement 가 일관된 snapshot 봄
SELECT * FROM accounts;
-- ... 시간 지남, 다른 트랜잭션 commit ...
SELECT * FROM accounts;  -- 첫 SELECT 와 같은 view
COMMIT;
SERIALIZABLE — retry 처리·python
def transfer_with_retry(c, from_id, to_id, amount, attempts=5):
    for i in range(attempts):
        try:
            with c.transaction(isolation_level="serializable"):
                c.execute("UPDATE accounts SET balance = balance - %s WHERE id = %s", (amount, from_id))
                c.execute("UPDATE accounts SET balance = balance + %s WHERE id = %s", (amount, to_id))
            return  # 성공
        except psycopg.errors.SerializationFailure:
            continue
    raise RuntimeError("transfer failed after %d attempts" % attempts)

External links

Exercise

psql 두 세션. A: BEGIN ISOLATION LEVEL REPEATABLE READ; 행 SELECT. B: 같은 행 UPDATE, COMMIT. A 로 돌아가: 다시 SELECT — 같은 값? A 에서: 같은 행 UPDATE 시도. 뭐 일어남?

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.