# Idempotency

> Repeat any request without fear: with the same Idempotency-Key nothing happens twice; nothing is stamped, created or emailed again.

A network that drops halfway leaves your system not knowing whether the invoice was stamped. That's why everything that stamps requires the `Idempotency-Key` header: if you repeat the request with the same key, Fiscalisto answers with the document it already stamped instead of stamping another.

```bash tab="cURL"
curl https://api.fiscalisto.com/v1/invoices \
  -H "Authorization: Bearer $FISCALISTO_API_KEY" \
  -H "Idempotency-Key: pedido-A-1042" \
  -H "Content-Type: application/json" \
  -d '{ "customer": "cus_OufpKqnrvx9p1", "payment_form": "04", "items": [{ "product": "prd_OufpKqnrvx9p1" }] }'
```

```ts tab="TypeScript"
import { Fiscalisto } from "fiscalisto";

// The key comes from FISCALISTO_API_KEY.
const fiscalisto = new Fiscalisto();

const invoice = await fiscalisto.invoices.create({
  customer: "cus_OufpKqnrvx9p1",
  payment_form: "04",
  items: [{ product: "prd_OufpKqnrvx9p1" }],
}, { idempotencyKey: "pedido-A-1042" });
```

```python tab="Python"
from fiscalisto import Fiscalisto

# The key comes from FISCALISTO_API_KEY.
fiscalisto = Fiscalisto()

invoice = fiscalisto.invoices.create({
    "customer": "cus_OufpKqnrvx9p1",
    "payment_form": "04",
    "items": [{"product": "prd_OufpKqnrvx9p1"}],
}, idempotency_key="pedido-A-1042")
```

```php tab="PHP"
<?php

use Fiscalisto\Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
$fiscalisto = new Fiscalisto();

$invoice = $fiscalisto->invoices->create([
    'customer' => 'cus_OufpKqnrvx9p1',
    'payment_form' => '04',
    'items' => [['product' => 'prd_OufpKqnrvx9p1']],
], ['idempotency_key' => 'pedido-A-1042']);
```

```go tab="Go"
package main

import (
	"context"
	"fmt"
	"log"

	fiscalisto "fiscalisto.com/go"
)

func main() {
	// The key comes from FISCALISTO_API_KEY.
	client, err := fiscalisto.NewClient("")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	invoice, err := client.Invoices.Create(ctx, &fiscalisto.InvoiceCreate{
		Customer:    fiscalisto.IDOf[fiscalisto.InvoiceCreateCustomer]("cus_OufpKqnrvx9p1"),
		PaymentForm: fiscalisto.String("04"),
		Items: []fiscalisto.InvoiceCreateItem{
			{Product: fiscalisto.String("prd_OufpKqnrvx9p1")},
		},
	}, fiscalisto.WithIdempotencyKey("pedido-A-1042"))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(invoice.ID)
}
```

```java tab="Java"
import com.fiscalisto.FiscalistoClient;
import com.fiscalisto.RequestOptions;
import com.fiscalisto.model.InvoiceCreate;
import com.fiscalisto.model.InvoiceCreateItem;
import java.util.List;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var invoice = fiscalisto.invoices().create(new InvoiceCreate()
        .setCustomer("cus_OufpKqnrvx9p1")
        .setPaymentForm("04")
        .setItems(List.of(
                new InvoiceCreateItem()
                        .setProduct("prd_OufpKqnrvx9p1")
        )), RequestOptions.idempotencyKey("pedido-A-1042"));
System.out.println(invoice.getId());
```

```csharp tab="C#"
using Fiscalisto;

// The key comes from FISCALISTO_API_KEY.
var fiscalisto = new FiscalistoClient();

var invoice = await fiscalisto.Invoices.CreateAsync(new InvoiceCreate
{
    Customer = "cus_OufpKqnrvx9p1",
    PaymentForm = "04",
    Items = new() { new() { Product = "prd_OufpKqnrvx9p1" } },
}, new RequestOptions { IdempotencyKey = "pedido-A-1042" });
```

## Where it's used

Every `POST` in the API accepts `Idempotency-Key`, as in Stripe or Resend:

- **Whatever stamps requires it**: invoices, replacements, payment complements, credit notes, advances and their application, payroll receipts, withholding certificates, batches and invoicing a quote. Without it they answer `idempotency_key_missing`.
- **Everything else accepts it**: creating a customer, a product, a webhook, a quote, a recurring invoice, a ticket, a SAT download, sending an email, connecting a store… With the key, a retry answers the same as the first time, with `idempotent-replayed: true`, and creates nothing again nor sends another email.

