====== Idempotency for APIs ====== Idempotency for APIs is especially important because the likelyhood of an API consumer implementing a "retry" functionality is alot higher than someone working with a UI. What does a "retry" functionality have to do with Idempotency though you may ask? As briefly explained in the article about [[programmieren:grundlagen:idempotency|Idempotency]] Idempotency is ensuring that actions always result in the same one thing. This is hard to do for API endpoints like ''POSTs'' because if not handled properly multiple exact same requests will cause multiple entries to be created, which can violate the Data Integrity. To counteract this, a decently new HTTP header has been developed, called an "Idempotency-key" it is basically an identifier to the request, according to which, an application should decide if it should run the business logic again or simply return the cached response from a previous request. Heres a Diagram to visualize this: @startuml 'https://plantuml.com/de/activity-diagram-beta start :Request arrives with Idempotency-Key: key-xyz; if (Check key-xyz in storage) then (Exists) :Key found; if (Key status?) then (completed) :Status: completed; if (Request hash matches the stored one?) then (Matches) :Return cached response (don't reprocess); end else (Doesn't match) :Return 422 Different payload for the same key; end endif else (processing) :Return 409 Conflict (still being processed); end endif else (Not found) :Atomic Insert key with status `processing` (UNIQUE constraint); if (Insert suceeded? (affected rows = 1)) then (Yes) :Execute business logic; :Save response + update status to `completed`; :Return response; end else (No (duplicate insert) :Return 409 Concurrent duplicate; end endif @enduml And another Diagram to show how and what could go wrong with ERV BE PartnerAPI as an example: @startuml 'https://plantuml.com/de/sequence-diagram title "Idempotency demonstration with PartnerAPI example" note across: Without Idempotency -- Retry = Saved twice client as "User/Client" -> server as "Server": POST /private/bookings {policy data} server -> db as "Database": Persist Policy Data note over server: Server crash / Timeout before sending response! client --> client: Timeout -- no response recieved client -> server: POST /private/bookings (RETRY) server -> db: Persist Policy Data AGAIN server --> client: 201 CREATED note across: Two different Policies with identical data were persisted! note across: With Idempotency -- Retry is Safe client -> server: POST /private/bookings { Idempotency-Key:key-abc } server -> db: Persist Policy Data + save key-abc + response note over server: Server crash / timeout! client --> client: Timeout client -> server: POST /private/bookings { Idempotency-Key:key-abc } (RETRY) server -> db: Check key-abc, already exists, get cached response server --> client: 201 CREATED (returns cached response, without actual change) note across: Policy data is only saved once while Client still receives success response @enduml But in what situation can a request be sent twice, usually after a request a user won't resend the request. But an automated API might, incase it recieves no response due to some kind of network or server issue, it might send a retry on a timeout which would cause the request to be recieved and saved twice. This is only an issue for endpoints with ''POST'' or ''PATCH'' since the others are naturally Idempotent. A ''GET'' request is safe anyways as it doesn't edit data. ''Delete'' is Idempotent as calling it multiple times will not delete more pages, only the same one over and over. This will lead to a different response to the user. Some kind of ''404 Not Found'' will be thrown however, the effect on the application remains the same which is why its Idempotent. ''PUT'' Is Idempotent as it overwrites one singular resource in the exact same way, which leads to no change in data. ''PATCH'' even tho listed as not Idempotent, can also be Idempotent, it can also only edit things in the exact same way, however it can also edit resources percentually, which would lead to for example a price to be raised by 20% twice on a duplicate request. This is only if you follow the conventions, since if you wanted to, you could just map a ''PATCH'' request to logic that creates a new entry.