5

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.

N. Q. P
  • 395
  • 5
  • 15
  • You could probably set a timeout window for your request – drtf Nov 04 '13 at 14:34
  • Hi @MrKlin, I don't quite get it. If I have a timeout (let's say 30s), then no response, I still need to re-send the POST request, and may create 2 duplicated objects on server. – N. Q. P Nov 04 '13 at 14:41
  • Hi @N.Q.P, If for some reason it's take the server more than 30s (very long time) processing your request, you may change a little bit of the business logic. Say return a "receive notification" immediately and raise a complete flag when process is done.. – drtf Nov 04 '13 at 14:46

2 Answers2

3

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.

dmcontador
  • 660
  • 1
  • 8
  • 18
1

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.

Hugo
  • 541
  • 7
  • 21