.NET Architecture & System Design Interview Question #98

What is optimistic locking in a REST API?

Transactions, CQRS, Event Sourcing & Distributed Consistency Mid-Level Intermediate

Quick Interview Answer

Optimistic locking prevents lost updates by requiring a client to update the version it previously read. The server accepts the update only if the resource has not changed in the meantime.

Detailed Explanation

Optimistic locking prevents lost updates by requiring a client to update the version it previously read. The server accepts the update only if the resource has not changed in the meantime.

HTTP APIs can implement this with ETags and If-Match headers or with explicit version fields. On mismatch, the server returns a conflict or precondition failure so the client can reload or reconcile.

Code Example

GET /products/1
ETag: "v7"

PUT /products/1
If-Match: "v7"

Current version = v8
-> reject stale update