Commit vs. Rollback: Database Transaction Essentials
Tags: mysql, commit, rollback, database
Published: 2024-06-25 19:25:07

In the world of databases, transactions are akin to journeys—comprising a series of steps or operations performed as a single, cohesive unit of work. Whether you're booking a flight, ordering groceries online, or transferring funds between accounts, transactions play a vital role in ensuring that database operations are reliable, consistent, and resilient. Let's take on a journey through the commit and rollback processes in database transactions, exploring each step with relatable analogies to make the journey more understandable, followed by the technical details.

## The Commit Process

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tqigcmd72esqh95mrmdx.png)

### 1. Initiating the Journey: Begin Transaction

#### Analogy:
Think of it as the moment you decide to embark on a trip. You gather your essentials and map out your route before setting off. This planning phase ensures that you're prepared for the journey ahead.

#### Technical Detail:
A transaction begins with the BEGIN TRANSACTION statement. This marks the start of a series of operations that must be executed atomically. All changes made during the transaction are initially tentative and only become permanent upon commit.


### 2. Logging the Voyage: Write-Ahead Logging (WAL)

#### Analogy:
Before setting sail, it's wise to create a list of everything you're bringing along. Similarly, the WAL records all changes made by the transaction in a log before they're applied to the database. This log serves as a safety net, allowing for recovery in case of unforeseen circumstances—much like referring back to your list if you forget something during your journey.

#### Technical Detail:
Before making any changes to the database, the system writes these changes to a write-ahead log (WAL). The WAL is a sequential record of all modifications. By logging changes before they are applied, the database can ensure durability and support recovery in case of a crash.


### 3. Planning the Itinerary: In-Memory Data Modification

#### Analogy:
With your journey underway, you begin planning your itinerary and mentally preparing for the adventure. It's akin to mapping out your route and making mental notes of the places you'll visit before physically setting foot on your journey.

#### Technical Detail:
Changes are initially made in-memory, within the database's buffer cache. This allows for quick response times and reduces the immediate need for disk I/O. The in-memory data structures are updated first, and these changes are later propagated to the disk.


### 4. Securing the Record: Log Flush

#### Analogy:
Just as you ensure your list is safely stored in your backpack before hitting the road, the database flushes the log entries to disk to ensure they're durably recorded. This step guarantees that there's a persistent record of the transaction's changes, providing a safety net in case of unexpected detours or interruptions along the way.

#### Technical Detail:
The log entries recorded in the WAL are flushed to disk to ensure their durability. This means writing the log entries from memory to stable storage, ensuring that they are not lost even if there is a system crash.


### 5. Confirming the Voyage: Commit Record

#### Analogy:
As you progress on your journey and decide to commit to the adventure, you officially confirm your plans by signing your name on a travel document. Similarly, in a database, a special commit record is written to the log to mark the transaction as complete. This commitment ensures that the changes made by the transaction are finalized and applied to the database.

#### Technical Detail:
A commit record is written to the WAL to indicate that the transaction has been successfully completed. This commit record marks the point at which all changes made by the transaction become permanent.


### 6. Ensuring Durability: Data Page Flush (Deferred)

#### Analogy:
While you've committed to your journey, you may not immediately load all your belongings onto the transport. Similarly, in a database, modified data pages in the buffer cache are eventually flushed to disk, but not necessarily immediately. This delayed flushing optimizes performance while still ensuring durability, much like waiting for the right moment to load your belongings for maximum efficiency.

#### Technical Detail:
While the commit ensures the changes are durable, the actual data pages containing the changes might not be immediately written to disk. The database employs a lazy writing strategy, flushing these pages to disk at a later time, optimizing for performance.


## The Rollback Process

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5fpv8vwz33idi34kc9h1.png)


### 1. Identifying Uncommitted Changes: Identifying Mistakes in Your List

#### Analogy:
Suppose you suddenly realize you've forgotten to pack something essential. You identify the items you haven't packed yet. In a database, this means identifying changes made by the transaction that need to be undone.

#### Technical Detail:
If a transaction needs to be rolled back, the database first identifies all changes made by the transaction that have not been committed. This involves scanning the WAL to find all operations that need to be undone.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1trfwjr6z7qz1wn4ybgh.png)


### 2. Undo Log Entries: Erasing Mistakes

#### Analogy:
You refer back to your packing list to see what items you haven't yet packed and need to remove. Similarly, in a database, undo log entries are used to find information to undo each change made by the transaction.

#### Technical Detail:
The database uses the WAL to undo each change made by the transaction. For each operation recorded in the WAL, a corresponding undo operation is performed to revert the data to its previous state.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qocea0zu69eq0ercdul2.png)


### 3. Apply Undo Operations: Fixing Mistakes

#### Analogy:
You unpack the items you previously packed incorrectly, ensuring you're only taking what you need for the trip. In a database, undo operations are applied to in-memory data structures to reverse the changes made by the transaction.

#### Technical Detail:
The database applies the undo operations to the in-memory data structures, effectively rolling back the changes. This ensures that the database is returned to its state prior to the start of the transaction.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xsy37xueb9y30vx694mk.png)


### 4. Log Rollback: Recording the Change of Plans

#### Analogy:
You make a note in your travel log that you've decided not to proceed with the trip, keeping a record of the change in plans. Similarly, in a database, a rollback log entry indicates that the transaction was rolled back.

#### Technical Detail:
A rollback log entry may be written to indicate that the transaction has been rolled back. This helps in maintaining an accurate log for recovery purposes.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ms6otvcs0fo50vu8vie.png)


### 5. Release Locks: Freeing Resources

#### Analogy:
Any reservations or bookings you made for the trip are canceled, freeing up resources for others to use. In a database, releasing locks ensures that other transactions can access the database and make changes without any problems.

#### Technical Detail:
Any locks held by the transaction on database objects are released. This allows other transactions to access these objects and proceed with their operations.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jtytzubjicdnglqtm946.png)


### Conclusion: 
In the domain of databases, transactions are like well-planned voyages. Just as you prepare for a trip by packing your essentials and mapping out your route, databases begin transactions by organizing the changes they need to make.

During transaction’s journey, data changes are logged so that nothing gets lost along the way. For example, this log acts as a safety net for databases helping them in recovering after something unexpected happens.

When it is time for a transaction to be committed, it’s just like finalizing plans and making them official. The database ensures all changes are securely saved.

However, if there is an error and a rollback is required it’s just like changing your mind about taking a journey after all. The database cancels out any modifications made by the transaction and restores everything back to how it was before.

Releasing locks at the end of a transaction is like canceling reservations freeing up resources for others to use.

Understanding these processes will help you maintain smooth running of your database systems, reliable data, consistent operations. Whether using apps or shopping online or managing finances those background processes matter which can keep thing running smoothly. Thus next time you communicate with a data base remember committing and rolling back- ensuring you