Idempotency and Safety

Idempotency

it’s the ability to perform the same action multiple times while only producing “side effects” on the server once.

An idempotent HTTP method is an HTTP method that can be called many times without different outcomes.

Safe action:

GET / HEAD / OPTIONS / TRACE

Unsafe actions:

PUT / POST / DELETE

idempotent REST APIs

  1. POST is NOT idempotent.
  2. GETPUTDELETEHEADOPTIONS and TRACE are idempotent.

Safety and idempotency of HTTP methods

Method Safe? Idempotent?
GET Yes Yes
HEAD Yes Yes
OPTIONS Yes Yes
PUT No Yes
DELETE No Yes
POST No No
PATCH No No

 

How to make it idempotent call

Constructing a retry mechanism for non-idempotent requests requires cooperation from the server.

the client attaches a unique ID to each request (a GUID/UUID would suffice). When the server processes a request successfully, it saves the ID and a copy of the response it wants to send back. If that response never makes it back to the client, the client will send the request again, reusing the same ID. The server will recognize the ID, skip the actual processing of the request, and just send back the stored response. This makes all requests effectively idempotent from the client’s point of view.

private string Execute(string queryString){
    // maxRequestTries is a private class member set to 3 by default, optionally set via a constructor parameter (not shown)
    var remainingTries = maxRequestTries;
    var exceptions = new List();  
    do {
        try {   --remainingTries;
            return ExecuteSingle(queryString);
        }
        catch (Exception) {
            exceptions.Add(e);
        }
    } while (remainingTries > 0)
    throw new AggregateException(exceptions)  //containing a list of all the exceptions thrown on each request
}

发表评论