Optimistic concurrency control is a technique used in database systems to prevent conflicts when multiple transactions try to update the same data concurrently. It assumes that conflicts are rare, so it allows transactions to proceed without locking data resources. Instead, each transaction reads data and checks if any other transaction has modified the data before it writes. If another transaction has made changes, the current transaction is rolled back and can be retried with the updated data. In this way, optimistic concurrency control allows concurrent transactions to operate on the same data without locking, which can improve system performance.
Example
Here’s an example of how optimistic concurrency control can be implemented:
Suppose you have a banking application with a table for customer account information, including the account balance. A user wants to transfer $100 from their account to another account. Here’s how the transaction might proceed:
- The user initiates the transfer by submitting a command to the application. The command includes the source account ID, the destination account ID, and the amount to transfer.
- The command handler retrieves the source account information from the database and verifies that the account has sufficient funds to complete the transfer.
- The command handler creates a new event that represents the transfer, and stores it in the event store. The event includes the source account ID, the destination account ID, and the amount transferred.
- The command handler updates the source account balance in the database by subtracting the transfer amount.
- At the same time, another user initiates a transfer from the same source account to a different destination account. This transaction proceeds in the same way as the first transaction, with a new event stored in the event store and the source account balance updated in the database.
- Both transactions attempt to commit to the database. The optimistic concurrency control mechanism verifies that the source account balance has not changed since the transactions began. If the balance has not changed, the transactions are committed. If the balance has changed, one of the transactions is rolled back and the user is notified that the transfer could not be completed.
This example demonstrates how optimistic concurrency control can be used to prevent conflicting modifications to data in a database.