Idempotency Deduplication of Retried Requests
Problem Statement
Retries can cause the same side-effecting request to run twice. Use idempotency keys to return the first response for any repeated key instead of re-executing.
Background
Each request carries an idempotency_key and a result. Processing in order: the first time a key is seen, its result is committed and returned. Any later request with a key already committed returns the stored result (a replay), regardless of its own result value. Report the response returned for each request and whether it was a replay.
Your Task
def dedupe_requests(requests):
- requests: list of {"idempotency_key": str, "result": any}.
- Return a list of {"result": committed_result, "replay": bool} per request.
Input Format
- requests (list of dicts).
Output Format
- A list of dicts {"result", "replay"}.
Sample
print(dedupe_requests([{"idempotency_key":"a","result":1},{"idempotency_key":"a","result":99}]))
Output:
[{'result': 1, 'replay': False}, {'result': 1, 'replay': True}]
Example
print(dedupe_requests([{"idempotency_key":"a","result":1},{"idempotency_key":"a","result":99}]))[{'result': 1, 'replay': False}, {'result': 1, 'replay': True}]- Initialize an empty store to track committed idempotency keys and their associated results.
- Process the first request with key
"a"and result1: since"a"is not in the store, commit result1to the store and record the response as{"result": 1, "replay": False}. - Process the second request with key
"a"and result99: since"a"is already in the store, retrieve the stored result1and record the response as{"result": 1, "replay": True}, ignoring the new result99. - The final output is
[{'result': 1, 'replay': False}, {'result': 1, 'replay': True}]
Constraints
- First occurrence of a key commits and returns its own result (replay False).
- Later occurrences return the committed result (replay True), ignoring their own result.
- Preserve input order.