Files
llm-wiki/raw/official-docs/lock-postgres-advisory-locks.md

11 KiB

title, source_type, url, archive_url, related_branches, related_projects, tags, created
title source_type url archive_url related_branches related_projects tags created
PostgreSQL Advisory Locks — §13.3.5 Explicit Locking + §9.28.10 Advisory Lock Functions official-doc https://www.postgresql.org/docs/current/explicit-locking.html
feature-distributed-lock-contract
ca-skeleton-operational-contract
official-doc
ca-skeleton
persistence
postgresql
advisory-lock
distributed-lock
2026-06-12

PostgreSQL Advisory Locks — §13.3.5 Explicit Locking + §9.28.10 Advisory Lock Functions

Layer: raw/ — 외부 자료(공식 문서)의 원문 발췌·출처 기록. 검증된 요약은 /ingestwiki/concepts/source-summary-template 형식으로 별도 작성. 원본은 raw에 영구 보관.

Parent / 활용 branch (필수, 최소 1개+)

Branch 이 자료가 정당화하는 결정
raw/branch-notes/feature-distributed-lock-contract ca-tmpl distributedLockProvider 의 default 메커니즘으로 PostgreSQL advisory lock 을 검토 — 특히 session-level vs transaction-level (pg_advisory_xact_lock, commit/rollback 시 자동 해제) 차이가 "lock 해제 vs DB commit 순서 정합" 결정(트랜잭션 commit 정합)의 1차 근거

출처 / Source

왜 저장했는지 / Why archived

PostgreSQL advisory lock 의 session-level vs transaction-level 해제 시맨틱이 distributedLockProvider 구현 결정의 1차 공식 근거이기 때문에 보관한다. 특히 transaction-level lock 이 commit/rollback 에 자동 연동되어 "DB 트랜잭션 commit 시 lock 해제 보장"을 만족시킬 수 있는지 확인하기 위한 자료다.

핵심 인용 / Key quotes (verbatim, 5문장)

[§13.3.5] "Advisory locks can be useful for locking strategies that are an awkward fit for the MVCC model. For example, a common use of advisory locks is to emulate pessimistic locking strategies typical of so-called "flat file" data management systems. While a flag stored in a table could be used for the same purpose, advisory locks are faster, avoid table bloat, and are automatically cleaned up by the server at the end of the session."

[§13.3.5] "Unlike standard lock requests, session-level advisory lock requests do not honor transaction semantics: a lock acquired during a transaction that is later rolled back will still be held following the rollback, and likewise an unlock is effective even if the calling transaction fails later."

[§13.3.5] "Transaction-level lock requests, on the other hand, behave more like regular lock requests: they are automatically released at the end of the transaction, and there is no explicit unlock operation. This behavior is often more convenient than the session-level behavior for short-term usage of an advisory lock."

[§9.28.10] "pg_try_advisory_lock(key bigint) — Obtains exclusive session-level lock if available immediately; returns true or false"

[§13.3.5 — LIMIT 주의] "the second form is dangerous because the LIMIT is not guaranteed to be applied before the locking function is executed. This might cause some locks to be acquired that the application was not expecting, and hence would fail to release (until it ends the session). From the point of view of the application, such locks would be dangling, although still viewable in pg_locks."

Claims Extracted / 추출된 주장

Claim ID Claim (이 자료가 직접 말하는 것) Evidence quote Strength Applies to Does not prove
PG-ADV-C1 Advisory lock 은 MVCC 모델에 맞지 않는 locking 전략에 유용하며, table 에 flag 를 저장하는 방식보다 빠르고 table bloat 이 없고 세션 종료 시 자동 정리된다 [§13.3.5] "advisory locks are faster, avoid table bloat, and are automatically cleaned up by the server at the end of the session" official-vendor-doc PostgreSQL 에서 application-defined 잠금이 필요한 모든 경우 특정 언어/드라이버에서의 동작 구현 방법; 분산 환경에서의 보장 범위
PG-ADV-C2 Session-level advisory lock 은 트랜잭션 시맨틱을 따르지 않는다 — 트랜잭션 롤백 후에도 lock 이 유지되고, unlock 은 호출 트랜잭션이 나중에 실패해도 유효하다 [§13.3.5] "session-level advisory lock requests do not honor transaction semantics: a lock acquired during a transaction that is later rolled back will still be held following the rollback, and likewise an unlock is effective even if the calling transaction fails later" official-vendor-doc PostgreSQL session-level advisory lock 을 사용하는 모든 코드 "session-level lock = 안전하지 않다"는 뜻이 아님; connection pool 환경의 위험은 별도 추론 필요
PG-ADV-C3 Transaction-level advisory lock 은 트랜잭션 종료 시 자동 해제되며 명시적 unlock 연산이 없다 [§13.3.5] "Transaction-level lock requests, on the other hand, behave more like regular lock requests: they are automatically released at the end of the transaction, and there is no explicit unlock operation" official-vendor-doc PostgreSQL transaction-level advisory lock (pg_advisory_xact_lock 계열) 트랜잭션 외부 컨텍스트(non-transactional 코드)에서의 동작; Spring @Transactional 과의 실제 정합은 별도 검증 필요
PG-ADV-C4 pg_try_advisory_lock 계열은 즉시 획득 가능 여부를 true/false 로 반환하는 non-blocking 변형이다 [§9.28.10] "pg_try_advisory_lock(key bigint) — Obtains exclusive session-level lock if available immediately; returns true or false" official-reference Non-blocking lock acquisition 이 필요한 모든 경우 try variant 가 항상 transaction-level 보장을 제공한다는 뜻이 아님 (pg_try_advisory_xact_lock 은 별개 함수)
PG-ADV-C5 LIMIT 절을 포함한 쿼리에서 advisory lock 함수를 직접 호출하면 LIMIT 이 locking 함수보다 먼저 적용된다는 보장이 없으므로 예상치 않은 lock 이 획득될 수 있고, 세션 종료 전까지 해제되지 않는 dangling lock 이 발생할 수 있다 [§13.3.5] "the second form is dangerous because the LIMIT is not guaranteed to be applied before the locking function is executed. This might cause some locks to be acquired that the application was not expecting, and hence would fail to release (until it ends the session). From the point of view of the application, such locks would be dangling, although still viewable in pg_locks" official-vendor-doc LIMIT 이 포함된 SELECT 에서 advisory lock 함수를 사용하는 모든 쿼리 LIMIT 없는 단순 키 기반 pg_advisory_lock(key) 호출에는 해당 없음

