Learn about optimistic concurrency and how it prevents lost data writes with Square APIs.
Concurrency is the concept of executing two or more applications at the same time. When these applications access the same objects at the same time, they can interfere with each other in unexpected ways. Without optimistic concurrency, if two client applications retrieve the same catalog item and both try to update it, the following can happen:
- Client A modifies the item and sends an update.
- Client B also modifies the item and sends the update overwriting the changes client A made, which is unintended.
Optimistic concurrency refers to the ability of multiple operations to complete without interfering with each other. The Square API enables optimistic concurrency by supporting versioning on some of the API resources.
For example, each Customer
object has a version
field. Initially, the version number is 0. For each successful update, Square increases the version number. If you don't specify a version number in an update request, the latest version is assumed.
Note
Different Square APIs use different versioning schemes.
In your update or delete request, you must provide the version number you received from Square. Otherwise, Square returns a "version mismatch" error on your request and your application must retrieve the object again and then update it.
A version field can only be updated by Square. Your application must have the current object and you pass in the version
value of the object update request.
Consider an example of two clients trying to update the same object at the same time. The first client updates the object and writes it back. The second client tries to write back an update on the same object, gets a concurrency error, does another GET request, and then performs the update.
- Client A gets a catalog item "Coffee".
- Client B gets the same "Coffee" item.
- Client A changes the item
description
to "Filter coffee" and sends the update, which increments the item version. - Client B tries to update the now stale "Coffee" item
available_for_pickup
field tofalse
. - The client B update request fails with a
VERSION_MISMATCH
error. - Client B gets the current version of the "Filter coffee" item, changes the
available_for_pickup
field tofalse
, and completes an update of the item, which increments the version.
There are other Square API patterns. For more information, see Common Square API Patterns.