Optimistic Locking and Concurrency

Apiture APIs use optimistic locking in cases of concurrent updates of resources from multiple clients.

HTTP provides a protocol using entity tags. Responses representing mutable resources include an entity tag in the ETag response header. The value of the entity tag (an opaque string with no meaning) changes each time a resource is updated.

An update via PUT or PATCH or POST passes the entity tag via the If-Match request header. If the resource has changed since the client received the representation, and the value of the client’s entity tag does not match the current entity tag on the server, then the If-Match precondition test fails. This means another agent updated the resource since the entity tag was issued to the client, changing its entity tag value. If so, the PUT/PATCH/POST operation is rejected (not processed) with a 412 Precondition Failed response. If the request omits the If-Match request header, the operations is rejected (not processed) and the service responds with 428 Precondition Required.

If a client already holds a representation of the resource and wishes to fetch the most recent data, it can issue a GET request and pass an If-None-Match header whose value is the entity tag that the client obtained with that cached representation. If the resource has not been modified (the entity tag values match), the GET request will return 304 Not Modified and no response body. If the resource has changed (the client’s cached data is stale), the API will return 200 OK and the updated data (or perhaps a 3xx response if the resource has moved). Using entity tags also requires the service return cache headers to indicate that the resource maybe cached.

ETag is preferred over using Last-Modified / If-Unmodified-Since headers, since the Last-Modified header in HTTP does not support sub-second granularity. That is, a resource can change multiple times but it’s associated Last-Modified date-time stamp might not change, so clients may not know the resource has actually changed.