|
| 1 | +# Optimistic Locking |
| 2 | + |
| 3 | +Optimistic locking is a concurrency control mechanism that allows multiple transactions to proceed without locking |
| 4 | +resources but checks for conflicts before committing changes. This approach is useful in scenarios where contention |
| 5 | +for resources is low, and it helps to improve performance by reducing the overhead of locking. |
| 6 | + |
| 7 | +## How It Works |
| 8 | + |
| 9 | +In optimistic locking a version number is used to track changes to a record. |
| 10 | + |
| 11 | +1. When a record is updated the version number is incremented; |
| 12 | +2. Before committing the changes the application checks if the version number in the database matches the version number |
| 13 | + in the application; |
| 14 | +3. If they match the changes are committed otherwise an exception is thrown indicating that the record has been modified |
| 15 | + by another transaction since it was read. |
| 16 | + |
| 17 | +```mermaid |
| 18 | +sequenceDiagram |
| 19 | + participant A as Application 1 |
| 20 | + participant DB as Database |
| 21 | + participant B as Application 2 |
| 22 | + |
| 23 | + Note over A,DB: Initial state: Record with version=1 |
| 24 | + |
| 25 | + A->>DB: Read record (version=1) |
| 26 | + B->>DB: Read same record (version=1) |
| 27 | + |
| 28 | + Note over A: Modify record locally |
| 29 | + Note over B: Modify record locally |
| 30 | + |
| 31 | + A->>DB: Update record with changes<br/>(Check version=1) |
| 32 | + Note over DB: Versions match!<br/>Update succeeds<br/>Increment version to 2 |
| 33 | + DB-->>A: Commit successful |
| 34 | + |
| 35 | + B->>DB: Update record with changes<br/>(Check version=1) |
| 36 | + Note over DB: Versions don't match!<br/>(DB has version=2) |
| 37 | + DB-->>B: Throw OptimisticLockException<br/>"Record modified by another transaction" |
| 38 | + |
| 39 | + Note over B: Must re-read record<br/>and retry operation |
| 40 | + B->>DB: Read record (version=2) |
| 41 | + Note over B: Resolve conflict and<br/>apply changes |
| 42 | + B->>DB: Update record with new changes<br/>(Check version=2) |
| 43 | + Note over DB: Versions match!<br/>Update succeeds<br/>Increment version to 3 |
| 44 | + DB-->>B: Commit successful |
| 45 | +``` |
| 46 | + |
| 47 | +## Implementation |
| 48 | + |
| 49 | +To implement optimistic locking in your Active Record model you need to follow these steps: |
| 50 | + |
| 51 | +### 1. Add a version column |
| 52 | + |
| 53 | +Add a version column to your database table. This column will be used to track changes to the record. |
| 54 | +For example, you can add a `version` column of type `bigint`. |
| 55 | + |
| 56 | +```sql |
| 57 | +ALTER TABLE document ADD COLUMN version BIGINT DEFAULT 0; |
| 58 | +``` |
| 59 | +### 2. Define the version property |
| 60 | + |
| 61 | +In your Active Record model, define a property for the version column and implement the `OptimisticLockInterface` |
| 62 | +interface. |
| 63 | + |
| 64 | +```php |
| 65 | +use Yiisoft\ActiveRecord\ActiveRecord; |
| 66 | +use Yiisoft\ActiveRecord\OptimisticLockInterface; |
| 67 | + |
| 68 | +final class Document extends ActiveRecord implements OptimisticLockInterface |
| 69 | +{ |
| 70 | + public int $id; |
| 71 | + public string $title; |
| 72 | + public string $content; |
| 73 | + public int $version; |
| 74 | + |
| 75 | + public function optimisticLockPropertyName(): string |
| 76 | + { |
| 77 | + return 'version'; |
| 78 | + } |
| 79 | +} |
| 80 | +``` |
| 81 | + |
| 82 | +### 3. Handle optimistic locking exceptions |
| 83 | +When saving, updating or deleting the record handle the `OptimisticLockException` exception that is thrown |
| 84 | +if the version number does not match. |
| 85 | + |
| 86 | +```php |
| 87 | +use Yiisoft\ActiveRecord\OptimisticLockException; |
| 88 | + |
| 89 | +try { |
| 90 | + $document->save(); |
| 91 | +} catch (OptimisticLockException $e) { |
| 92 | + // Handle the exception, e.g. reload the record and retry logic or inform the user about the conflict |
| 93 | + |
| 94 | + $document->refresh(); |
| 95 | + // Retry logic |
| 96 | +} |
| 97 | +``` |
| 98 | + |
| 99 | +## Usage with Web Application |
| 100 | + |
| 101 | +In a web application, you can use optimistic locking in your controllers or services where you handle the business logic. |
| 102 | + |
| 103 | +For example, when updating a document: |
| 104 | + |
| 105 | +```php |
| 106 | +use Psr\Http\Message\ResponseInterface; |
| 107 | +use Psr\Http\Message\ServerRequestInterface; |
| 108 | +use Yiisoft\ActiveRecord\ActiveQuery; |
| 109 | + |
| 110 | +final class DocumentController |
| 111 | +{ |
| 112 | + public function edit( |
| 113 | + ServerRequestInterface $request, |
| 114 | + ): ResponseInterface { |
| 115 | + $id = (int) $request->getAttribute('id'); |
| 116 | + |
| 117 | + $document = (new ActiveQuery(Document::class))->findOne($id); |
| 118 | + |
| 119 | + if ($document === null) { |
| 120 | + throw new NotFoundException('Document not found.'); |
| 121 | + } |
| 122 | + |
| 123 | + // Render the document edit form with the current version |
| 124 | + } |
| 125 | + |
| 126 | + public function save( |
| 127 | + ServerRequestInterface $request, |
| 128 | + ): ResponseInterface { |
| 129 | + $data = $request->getParsedBody(); |
| 130 | + |
| 131 | + $id = (int) $data['id']; |
| 132 | + $document = (new ActiveQuery(Document::class))->findOne($id); |
| 133 | + |
| 134 | + if ($document === null) { |
| 135 | + throw new NotFoundException('Document not found.'); |
| 136 | + } |
| 137 | + |
| 138 | + $document->title = $data['title'] ?? ''; |
| 139 | + $document->content = $data['content'] ?? ''; |
| 140 | + $document->version = (int) ($data['version'] ?? 0); |
| 141 | + |
| 142 | + try { |
| 143 | + $document->save(); |
| 144 | + } catch (OptimisticLockException $e) { |
| 145 | + // Handle the exception, e.g. reload the record and retry logic or inform the user about the conflict |
| 146 | + |
| 147 | + $document->refresh(); |
| 148 | + // Retry logic |
| 149 | + } |
| 150 | + |
| 151 | + // Redirect or render success message |
| 152 | + } |
| 153 | +} |
| 154 | +``` |
0 commit comments