Working With APIs

Optimistic Concurrency

Learn about optimistic concurrency and how it prevents lost data writes.

What is optimistic concurrency? Permalink Get a link to this section

Optimistic concurrency assumes that multiple transactions can frequently complete without interfering with each other. Some Square API resources support versioning to enable optimistic concurrency.

Applications that integrate with these Square APIs should assume that when a resource is retrieved, it is the current resource. That resource can be updated and written back. After a resource update request succeeds and the new current version is returned, instances of the resource on other clients are stale and must be retrieved before they can be updated. An application should treat the failure to update a stale resource as a concurrency exception.

For example, two client endpoints get the same catalog item and both clients try to update it. Client A modifies the item and sends an update that succeeds and increments the item version number. The item update request from client B is rejected because the item it has is now stale. To correct the problem, client B does another GET request, updates the item, and sends a new update request.

Typical concurrent write flow Permalink Get a link to this section

Two clients are trying to update the same catalog item at the same time. The first client updates the item description and writes it back. The second client tries to write back an update on the same item, gets a concurrency error, does another GET request, and writes back an update.

  1. Client A gets catalog item "Drip coffee".

  2. Client B gets the same "Drip coffee" item.

  3. Client A changes the item description to "Filter coffee" and sends the update, which increments the item version.

  4. Client B tries to update the now stale "Drip coffee" item available_for_pickup field to false.

  5. The client B update request fails with a VERSION_MISMATCH error.

  6. Client B gets the current version of the "Filter coffee" item, changes the available_for_pickup field to false, and completes an update of the item, which increments the version.


A Square API resource version field must be treated as read-only. When updating a Square API resource with a version field, updates fail on PUT if a client endpoint has modified the value of the version field of the object in the update request body.


< Pagination