`GET` and `DELETE` don't need it: repeating them changes nothing.

## How to choose it

- 1 to 255 ASCII characters, no accents or ñ (8 or more for whatever stamps). Otherwise, `400` `idempotency_key_invalid`.
- One per document, taken from something your system already has that doesn't change on retry: the id of the order, the charge or the row in your database (`pedido-A-1042`, `pago-7781`). If you don't have one, generate a UUID when you create the order and store it with it.
- Never generate it at call time: a retry would have another key and stamp twice.

## What repeating it answers

| Situation | Answer |
| --- | --- |
| The first time | `201` with the stamped document (or `202` if the PAC hasn't answered yet). |
| Repeated, already stamped | `201` (same as the first time) with the same document and the header `idempotent-replayed: true`. It uses no other timbre. |
| Repeated while the first is still stamping | `409` `request_in_progress` with `Retry-After`. Wait and repeat it. |
| Repeated with another body | `409` `idempotency_key_reused`. Nothing is stamped. |
| The first failed the checks (`422` `invoice_invalid`) | The key is free: send the corrected body with the same key. |
| SAT rejected the first (`422` `invoice_rejected`) or there were no timbres (`402`) | Repeating it with the same body tries again. With another body, `409` `idempotency_key_reused`. |

The key keeps the body it was used with from the moment it reached the PAC. If SAT rejected an invoice and you fix it, the body is different: use a new key (`pedido-A-1042-2`). Repeating with the same key and the same body is for when the problem wasn't the data: the PAC didn't answer, timbres ran out and you bought more, or the issuer didn't have its CSD yet. An `invoice_invalid` never reached the PAC, so there you can fix and repeat with the same key.

Several requests with the same key at the same time (a double click, two servers) stamp only once: one gets the document and the others `409` `request_in_progress` until it's done; repeated, they get the same document.

## How long a key lasts

A key belongs to your account and your mode: the same one in test and in live, or in two [test environments](https://fiscalisto.com/en/docs/api/pruebas-y-produccion#a-test-environment-for-each-person), are different keys. An API key restricted to some issuers has its own: it doesn't share those of account-wide keys or of another key restricted to other issuers.

- On every `POST` the key is bound to that route and that body for 24 hours: using it for something else answers `409` `idempotency_key_reused`, even on another route.
- Only successful answers (`2xx`) are kept. If the first time answered an error, nothing was done and the key is free: fix and repeat with the same key.
- Whatever stamps also keeps each key's document forever: a key that already stamped always answers that document, even months later.

After 24 hours, the key of a `POST` that doesn't stamp is free again.

## Recommended retries

The SDKs ([TypeScript, Python, PHP, .NET, Go and Java](https://fiscalisto.com/en/docs/api/sdk)) already do all this on every `POST`: they set an `Idempotency-Key` if you don't give one, keep it on every retry and wait as long as `Retry-After` says. So no SDK retry creates or sends anything twice. What follows is for calling the API directly.

Retry with the same key when:

- no answer arrived (the connection dropped or the timeout ran out);
- `409` `request_in_progress`, `429` or a `5xx` arrived, waiting what `Retry-After` says or, if it's missing, with growing waits (1, 2, 4, 8 seconds).

Don't retry a `400`, `402`, `403`, `404` or `422` without changing something: the answer would be the same.

```js title="reintentar.js"
async function timbrar(body, idempotencyKey) {
  for (let intento = 0; intento < 5; intento++) {
    let res;
    try {
      res = await fetch("https://api.fiscalisto.com/v1/invoices", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${process.env.FISCALISTO_API_KEY}`,
          "Idempotency-Key": idempotencyKey,
          "Content-Type": "application/json",
        },
        body: JSON.stringify(body),
      });
    } catch {
      // Sin respuesta: repetir con la misma llave nunca timbra dos veces.
    }
    if (res && res.status !== 409 && res.status !== 429 && res.status < 500) return res.json();
    const espera = Number(res?.headers.get("retry-after")) || 2 ** intento;
    await new Promise((r) => setTimeout(r, espera * 1000));
  }
  throw new Error("Fiscalisto no respondió; reintente más tarde con la misma Idempotency-Key.");
}
```

> **409 idempotency_key_reused isn't retried.** The example's retry sends the same body again, so a `409` is always `request_in_progress`. If your code can change the body between tries, check `error.code` before waiting.
