systemdesign distributedsystem softwarearchitecture

What is Idempotence? Explained with Real-World Examples

What is Idempotency ?

Idempotence is a property of an operation that ensures that, if the operation is repeated once or more than once, you get the same result.

Idempotence Patterns in SA

API Design

In REST APIs, HTTP methods like GET, HEAD, PUT, and DELETE are inherently idempotent.

  • GET: Used to retrieve data from a server. Multiple GET requests to the same resource are safe and should return the same data, assuming no changes have been made to the resource in the meantime.
  • HEAD: Similar to GET, but it retrieves only the header information about a resource. Since it does not return a body, it’s inherently safe and idempotent.
  • PUT: Replaces a resource’s current representation with the request payload. Repeatedly putting the same data to the same resource endpoint will leave the resource in the same state.
  • DELETE: Removes a resource. Deleting the same resource multiple times results in the same outcome: the resource is removed after the first successful request, and subsequent DELETE requests typically return a 404 Not Found or 204 No Content status, indicating that there’s no resource to delete.

A POST operation is not inherently idempotent’

  • it is typically used to create resources.

  • We can make POST operation act like Idempotent by using Post-Redirect-Get Pattern.

    Intro

    This pattern is particularly useful for handling form submissions and can mitigate issues caused by users refreshing or bookmarking pages that make changes to the server’s state.

    Link to original

MQ Systems

A message queue can contribute to making a system idempotent by ensuring that even if a message (representing a request) is delivered multiple times, the operation it triggers is executed only once, or its effect is the same regardless of how many times it’s executed.

This is crucial in distributed systems where network failures, system crashes, or other issues can lead to the same message being processed multiple times

In this example, the system ensures idempotency by:

  • Checking Transaction IDs for new payments against a database of payments already made
  • Sending the acknowledgement to the queue after the message is ignored or processed by the Payment System. Thus ensures that the same message is only sent to the Payment System once.