Locks in PostgreSQL Part 1
Tags: postgres, postgressql, apacheage
Published: 2023-08-09 12:55:17

In the world of databases, where information swirls like a busy marketplace, imagine locks as friendly guides, making sure everyone gets their turn. Let's delve into the fascinating realm of locks in PostgreSQL – these are like invisible protectors that help keep your data safe and orderly.

Think of locks as bouncers at a club – they ensure only one person (or transaction) interacts with data at a time. Some locks, like "shared locks," allow multiple people to look at data together, while others, like "exclusive locks," let only one person make changes.

But sometimes, like in a game of musical chairs, transactions can get stuck, waiting for each other. No worries! PostgreSQL steps in with its magic detective skills to untangle these situations and keep things moving.

Picture locks as different tools in a toolbox – you've got locks for whole tables, smaller locks for rows, and even special "advisory locks" for tasks that need a temporary hold. Each tool has a job to do, helping the database handle many things at once, like a juggling act.

**We will discuss different types of locks, providing an explanation for each one:**

**1.Table-Level Locks:**
Remember that all of these lock modes are table-level locks, even if the name contains the word “row”, the names of the lock modes are historical. 
**1.1.Access Share (AccessShareLock):**
Imagine an online forum where users can view various posts and comments simultaneously. In this scenario, the `AccessShareLock `can be utilized to ensure smooth and concurrent reading access to the forum's content while maintaining data consistency.
**Capabilities of AccessShareLock:**

**Concurrent Reading**: Multiple users can access and read forum posts and comments simultaneously. This is particularly useful for read-heavy operations, where users can freely explore the content without blocking each other.

**No Modification**: Transactions holding an `AccessShareLock `cannot modify the data they are reading. This ensures that while users are browsing the forum, their actions won't interfere with one another or disrupt the content being displayed.

**imitations of AccessShareLock:**

**No Write Access:** Transactions with an AccessShareLock cannot make any modifications to the forum content. They are restricted to read-only operations, making it unsuitable for scenarios where data needs to be updated, added, or deleted.

**Conflict with Write Locks:** While `AccessShareLock `doesn't conflict with other shared locks, it does conflict with higher-level locks like `ExclusiveLock`. This means that if another transaction holds an `ExclusiveLock`, it will prevent transactions with `AccessShareLock `from proceeding until the exclusive lock is released.

In our online forum example, the `AccessShareLock `enables users to explore posts and comments without any risk of data modifications or disruptions. However, it does not allow them to participate actively, such as posting new content or commenting, as these actions involve modifications and would require a different type of lock, like `ExclusiveLock`.

**1.2.Row Share (RowShareLock):**
Imagine a university course enrollment system, students are actively exploring course offerings, checking details, and making enrollment decisions during the registration period. While the `RowShareLock `is a suitable choice for this scenario, the `AccessShareLock `doesn't suit it for the following reasons:

**Reasons the Use Case Doesn't Suit AccessShareLock:**

**Limited Modifications:**
Students not only need to read course details but may also need to make modifications by enrolling in courses. The `AccessShareLock `is intended for read-only access and does not permit any modifications. In this use case, students must be allowed to interact with the system beyond just reading.

**Exclusive Access Requirement:**
During course exploration and enrollment, it's crucial to ensure that while a student is interacting with a course, no other transaction can modify its details. The `AccessShareLock `does not provide the required level of exclusivity to prevent concurrent modifications by other transactions.

**Concurrency and Modifications:**
The use case requires a balance between concurrent reading and controlled modifications. The `RowShareLock `allows multiple students to concurrently read course details while ensuring that any modifications are protected against conflicts. The `AccessShareLock `is geared more toward scenarios where read-only access is sufficient and doesn't offer the same level of concurrency with controlled modifications.

In this university course enrollment scenario, where students need to explore and potentially modify course details, the `RowShareLock `is a more appropriate choice than the `AccessShareLock`. It strikes a better balance between allowing concurrent reading and managing controlled modifications, making it a more suitable fit for the use case.

**1.3.Row Exclusive (RowExclusiveLock):**
Let's take this use case.

**Use Case: Online Auction Bidding System**
In an online auction bidding system, participants engage in competitive bidding for various items. To ensure fair and orderly bid placement while preventing concurrent modifications, the `RowExclusiveLock `is the appropriate choice. However, both `RowShareLock `and `AccessShareLock `are not suitable due to the specific requirements of the use case.

**Why RowExclusiveLock is Appropriate:**

**Controlled Bid Placement:**
In an online auction, participants place bids on specific items. The `RowExclusiveLock `can be applied to the row representing the item being bid on. This lock ensures that only one participant can place a bid at a time, preventing conflicts and ensuring that the bid placement process remains orderly.

**Exclusive Access During Bidding:**
During the bid placement process, it's essential to provide exclusive access to the item's details to the participant who is currently placing a bid. The `RowExclusiveLock `guarantees that no other transactions, including those attempting to read or modify the same item, can interfere with the active bidding process.

**Conflict Prevention:**
Since the `RowExclusiveLock `prohibits other transactions from acquiring any other type of lock on the same row, it ensures that no other participants can simultaneously bid on the same item, thus preventing contention and data inconsistencies.

**Why RowShareLock and AccessShareLock are Unsuitable:**

`AccessShareLock `only permits read operations. Since bid placement involves modifying the bidding item's data.

the `RowShareLock `can indeed be used to modify data. However, it's important to clarify that the `RowShareLock `allows concurrent access for reading and modification by multiple transactions. It ensures that multiple transactions can read and modify the same resource simultaneously without conflicts.
In the context of the online auction bidding system use case, where controlled and exclusive access is required during bid placement, using the `RowShareLock `might not be ideal. This is because the `RowShareLock `allows multiple transactions to modify the same resource concurrently, which could lead to race conditions and inconsistent bid placement.

> There are other types of locks that we will explain at another time.
 
**REF:**
[PostgreSQL Documentation](https://www.postgresql.org/docs/current/explicit-locking.html)