Junior — Middle
How to implement safety against repeated calls in a REST controller so that it is resistant to re-execution?
sobes.tech AI
Answer from AI
To make a REST method idempotent, you can use several approaches:
-
Idempotent operations: design methods so that repeated calls with the same parameters do not alter the system's state further.
-
Using unique identifiers (idempotency keys): the client generates a unique key for each operation and sends it in the request. The server stores processed keys and ignores repeated requests with the same key.
-
Locks and transactions: use locking mechanisms or transactions to ensure that the operation is executed only once.
Example using a unique key:
@PostMapping("/process")
public ResponseEntity<?> process(@RequestHeader("Idempotency-Key") String key, @RequestBody Data data) {
if (processedRequests.containsKey(key)) {
return ResponseEntity.ok(processedRequests.get(key)); // Return the result of the previous call
}
Result result = service.processData(data);
processedRequests.put(key, result);
return ResponseEntity.ok(result);
}
Here, processedRequests is, for example, a thread-safe cache or database where results are stored by keys.