Sobes.tech
Middle

What is method idempotency?

sobes.tech AI

Answer from AI

An idempotent method is a method whose repeated execution with the same input data leads to the same final state of the system as after a single execution.

Key aspects:

  • Multiple calls do not cause side effects that change the state after the first successful execution.
  • The result of execution may differ (for example, a 200 OK response on the first call and a 409 Conflict on subsequent successful attempts if the resource is already created).
  • Examples in HTTP: methods GET, HEAD, OPTIONS, PUT, DELETE.
  • An example of a non-idempotent method in HTTP: POST, as each call usually creates a new resource or performs a new operation.
// Example of an idempotent method
public void setUserStatus(String userId, String status) {
    User user = findUserById(userId);
    if (user != null) {
        user.setStatus(status); // Setting the status multiple times does not change it if it is already the same
        saveUser(user);
    }
}

// Example of a non-idempotent method
public void createUser(User user) {
    // Each call will create a new user unless a check is in place
    saveNewUser(user);
}

Important for the reliability of distributed systems, retries, and caching.