DEV Community

Varun Sagar
Varun Sagar

Posted on

Transactions in DB

A transaction is a single unit of work.which can be broken down into multiple steps. For example a user adding an item to a cart.
step 1: update the item for the user in cart object
step 2: update the cost of the item
In the above example, step 1 and step 2 are tightly coupled and system goes to inconsistent state if one happens and other one fails, thus it is necessary for the transaction to be in its complete state but not be in a partial state.

we also have the concept of rollbacks in all OLTP databases. if step1 succeeds and step2 fails, database rollbacks step1 and shows the failure state to the client.

General theme here is not to have any partial states.

Another example is, when we receive a new email,
step 1: we need to add a new email to feed
step 2: Increment unread message count
these two steps have either succeed/fail but not be in partially committed state

Transactions show these 4 properties ACID :

Atomicity : Ensures no partial states in a transaction
Consistency : Ensures system is always in consistent states even if there are multiple transactions happening on single row/single DB by having locks(these could be range locking ,row/column level locking ideally)
Isolation : Ensures no two transactions interfere each other ( No phantom reads/dirty reads)
Durable : Ensures any transaction that happened will persist.( Might maintain a log and replay it incase of any server failures)

There is another alternative to acid is base kind DBs:

Basically Available : Ensures high availability of DBs
Soft-state : There would be partial states in DBs( but there will be eventual consistency)
Eventual consistency : Consistency is guaranteed but it is delayed

Top comments (0)