---
title: "Idempotency"
description: "The Stablegate API supports idempotent requests, allowing you to safely retry operations without risk of duplicating side effects. This is essential for payment processing where network failures, timeouts, or client crashes can leave you uncertain whether a request succeeded."
canonical_url: "https://docs.stablegate.com/docs/guide/getting-started/idempotency"
---
# Idempotency

> The Stablegate API supports idempotent requests, allowing you to safely retry operations without risk of duplicating side effects. This is essential for payment processing where network failures, timeouts, or client crashes can leave you uncertain whether a request succeeded.

The Stablegate API supports idempotent requests, allowing you to safely retry operations without risk of duplicating side effects. This is essential for payment processing where network failures, timeouts, or client crashes can leave you uncertain whether a request succeeded.

## How It Works

Include an `Idempotency-Key` header with any `POST`, `PUT`, or `PATCH` request. The API uses this key to recognize retries of the same request:

<table>
<thead>
  <tr>
    <th>
      Header
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        Idempotency-Key
      </code>
    </td>
    
    <td>
      A unique string identifying the request (max 255 printable ASCII characters)
    </td>
  </tr>
</tbody>
</table>

::code-switcher{body="{"source":{"rail":"sepa","asset":"EUR","amount":1000},"destination":{"rail":"ethereum","asset":"USDC","client_account_uuid":"wa1b2c3d-4e5f-6a7b-8c9d-0e1f2a3b4c5d"}}" idempotency-key="ord_2025-01-15_abc123" method="POST" path="/v1/customers/c1d2e3f4-a5b6-7c8d-9e0f-1a2b3c4d5e6f/orders/"}
```bash
curl https://api.stablegate.com/v1/customers/c1d2e3f4-a5b6-7c8d-9e0f-1a2b3c4d5e6f/orders/ \
  --request POST \
  --header 'X-Api-Key: YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --header 'Idempotency-Key: ord_2025-01-15_abc123' \
  --data '{
  "source": {
    "rail": "sepa",
    "asset": "EUR",
    "amount": 1000
  },
  "destination": {
    "rail": "ethereum",
    "asset": "USDC",
    "client_account_uuid": "wa1b2c3d-4e5f-6a7b-8c9d-0e1f2a3b4c5d"
  }
}'
```
::

### Request Lifecycle

:diagram{alt="Idempotency-Key decision tree: unseen key is processed and cached; a seen key replays the cached response for the same body or returns 422 for a different body" name="request-lifecycle"}1. **First request** — The API processes the request normally, caches the response, and returns the result.
2. **Retry with same key and same body** — The API returns the cached response with an `Idempotency-Replay: true` header. No side effects are repeated.
3. **Same key, different body** — The API returns `422` to prevent accidental misuse of keys.
4. **No key provided** — The request is processed normally without idempotency guarantees.

## Generating Keys

Use any unique string up to 255 printable ASCII characters. We recommend **UUID v4** or a compound key derived from your internal identifiers:

```javascript
// Option 1: UUID v4
const idempotencyKey = crypto.randomUUID();

// Option 2: Compound key (recommended for order creation)
const idempotencyKey = `order_${customerId}_${internalOrderId}`;
```

```python
import uuid

# Option 1: UUID v4
idempotency_key = str(uuid.uuid4())

# Option 2: Compound key
idempotency_key = f"order_{customer_id}_{internal_order_id}"
```

:tip[Using compound keys tied to your business logic (e.g., customer ID + internal order ID) naturally prevents duplicate orders even across application restarts.]## Replayed Responses

When a response is served from cache, the API adds the `Idempotency-Replay` header:

```text
Idempotency-Replay: true
```

The status code and response body are identical to the original response. Your client can inspect this header for logging or debugging, but should otherwise treat the response as normal.

## Key Retention

Idempotency keys and their cached results are retained for **24 hours**. After this period, the key is released and can be reused.

## Error Handling

### []{id="422--invalid-key-format"}`422` — Invalid key format

```json
{
  "trace_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "error_code": "devapi_idempotency_invalid_key",
  "message": "Idempotency-Key contains invalid characters or exceeds 255 characters."
}
```

The key must consist of printable ASCII characters (codes 33–126) and not exceed 255 characters.

