N. Q. P
N. Q. P

Reputation: 395

How to avoid sending 2 duplicate POST requests to a webservice

I send a POST request to create an object. That object is created successfully on the server, but I cannot receive the response (dropped somewhere), so I try to send the POST request again (and again). The result is there are many duplicated objects on the server side.

What is the official way to handle that issue? I think it is a very common problem, but I don't know its exact name, so cannot google it. Thanks.

Upvotes: 5

Views: 5380

Answers (2)

Hugo
Hugo

Reputation: 651

It is unreliable to fix these issues on the client only.

In my experience, RESTful services with lots of traffic are bound to receive duplicate incoming POST requests unintentionally - e.g. sometimes a user will click 'Signup' and two requests will be sent simultaneously; this should be expected and handled by your backend service.

When this happens, two identical users will be created even if you check for uniqueness on the User model. This is because unique checks on the model are handled in-memory using a full-table scan.

Solution: these cases should be handled in the backend using unique checks and SQL Server Unique Indices.

Upvotes: 1

dmcontador
dmcontador

Reputation: 668

In REST terminology, which is how interfaces where POST is used to create an object (and PUT to modify, DELETE to delete and GET to retrieve) are called, the POST operation is attributed un-'safe' and non-'idempotent, because the second operation of every other type of petition has no effect in the collection of objects.

I doubt there is an "official" way to deal with this, but there are probably some design patterns to deal with it. For example, these two alternatives may solve this problem in certain scenarios:

  • Objects have unicity constraints. For example, a record that stores a unique username cannot be duplicated, since the database will reject it.
  • Issue an one-time use token to each client before it makes the POST request, usually when the client loads the page with the input form. The first POST creates an object and marks the token as used. The second POST will see that the token is already used and you can answer with a "Yes, yes, ok, ok!" error or success message.

Useful link where you can read more about REST.

Upvotes: 3

Related Questions