Search code examples
restapi-design

How to ensure consistency while updating a document through REST API


I am designing a REST API that will have two client updating it, possibly at the same time: * Client A will GET a document, spend some X minutes processing and modifying it, then PUT it back. * Client B might PUT a new document at any time.

The problem arises when Client B PUT's new document whilst Client A is processing old version of the document. In this case, Client A will eventually override the changes Client B made, by PUT'ing modified version of an old document. I would like Client A to drop the processing result instead.

To explain it better, here is an example of straightforward(problematic) workflow:

  1. Client A GET <- Document version 1
  2. Client B PUT -> Document version 2
  3. Client A PUT -> Document version 1.1

Desired workflow:

  1. Client A GET <- Document version 1
  2. Client B PUT -> Document version 2
  3. Client A PUT -> Error. Client A drops the results and restarts
  4. Client A GET <- Document version 2
  5. Client A PUT -> Document version 2.1

Obviously, this can be achieved with versioning the documents in some manner. My question is whether there exists some standard way to achieve it (I'm sure I'm not the only one with this kind of problem), or should I design my own solution.


Solution

  • You're looking for RFC 7232. Specifically, you want either the If-Unmodified-Since header or the If-Match header. They will make Client A's PUT request conditional on the resource being unchanged on the server.