ndsurendra
ndsurendra

Reputation: 453

REST APIs: How to ensure atomicity?

I am developing a small REST API. As I got into analyzing all the possible failure scenarios, which I have to handle to create a reliable and stable system, I went into thinking about how to make my APIs atomic.

If we take a simple case of creating a contact through the POST API.

The client is bound to think that the contact creation has failed, though, in fact, the contact was in the DB.

Is this a rare case we can ignore? How do big companies deal with such an issue?

Upvotes: 2

Views: 3126

Answers (2)

Ed Griffin
Ed Griffin

Reputation: 486

If the request times out, the client should not make any assumption about whether it failed or succeeded.

If it is just a user making a request from a web form, then the timeout should just be exposed to the user, and they can hit the back button and check whether the operation succeeded or not, and if not they submit the request again. (This is fine as long as you always keep a consistent state. If your operation has multiple steps and fails mid way, you need to roll back.)

However if reliable messaging is important to your application you will have to use a library or build your own reliable messaging layer. This could work by having the client assign a unique ID to every request, and having another request that lets you check the result of that request ID later. Then you can do automated retries but only where necessary.

Upvotes: 1

Piyg
Piyg

Reputation: 244

To handle this, you should make your write APIs idempotent i.e. If the same operation is executed multiple times, the result should be same as the operation was done only once.

To achieve this in your current example, you need to be able to identify a contact uniquely based on some parameter, say emailAddress. So, if the createContact is called again with the same emailAddress, check in the DB if a contact already exists with the emailAddress. If so, return the existing contact. Else, create a new contact with the emailAddress and return it.

Hope this helps.

Upvotes: 3

Related Questions