DEV Community

Aniketh Deshpande
Aniketh Deshpande

Posted on

DB Locking - Why and How?

If you have sent concurrent requests to your DB to modify its contents, you would have come across a phenomenon called The Double Booking Problem!

Double Booking Problem arises when two or more threads read the same data point and one thread incorrectly overwrites the changes done by another thread resulting in inconsistency.

  • Lets see an example to get better understanding of it.
  • Suppose its a bus booking application.
  1. User 1 and User 2, both read Seat_21 as available.
  2. User 1 books the seat. However User 2 is unaware of this as he has read Seat_21 is available.
  3. User 2 also books the seat. Now the seat info is overwritten and the seat is allotted to User 2.
  4. Due to this phenomenon of double time booking of resources, it is named as The Double Booking Problem!

Following flow diagram gives clear idea about it.

Double Booking Problem Flowchart

  • In order to avoid this, we need to use locking.

Locking in DynamoDB

Let us see how we can lock dynamodb objects.

1. Optimistic Locking

  • The spotlight feature of optimistic locking is, it does not have a lock as such. Instead a version number is attached to the record and it is incremented whenever the record is updated.

  • Multiple users are allowed to read the document or record.

  • When the users try to commit their changes, the change related to the first request is accepted as the version numbers match in the record and in the commit request.

  • Subsequent users trying to commit their changes are sent a Validation Exception!

  • Based on this, the users can sync the updated record and make their changes and retry committing the changes.

  • Therefore, the double booking problem is eliminated.

2. Pessimistic Locking

  • In pessimistic locking mechanism, Locks are implemented. The record that is being updated is locked when a user starts a transaction.
  • Since the record is locked, the other users trying to update the record are notified that the record is locked and the read also fails.
  • This mechanism although equally effective, has an overhead of implementing locks.
  • Therefore, the double booking problem is eliminated.

Thanks for reading this blog.
Aniketh Deshpande
India

Top comments (0)