### []{id="422--key-reused-with-different-request"}`422` — Key reused with different request

```json
{
  "trace_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "error_code": "devapi_idempotency_key_misuse",
  "message": "The Idempotency-Key has already been used with a different request payload. Use a new key for a different request."
}
```

Each idempotency key is bound to a specific combination of HTTP method, URL path, and request body. Reusing a key with different parameters is rejected to prevent unintended behavior.

### []{id="409--concurrent-request-in-progress"}`409` — Concurrent request in progress

```json
{
  "trace_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "error_code": "devapi_idempotency_request_in_progress",
  "message": "A request with this Idempotency-Key is currently being processed. Retry after it completes."
}
```

Another request with the same key is still being processed. Wait briefly and retry.

## What Gets Cached

- **Successful responses** (2xx) and **client error responses** (4xx) are cached and replayed on retry.
- **Server errors** (5xx) are **not cached**. The key is released so you can retry the same request.

This means you can safely retry after a timeout or network error: if the server processed your request successfully, you'll get the cached result; if it failed with a 5xx, the retry will be processed as a new attempt.

## Which Requests Need Idempotency Keys

Idempotency keys are supported on all `POST`, `PUT`, and `PATCH` requests. They are most important for operations with financial side effects:

<table>
<thead>
  <tr>
    <th>
      Operation
    </th>
    
    <th>
      Recommended
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Create Customer
    </td>
    
    <td>
      <strong>
        Yes
      </strong>
      
       — prevents duplicate customer registration
    </td>
  </tr>
  
  <tr>
    <td>
      Create Order
    </td>
    
    <td>
      <strong>
        Yes
      </strong>
      
       — prevents duplicate orders
    </td>
  </tr>
  
  <tr>
    <td>
      Create Bank Account
    </td>
    
    <td>
      Yes — prevents duplicate account registration
    </td>
  </tr>
  
  <tr>
    <td>
      Create Wallet
    </td>
    
    <td>
      Yes — prevents duplicate wallet registration
    </td>
  </tr>
  
  <tr>
    <td>
      Check Fees
    </td>
    
    <td>
      Optional — read-only, safe to repeat
    </td>
  </tr>
  
  <tr>
    <td>
      Check Limits
    </td>
    
    <td>
      Optional — read-only, safe to repeat
    </td>
  </tr>
  
  <tr>
    <td>
      Check Exchange Route
    </td>
    
    <td>
      Optional — read-only, safe to repeat
    </td>
  </tr>
</tbody>
</table>

`GET` and `DELETE` requests are inherently idempotent and do not require keys.

## Retry Strategy

When implementing retries, we recommend:

1. **Always include an Idempotency-Key** for order creation and account registration requests.
2. **Generate the key before the first attempt** and reuse the same key for all retries of that operation.
3. **Retry on network errors and 5xx responses** — the API guarantees safe retries with the same key.
4. **Do not retry 4xx responses** (except `409`) — these indicate a client error that won't resolve on retry.
5. **Use exponential backoff** — wait 1s, 2s, 4s between retries to avoid overwhelming the API.

```javascript
async function requestWithRetry(method, path, body, idempotencyKey, maxRetries = 3) {
  for (let attempt = 0; attempt <= maxRetries; attempt++) {
    try {
      const response = await fetch(`${BASE_URL}${path}`, {
        method,
        headers: {
          "X-Api-Key": API_KEY,
          "Content-Type": "application/json",
          "Idempotency-Key": idempotencyKey,
        },
        body: JSON.stringify(body),
      });

      if (response.status === 409) {
        // Concurrent request — wait and retry
        await new Promise(r => setTimeout(r, 1000 * Math.pow(2, attempt)));
        continue;
      }

      if (response.status >= 500) {
        // Server error — safe to retry
        await new Promise(r => setTimeout(r, 1000 * Math.pow(2, attempt)));
        continue;
      }

      return response;
    } catch (error) {
      // Network error — safe to retry
      if (attempt === maxRetries) throw error;
      await new Promise(r => setTimeout(r, 1000 * Math.pow(2, attempt)));
    }
  }
}
```


## Sitemap

See the full [sitemap](https://docs.stablegate.com/sitemap.md) for all pages.
