> [!abstract] An operation is idempotent if it has the same result no matter how many times it's applied ## Ways to achieve idempotency ### Natural idempotency Many operations are naturally idempotent. Especially operations that sets [[State]] to a specific value. An example could be setting the username to the value `Kim Lindhard` You can do that operation again and again without changing the [[State]]. ### Keep track of prior decisions Check if the current state change have already been applied by keeping track of [[State change]]s via [[Event Sourcing]]. If a request for a [[State change]] with the same values have been applied then then current request can be ignored. ### Check for side effects This approach can be dangerous because the [[State]] observation is indirect and can be false positive or false negative. If the light sensor in a room, states that the current light leve is high, then there is no need to `Turn On The Light`. But if the light is coming from the window and not the lamp this current state of high light level may not be the light the person in the room wants. ### Versioning Record the current version number of the subject your operation will make a [[State change]] on as the first thing when you start your operation. If, at the point of committing the [[State change]], the subject’s version number has increased beyond the one your operation initially recorded, reload the subject’s [[State]] to reflect the latest version and retry the operation. ### Identify and deduplicate A fourth option is to identify each command with a unique identifier, and keep track of a list of recently performed commands (command sourcing). If the identifier is on the list, you can discard it. ### Partner state machines [[Partner State Machine]]s are an approach introduced in the legendary paper [Life Beyond Distributed Transactions](https://queue.acm.org/detail.cfm?id=3025012) by Pat Helland. the recipient [[State Machine]] will remember if a identical message has been processed, if so the repeated messages will typically generate another response matching the behavior of the first message, but spawn no [[State change]]. ### Accept uncertainty And finally, there is always the option, at least from a business perspective, to live with some uncertainty and deal with duplicates in after they have spawned a [[State change]]. Very often there are business processes in place which can correct these scenarios. For example when you performed a duplicate payment, than you can dedupe it by issuing a credit nota. ## Sources [7 ways to achieve idempotency](https://www.linkedin.com/posts/goeleven_a-functional-core-must-be-idempotent-idempotence-activity-7280915850897809408-qXgJ/) by [Yves Goeleven](https://www.linkedin.com/in/goeleven?miniProfileUrn=urn%3Ali%3Afsd_profile%3AACoAAABZpVcBcK-Z3cPkJGv6NXx9b31NmVJ71pg)