Why do HTTP operations need to be Idempotent when we have TCP/IP?
Why do we need HTTP GET,开发者_C百科 PUT, or DELETE to be idempotent if TCP/IP is a reliable protocol that will retry requests on our behalf?
TCP/IP does not retry requests, it retransmits the original packets that make up each request, if necessary.
If a request fails (at the HTTP layer) it's the job of the client to retry it, not the network stack.
In particular, if the client (for what ever reason) fails to receive the response code indicating whether a RESTful operation succeeded or not, the client must be able to resend the same operation without having to worry about any unintended side effects.
These failures can happen - an intermediate firewall might have timed-out the connection while the server was processing the operation. The server won't know that this has happened, as soon as it has received the request it has to carry on regardless.
HTTP's GET, PUT, and DELETE are idempotent because, in some network failure modes, the client cannot know whether the request completed or how fully.
For example, if a client requests a DELETE of a resource, but the server closes the connection before the complete response is received by the client, the client does not know whether the resource was deleted or not. The client then has a dilemma: perhaps the operation failed, in which case the DELETE should be re-sent in order to advance the application to the desired state. But perhaps it succeeded; will sending the same DELETE request work if I retry? Perhaps it will work. Perhaps it will return a 500 error (which just adds to the client's confusion). Perhaps it will apply to a different resource! The idempotency requirement allows the client to be confident that they can retry the request and have it work. That doesn't mean you'll get exactly the same response; the first request might receive 200 OK and the second 404 Not Found or 410 Gone. But the client doesn't have to worry about unintended side-effects from retries.
You seem to be confusing Idempotency at the HTTP-protocol level with byte-stream reliability at the TCP level.
HTTP Idempotency:
Idempotent (wikipedia) means that sending the same HTTP request 10 times has the same effect as doing it once.
TCP reliability:
If you lose a packet in a TCP stream, it will be retransmitted. But the application-protocol (HTTP) has no knowledge that TCP had to retransmit packets.
Even if an individual packet containing a complete HTTP request is retransmitted 10 times by TCP, the browser/server will only see one HTTP request. The reason TCP retransmits is because of packet loss, but application-protocols (like HTTP) have no knowledge that TCP had to retransmit. They seem the same request with or without packet loss
精彩评论