Idempotent Requests
Idempotency is a concept that allows you to safely retry API requests without accidentally performing the same operation multiple times. This is particularly important for operations like creating charges or refunds, where duplicate requests could lead to unintended consequences.
How Idempotency Works
Payonify supports idempotent requests through the use of idempotency keys. An idempotency key is a unique identifier that you provide with your request. If a connection error occurs during the request, you can retry using the same idempotency key, and Payonify will ensure that the operation is only executed once.
Using Idempotency Keys
To make an API call idempotent, include the Idempotency-Key header with a unique string:
Code
Guidelines for Idempotency Keys
- Uniqueness: Each key should be unique for each distinct operation. You can use UUIDs or another unique identifier.
- Scope: Idempotency keys are tied to your API key. Different API keys can use the same idempotency key without conflict.
When to Use Idempotency Keys
You should use idempotency keys for requests that:
- Create new resources (e.g., charges, refunds, checkout sessions)
- Update important data
- Could have unintended consequences if run multiple times
- Are vulnerable to network interruptions
Idempotency Errors
If you encounter an issue with idempotency, you may receive an idempotency_error
Example Scenarios
Scenario 1: Successful Retry
- You make a request to create a charge with an idempotency key
- Network connection fails before you receive a response
- You retry the exact same request with the same idempotency key
- Payonify recognizes the key and returns the result of the original request (which was successfully processed)
- No duplicate charge is created
Scenario 2: Parameter Conflict
- You make a request to create a charge with an idempotency key
- You retry with the same idempotency key but different parameters
- Payonify returns the same initial response disregarding different parameters
Best Practices
- Generate a new idempotency key for each new operation
- Store idempotency keys along with the request parameters to ensure consistent retries
- Implement exponential backoff for retries
- Only retry failed requests (HTTP 5xx or connection errors), not business logic errors (HTTP 4xx)
- Use meaningful idempotency keys to aid debugging (e.g., include timestamps, operation types)