Search code examples
apirestconcurrencyhateoas

Concurrency in a REST api


Context

I'm creating a basic REST API -I don't really care about the purpose, it's just an example- where I have a cart containing:

  • A list of items corresponding to different products.
  • A status: either TIMEOUT, PURCHASED. A cart has a limited period of validity.
  • A link for the payment: i don't go in details for that.

A client can interact with the cart through POST, appending items and quantity on it. Appending items create sub-resources, client can deal with items by updating (PUT) or deleting (DELETE) them.

Like that: https://blog.apigee.com/detail/does_your_api_need_to_be_truly_restful

Server is responsible to update the status of the cart. I hope it doesn't break the REST principles, but he will update either:

  • with PURCHASED when the payment is done (payment link from cart resource and all the items are removed)
  • with TIMEOUT when the first item has been append to cart.

Problem

Client modify the cart resource by appending items. Server modify it "alone" when a timeout has expired.

Concurrency occurs when a client append items after the timeout has expired.

To solve it, optimistic lock seems to be suitable. Then with ETag header, the client modify the cart resource and is aware when somebody else has modified it.

Question

In this case, the concurrency is between client and server.

Is it relevant to update the ETag header (Last-Modified) when the server has modified itself the resource ?

Thanks!


Solution

  • Yes. This is an appropriate use of ETag.

    The ETag response header should change when there are new items in the cart or when the cart's status changed, e.g. to EXPIRED.

    The client can remember the ETag and send it when the user changes the cart, in the request's if-match header (on PUT/POST/DELETE calls). The server should then return a 412 code if its ETag differs.