Strength 허용값 (이 파일에서 사용한 값)

  • official-vendor-doc — PostgreSQL 공식 벤더 문서
  • official-reference — PostgreSQL 공식 함수 레퍼런스

Usage Boundaries / 적용 경계

  • 이 자료가 직접 증명하는 것:
    • PG-ADV-C1: Advisory lock 이 flag-in-table 보다 빠르고 bloat 없음 (PostgreSQL 공식 서술)
    • PG-ADV-C2: Session-level lock 이 rollback 에 영향받지 않음 (PostgreSQL 공식 서술)
    • PG-ADV-C3: Transaction-level lock 이 트랜잭션 종료 시 자동 해제됨 (PostgreSQL 공식 서술)
    • PG-ADV-C4: Non-blocking try 변형이 존재하고 boolean 반환 (PostgreSQL 공식 레퍼런스)
    • PG-ADV-C5: LIMIT 포함 쿼리에서 dangling lock 위험 존재 (PostgreSQL 공식 경고)
  • 이 자료가 증명하지 않는 것:
    • Connection pool (HikariCP 등) 환경에서 session-level lock 이 실제로 어떻게 동작하는지 (session 재사용 시 이전 lock 잔류 위험은 공식 문서에 직접 언급 없음 — 별도 추론 필요)
    • Spring @Transactionalpg_advisory_xact_lock 의 실제 커밋/롤백 정합이 ca-tmpl 구현에서 동작하는지 (별도 locally-verified 검증 필요)
    • ca-tmpl 의 distributedLockProvider 가 advisory lock 으로 구현되어야 한다는 결정 자체 (그 결정은 branch-note 가 내리고 이 문서는 그 근거 중 하나)
    • Redis, Zookeeper 등 다른 distributed lock 메커니즘 대비 advisory lock 의 우위 (비교 분석은 별도 자료 필요)
  • 내 프로젝트에 적용하려면 추가 확인이 필요한 것:
    • PG-ADV-C3 + Spring @Transactional: pg_advisory_xact_lock 이 Spring 트랜잭션 커밋 시점과 실제로 정합하는지 로컬 검증
    • Connection pool 재사용 시나리오에서 session-level lock 누수 여부 확인

보조 출처 요약 / Supplementary Source (§9.28.10)

출처: https://www.postgresql.org/docs/current/functions-admin.html §9.28.10 Advisory Lock Functions

주요 함수 분류 (원문 기반):

함수 레벨 Blocking 반환
pg_advisory_lock(key bigint) session blocking void
pg_advisory_xact_lock(key bigint) transaction blocking void
pg_try_advisory_lock(key bigint) session non-blocking boolean
pg_try_advisory_xact_lock(key bigint) transaction non-blocking boolean
pg_advisory_unlock(key bigint) session boolean
pg_advisory_unlock_all() session void

추가 사항 (원문 기반): "Multiple session-level lock requests on the same resource stack; three lock requests require three unlock requests for complete release" — session-level lock 은 스택 방식으로 카운팅됨 (reentrancy 시 unlock 횟수 일치 필요).

메모 / Notes

  • pg_advisory_xact_lock 은 Spring @Transactional 과 결합할 때 트랜잭션 commit/rollback 과 함께 자동 해제된다는 점이 ca-tmpl distributedLockProvider 의 핵심 선택 근거 후보 (PG-ADV-C3 기반, 실제 동작은 locally-verified 필요).
  • Session-level lock 은 connection pool 환경에서 같은 커넥션이 재사용되면 이전 lock 이 남아있을 수 있음 — 이 위험은 공식 문서에 직접 언급은 없으나 PG-ADV-C2 ("held until explicitly released or the session ends") 에서 추론 가능. 추론이므로 메모에만 기록.
  • Lock 획득 가능 개수 상한: max_locks_per_transaction * max_connections 에 의존 (공식 문서 서술 있음).
  • 추가로 봐야 할 동일 출처 페이지: pg_locks 시스템 뷰 (현재 advisory lock 목록 조회).
  • 이 자료를 인용한 branch: raw/branch-notes/feature-distributed-lock-contract
  • 같은 주제 참고 자료: (Redis SETNX / Redisson 관련 자료 추가 시 여기 연결)
  • 검증된 요약 생성 시: [[wiki/concepts/advisory-lock-postgresql]] (생성 전)