Idempotency
Advanced: Idempotency
Idempotency ensures that making the same API request multiple times produces the same result as making it once. This is crucial for building robust applications that can safely retry requests after network errors or timeouts without causing unintended side effects (like creating duplicate resources or charging a user multiple times).
How it Works
REALM AI supports idempotency for specific mutating operations (like creating models, listing items on the marketplace, initiating purchases) via the Idempotency-Key
HTTP header.
Generate a Key: When making a potentially mutating request for the first time, your client application generates a unique key (e.g., a UUID v4). This key should be unique for each distinct operation you want to perform.
Send the Key: Include this unique key in the
Idempotency-Key
header of your API request.Server Processing:
The first time the server receives a request with a specific
Idempotency-Key
, it processes the request as usual and stores the result (including the status code and response body) associated with that key.If the server receives another request with the same
Idempotency-Key
within a certain time window (e.g., 24 hours), it will not re-process the request. Instead, it will return the cached result from the original request.
Using Idempotency Keys
Example Scenario: Listing an item
You want to list model-123
for sale. Your application generates a unique key: uuid-abc-123
.
Request 1:
The server processes this, creates the listing, and returns a
201 Created
response.Request 2 (e.g., after a network timeout and retry):
The server recognizes
uuid-abc-123
, sees it was already processed successfully, and immediately returns the same201 Created
response from the first request without creating a second listing.
Best Practices
Use for Mutating Requests: Apply idempotency keys primarily to
POST
,PUT
,PATCH
, andDELETE
requests where unintended duplication could be harmful.Generate Unique Keys: Ensure your key generation mechanism produces highly unique keys (UUIDs are recommended).
Key Scope: Use the same key only when retrying the exact same logical operation. Use a new key for a distinct operation (e.g., listing a different model).
Storage: Your client might need to store the generated idempotency key alongside the operation details in case a retry is needed later.
Expiration: Idempotency keys typically expire on the server after a period (e.g., 24 hours). Retrying with the same key after expiration will likely be treated as a new request.
Last updated