What Is a Transaction?

Learn to understand transactions, their working, and life cycle in IndexedDB.

A transaction in IndexedDB is a unit of work that’s performed on a database.

IndexedDB transactions work based on a commit or rollback mechanism, which ensures that all or none of the transactions are successful. This mechanism helps to ensure the consistency, completeness, and atomicity of the data present in the database.

How do transactions work?

When we start a transaction, IndexedDB locks the database to prevent other transactions from accessing it. This ensures that the data in the database isn’t changed while the transaction is in progress. Once the transaction is complete, IndexedDB unlocks the database and allows other transactions to access it.

We should use transactions in IndexedDB whenever we need to perform operations that must be executed as a single unit of work to maintain the integrity and consistency of the data within the database.

Modes of transactions

The transaction can have three modes:

  • readonly: In this mode, we can only read data. Multiple read-only transactions can access the same object store concurrently because reading from the object store doesn’t alter the data.

  • readwrite: In this mode, we can read and write data to the object store. Only one transaction can be performed on a specific object store at a time.

  • versionchange: In this mode, we can create, delete, or update the object store. We can’t create this event manually. This event will be fired automatically on opening the database for the upgradeneeded handler.

Transaction life cycle

In IndexedDB, the transaction life cycle goes through four distinct stages:

  1. Creation: This is where the developer creates a transaction using the database connection.

  2. Object store access: After creating a transaction, the user then accesses the necessary object stores and indexes to perform the required data operation.

  3. Data processing: In this stage, the user carries out the required data operation using one of the read-write functions, like add(), put(), and delete().

  4. Completion: After carrying out the data operation, the user commits the transaction, and the changes are made to the object store.

Conclusion

Transactions ensure that all of the operations in a unit of work are performed atomically; either all succeed or all fail. This is important for maintaining the integrity of the database.

Here are some additional things to keep in mind about transactions in IndexedDB:

  1. Transactions can be nested. This means that we can start a transaction within another transaction.

  2. Transactions can be aborted. This means that we can cancel a transaction before it’s complete.

  3. Transactions can be timed out. This means that the transaction will automatically be aborted if it takes too long to complete.

Get hands-on with 1400+ tech skills courses.