CodePark/ questions / Methods, safety & idempotency
START PRACTICINGPRACTICE
Backend question · HTTP & API design › Methods, safety & idempotency

Explain the difference between a safe method and an idempotent method. Give examples of each and say why it matters.

A safe method is read-only by definition. An idempotent method has the same effect whether you send it once or many times.

Safe: the client does not ask for any change to the server's state. GET, HEAD, OPTIONS and TRACE are safe. The server can still log or count requests. What matters is that the client did not ask for a change.

Idempotent: sending the same request once or many times has the same intended effect on the server. These methods are idempotent:

  • all safe methods
  • PUT
  • DELETE

POST and PATCH are not idempotent by definition.

Idempotency is about the server's state, not about getting identical responses. For example, a second DELETE may return 404, but it is still idempotent, because the resource is gone either way.

Why it matters:

  • Clients, proxies and retry libraries can retry idempotent requests automatically after a network failure. Retrying a POST could create duplicates, like two orders.
  • Crawlers and prefetchers assume GET has no side effects. So GET must be safe.
  • A safe method has read-only meaning: GET, HEAD, OPTIONS and TRACE are safe.
  • An idempotent method has the same effect if you repeat it: the safe methods plus PUT and DELETE.
  • POST and PATCH are not idempotent by definition.
  • Idempotency is about server state, not about identical responses.
  • Idempotency allows automatic retries, and GET must never change data.