What techniques can we use to avoid collision between data from two PUT requests so that the changes in the second request do not override the first request?
Let's imagine the situation:
- There is a product registered in a virtual store system named "Product Well Bacana", without description and unit price R $ 10.00.
The JSON that would represent the resource is shown below, accessed via /produto/1
.
{
"id": 1,
"name": "Produto Bem Bacana",
"description": "",
"price": 10.00
}
We have two active users in the system: Albert and Bohr; both access the resource. Staying then:
[Banco de dados] [Albert] [Borh]
{ { {
"id": 1, "id": 1, "id": 1,
"name": "Produto Bem Bacana", "name": "Produto Bem Bacana", "name": "Produto Bem Bacana",
"description": "", "description": "", "description": "",
"price": 10.00 "price": 10.00 "price": 10.00
} } }
At this point, Albert realizes that the product is without description and decides to add it.
[Banco de dados] [Albert] [Borh]
{ { {
"id": 1, "id": 1, "id": 1,
"name": "Produto Bem Bacana", "name": "Produto Bem Bacana", "name": "Produto Bem Bacana",
"description": "", "description": "É bacana mesmo", "description": "",
"price": 10.00 "price": 10.00 "price": 10.00
} } }
Albert then submits to the database, updating the feature:
[Banco de dados] [Albert] [Borh]
{ { {
"id": 1, "id": 1, "id": 1,
"name": "Produto Bem Bacana", "name": "Produto Bem Bacana", "name": "Produto Bem Bacana",
"description": "É bacana mesmo", "description": "É bacana mesmo", "description": "",
"price": 10.00 "price": 10.00 "price": 10.00
} } }
Borh realizes that the price of the product is wrong. Instead of R $ 10.00, the product should be worth R $ 15.00. This way, it fixes the product:
[Banco de dados] [Albert] [Borh]
{ { {
"id": 1, "id": 1, "id": 1,
"name": "Produto Bem Bacana", "name": "Produto Bem Bacana", "name": "Produto Bem Bacana",
"description": "É bacana mesmo", "description": "É bacana mesmo", "description": "",
"price": 10.00 "price": 10.00 "price": 15.00
} } }
Borh then submits your change to update in the database:
[Banco de dados] [Albert] [Borh]
{ { {
"id": 1, "id": 1, "id": 1,
"name": "Produto Bem Bacana", "name": "Produto Bem Bacana", "name": "Produto Bem Bacana",
"description": "", "description": "É bacana mesmo", "description": "",
"price": 15.00 "price": 10.00 "price": 15.00
} } }
And it turns out that Bohr's information was outdated after Albert made his changes. By the time Bohr submits his own, the description that Albert had added is lost.
So, what techniques can be applied to prevent this data collision? How could it be done to identify, at the time of Bohr's submission, that the resource has been updated and that its information is outdated, preventing its changes from overwriting Albert's?
I quoted the PUT method because all resource information was usually sent through the request, not just changed fields, as it would be in PATCH - which would suffer from the same harm if Albert and Bohr changed the same field. p>