user1028741
user1028741

Reputation: 2815

What HTTP status code is appropriate when a client attempts to update a data entity that is stale on the client-side?

I've built an API where the client will instruct the server to update some entity in the database, and it must accommodate multiple users attempting to operate on the same data entitity, possibly at the 'same time'.

This is a distributed users race condition problem. (Similar to how Wordpress handles "Locking" of blog posts as other users are editing them.)


An Example Data Entity

{
    versionID : 12345,
    type : "building",
    name : "The CN Tower"
}


Operating on a Data Entity

For example, the client will tell the server to update the name property of any given entity.

In order to handle multiple users trying to change the same entity — without the users accidentally overwriting each other's updates — each user must send along with its update request the versionID (also possibly known as a stateID) of the database entity it got it from server when it was loaded into the UI (or otherwise stored on the client-side in the case of CLI apps).

This way, if Client A has updated the building before Client B, the server will be able to tell Client B that their update request has failed because the building they're trying to update is not the current (canonical) state of such record in the database.


The Question

What is the proper http status code from the server when any user attempts to update a database record that has already been updated by another user in the interim?

Upvotes: 4

Views: 3754

Answers (2)

Jag
Jag

Reputation: 141

I think the API should respond with 409 Conflict Error, whilst including the latest state of the resource (building, in your case) in the body that helps identify the latest version to the consumer.

Upvotes: 12

Opal
Opal

Reputation: 84756

In such case the server should reply with 412 Precondition Failed status code.

It typically works with the following headers (send along with the request):

  • ETag
  • If-Modified-Since
  • If-Not-Modified-Since

Server checks the value of one the headers mentioned above and if it matches to client is allowed to modify the resource, otherwise 412 should be returned.

So A wants to edit C with ETag equal to 10. Server accepts this request, edits C computes new ETag e.g. 11 and sends the resource back. Now, if B wants to edit C with ETag equal to 10 it will receive 412. B should synchronize the resource C and try to edit it once again.

Upvotes: 1

Related Questions