행 수준 잠금 전략
동시 쓰기를 최적화하도록 행 수준 잠금을 관리하는 고급 전략을 살펴봅니다.
행 수준 잠금 전략은(는) CoddyKit의 무료 PostgreSQL Performance & Query Optimization 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 PostgreSQL Performance & Query Optimization 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. PostgreSQL Performance & Query Optimization 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Why Row-Level Locking?
When multiple users or processes try to change the same data at the same time, databases need a way to prevent conflicts and ensure data integrity. This is where row-level locking comes in.
A row-level lock allows a transaction to claim exclusive or shared access to specific rows, preventing other transactions from making conflicting changes until the lock is released. It's crucial for high-concurrency applications.
Implicit Row Locks
PostgreSQL automatically applies row-level locks during Data Manipulation Language (DML) operations like INSERT, UPDATE, and DELETE.
INSERT: Places an exclusive lock on the newly inserted row.UPDATE: Places an exclusive lock on the row being modified.DELETE: Places an exclusive lock on the row being deleted.
These implicit locks ensure that only one transaction can modify a specific row at a time.
Explicit Locks: FOR UPDATE
Sometimes you need to lock rows before modifying them, especially when your application logic involves reading data, making decisions, and then updating. This is where SELECT ... FOR UPDATE is invaluable.
It acquires an exclusive lock on the selected rows, preventing other transactions from updating or deleting them until your transaction commits or rolls back.
FOR UPDATE in Action
Try this example. If you run SELECT ... FOR UPDATE in one database session, then try to UPDATE the same row from another session, the second session will wait.
Session 1:
BEGIN;
SELECT * FROM products WHERE product_id = 1 FOR UPDATE;
-- Do some work...
-- UPDATE products SET stock = stock - 1 WHERE product_id = 1;
-- ROLLBACK; OR COMMIT;FOR UPDATE: What Happens
The previous code snippet shows how FOR UPDATE works. If you ran the SELECT in Session 1, then immediately tried to run this UPDATE in a different Session 2, Session 2 would wait until Session 1 either COMMITs or ROLLBACKs.
Session 2 (will wait):
UPDATE products SET price = 10.99 WHERE product_id = 1;Explicit Locks: FOR SHARE
What if you want to prevent updates, but allow other transactions to read the data or even acquire their own shared lock?
SELECT ... FOR SHARE acquires a shared lock. This means:
- Other transactions can read the rows.
- Other transactions can acquire their own
FOR SHARElocks. - Other transactions cannot acquire
FOR UPDATElocks or modify the rows.
FOR SHARE in Action
If Session 1 holds a FOR SHARE lock, Session 2 can also acquire a FOR SHARE lock, but a FOR UPDATE or DML operation on the same row will wait.
Session 1:
BEGIN;
SELECT * FROM orders WHERE order_id = 101 FOR SHARE;
-- Do some calculations...
-- COMMIT; OR ROLLBACK;More Granular Locks: FOR NO KEY UPDATE
SELECT ... FOR NO KEY UPDATE is similar to FOR UPDATE but is weaker. It acquires an exclusive lock that doesn't block FOR KEY SHARE locks.
It's useful when you're updating non-key columns and don't need to prevent concurrent foreign key operations, which are typically very short-lived.
Shared Read Locks: FOR KEY SHARE
SELECT ... FOR KEY SHARE is the weakest explicit row-level lock. It allows other transactions to acquire FOR SHARE, FOR NO KEY UPDATE, and even other FOR KEY SHARE locks.
It primarily prevents other transactions from deleting the locked rows or acquiring an exclusive lock that would modify key columns. It's often used by foreign key constraints.
Locking Order Strategy
A critical strategy to prevent deadlocks (where two transactions wait for each other indefinitely) is to always acquire locks on multiple rows in a consistent order.
For example, if you need to lock rows with product_id = 5 and product_id = 10, always lock 5 first, then 10 across all transactions. This prevents a scenario where one transaction locks 5 then tries for 10, while another locks 10 then tries for 5.
Quick Check: Row Locks
Consider two concurrent transactions. Transaction A runs SELECT * FROM users WHERE user_id = 1 FOR UPDATE;. What happens if Transaction B immediately tries to run UPDATE users SET email = 'new@example.com' WHERE user_id = 1;?
Recap: Row-Level Locks
We've explored how PostgreSQL manages concurrency with row-level locks:
- Implicit locks protect DML operations.
FOR UPDATEprovides exclusive row locks for modifications.FOR SHAREprovides shared locks, allowing reads but blocking updates.FOR NO KEY UPDATEandFOR KEY SHAREoffer more granular control.- Consistently ordering lock acquisition is a key strategy to prevent deadlocks.
Mastering these strategies ensures your application handles concurrent writes efficiently and reliably!
자주 묻는 질문
“행 수준 잠금 전략” 강의는 무료인가요?
네 — “행 수준 잠금 전략” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 PostgreSQL Performance & Query Optimization 강의 전체를 잠금 해제할 수 있습니다. PostgreSQL Performance & Query Optimization 강의에는 총 4개의 강의가 포함되어 있습니다.
“행 수준 잠금 전략”에서 뭘 배우나요?
동시 쓰기를 최적화하도록 행 수준 잠금을 관리하는 고급 전략을 살펴봅니다. 브라우저에서 직접 실행하는 실습 코드로 PostgreSQL Performance & Query Optimization을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
PostgreSQL Performance & Query Optimization을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 PostgreSQL Performance & Query Optimization은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“행 수준 잠금 전략” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 PostgreSQL Performance & Query Optimization 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 PostgreSQL Performance & Query Optimization 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.