Sobes.tech
Junior — Middle

Can the concept of idempotency be explained in the context of web APIs and why is it important for system reliability?

sobes.tech AI

Answer from AI

Idempotency in the context of web APIs means that making the same request multiple times with the same parameters will not change the system's state after the first call. That is, regardless of how many times the client sends the request, the result will be the same and will not cause additional side effects.

This is important for system reliability because, in real network conditions, requests can be duplicated due to failures, timeouts, or retries. If an API is not idempotent, a repeated request can lead to undesirable changes, such as creating multiple identical records or double charging.

Example: HTTP methods GET, PUT, and DELETE are considered idempotent, while POST is not. If you use PUT to update a resource, repeated calls with the same data will not change the result.

// Example of an idempotent resource update method
[HttpPut("/users/{id}")]
public IActionResult UpdateUser(int id, UserDto userDto)
{
    var existingUser = _userRepository.GetById(id);
    if (existingUser == null) return NotFound();

    existingUser.Name = userDto.Name;
    existingUser.Email = userDto.Email;
    _userRepository.Update(existingUser);

    return Ok(existingUser);
}

Calling this method repeatedly with the same data will not change the user's state after the first update.