In programming, an operation is Idempotent if it can be applied multiple times without changing the result beyond the initial application. This is a critical concept for building robust networking and state management systems.
In math terms: f(x) = f(f(x)).
If you perform an action once, it has an effect. If you perform it again, nothing new happens. The state of the world remains consistent.
If a client sends a “Use Item” packet and the server receives it twice (due to network re-routing or lag), a non-idempotent server would use two items. An idempotent server would check the packet ID and ignore the second one.
If a user double-clicks a “Submit Score” button, the logic should be idempotent. The first click sends the score; the second click recognizes a submission is already in progress and does nothing.
// Calling this twice heals the player twice.
void Heal(int amount) {
health += amount;
}
// Calling this twice results in the same health (100).
void SetFullHealth() {
health = 100;
}
To make complex actions (like “Buy Item”) idempotent, you can assign every request a unique ID (UUID).
void ProcessPurchase(string requestID, Item item) {
if (processedRequests.Contains(requestID)) return; // Already done!
inventory.Add(item);
processedRequests.Add(requestID);
}