Problem
You are implementing an API endpoint (e.g., POST /charge) that must be idempotent using an Idempotency-Key.
Design and implement an in-memory component that enforces the following behavior:
API you must implement
Implement a class/function with an interface equivalent to:
-
Response handle(Request req)
Where Request contains:
-
string idempotencyKey
(may be empty/null)
-
string payload
(request body)
And Response contains:
-
int statusCode
-
string body
Requirements
-
No idempotency key:
If
idempotencyKey
is missing, process the request normally (always execute the business logic).
-
First time a key is seen:
Execute the business logic exactly once, return its
Response
, and store the response associated with this key.
-
Repeated key:
If the same
idempotencyKey
is seen again, return the
same stored response
and
do not
execute the business logic again.
-
Concurrent duplicates:
If two requests with the same key arrive concurrently, ensure the business logic runs
only once
; the other request(s) should wait and then return the same stored response.
-
TTL expiration:
Stored keys expire after
ttlSeconds
. After expiry, the next request with that key should be treated as a new key.
Inputs/Constraints (for testing)
-
Up to
10^5
calls to
handle
.
-
ttlSeconds
is provided at construction time.
-
You may assume a single process (in-memory only), but multiple threads may call
handle
concurrently.
What to return
Implement the logic described above. You may stub the business logic as a provided callback Response process(payload) that you call only when needed.