Sign inGet started
Back to blog
Rejections and errors

Duplicate invoices: avoiding them with idempotent issuance

How to avoid a duplicate invoice when the network fails mid-issuance: Idempotency-Key, consulting the NFS-e by DPS id and when a retry is safe.

In an integration, a duplicate invoice almost never comes from a double click: it comes from a timeout. The system sends the NF-e or NFS-e, the connection drops before the answer, and the code, not knowing whether the document was authorized, tries again. If the first attempt reached the tax authority, the second becomes a second fiscal document for the same sale — or a duplicate rejection, if the numbering is the same.

The defence is idempotency: every issuance gets a key of your own, and every retry uses that same key. In the Stackin API, the Idempotency-Key header on POST /api/v1/invoices makes a retry with the same key and the same body return the first response instead of issuing again. And when the one not answering is the authority — the SEFAZ or the NFS-e Nacional's ADN —, Stackin consults the document before recording anything and says, through the error code, whether trying again is safe.

How Idempotency-Key works on issuance

The header applies to POST /invoices, POST /invoices/{invoice_id}/reissue and POST /invoices/{access_key}/cancel. The key is yours, up to 255 characters, scoped to your company. Stackin keeps the key together with a fingerprint of the request body for 24 hours:

  • New key: issues normally and records the response.
  • Same key and same body, first call finished: returns the recorded response. No new document, no credit spent.
  • Same key with a different body: 422. Reusing a key for another request is a client error, not a retry.
  • Same key while the first call is still running: 409, still in progress.
  • The first call failed (a SEFAZ rejection, say): the key is released and the next call is processed again.
  • After 24 hours, the same key is treated as new.
POST /invoices with Idempotency-Key
Copy
curl -X POST https://api.stackin.io/api/v1/invoices \
  -H "Authorization: Bearer $STACKIN_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: order-1234-nfse" \
  -d @order-1234.json

Generate the key once per business event — order 1234, March's subscription — and store it with that event, not per HTTP call: a key drawn fresh on each attempt protects nothing. That is why the SDKs never generate one themselves; they pass on what you send as idempotency_key (idempotencyKey in Node and PHP, IdempotencyKey or WithIdempotencyKey in Go). An issue, reissue or cancel sent without the header comes back with Stackin-Idempotency: absent on the response, the warning that the call was unprotected.

What happens when the network fails mid-issuance

A network failure between Stackin and the authority falls into one of three cases. Those that end in an error arrive as 502, with an error block whose source is transport; what changes is error.code and error.retryable.

  • It never left. Connection refused, DNS, connect timeout or a failed TLS handshake: the document never reached the authority. You get CONNECTION_FAILED with retryable: true and invoice_id: null. Nothing was recorded: no rejected invoice in the history, no webhook, no charge. On an auto-numbered issuance, the next attempt may reuse the same number.
  • It left and no answer came. Here Stackin does not guess: it asks the authority by the document's own identifier — for an NF-e, the SEFAZ situation by the access key it just sent; for an NFS-e, the ADN by the DPS id. If the document exists, the response is that of a normal issuance. If the authority confirms it holds nothing, you get CONNECTION_FAILED as above, and the number used stays behind, so a late arrival of the first attempt can never collide with the second.
  • It left, no answer came, and the consult failed too. Nobody knows whether the document exists. You get OUTCOME_UNKNOWN, with retryable: false and document_id: the NF-e access key or the NFS-e DPS id.
502 OUTCOME_UNKNOWN
Copy
{
  "detail": "Authorizer error (OUTCOME_UNKNOWN): the NF-e 3526… was sent and the SEFAZ never answered (…) — the document was sent, the tax authority never answered, and it could not be asked afterwards whether it issued it. …",
  "error": {
    "code": "OUTCOME_UNKNOWN",
    "source": "transport",
    "message": "the NF-e 3526… was sent and the SEFAZ never answered (…); it could not be asked whether it authorized it",
    "guidance": "the document was sent, the tax authority never answered, and it could not be asked afterwards whether it issued it. It may exist. Do not send the same request again: consult document_id at the authority (the NF-e access key, or the NFS-e DPS id) once it is back, and issue again only if it is not there.",
    "invoice_id": null,
    "retryable": false,
    "document_id": "3526…",
    "status_url": "https://app.stackin.io/status"
  }
}

It is the same care the NF-e Portal asks of every client application: when a batch receipt is lost, consult the access key of each NF-e and decide from the result instead of sending again. Resending the same sale with a different numeric code is the classic path to rejection 539; resending an already authorized note leads to rejection 204. When the authority is down for longer, that is a different topic: SEFAZ unavailable and contingency. On every transport error worth retrying, error.status_url points to the public status page for the authorities.

An issuance with no answer never becomes a rejected invoice: no invoice_id, no invoice.rejected webhook, no charge. If your integration treated CONNECTION_FAILED as a recorded rejection, treat it as "nothing was issued".

Why a retry with the same key gets 409

On OUTCOME_UNKNOWN, Stackin does not release the idempotency key: it stays held as in progress until it expires, 24 hours after the first call. A retry with the same key gets 409 instead of a second issuance. That is deliberate: if the document exists, sending again would issue the same sale twice; if it does not, only the authority can say so.

The way forward is to wait for the authority to come back and consult document_id. For an NF-e, GET /api/v1/invoices/{access_key}?document_type=nfe asks the SEFAZ for its situation. For an NFS-e, document_id is the DPS id, and GET /api/v1/invoices/dps/{dps_id} asks the national environment whether that DPS produced a note. The answer is the one the consult by access key gives, plus the note's access_key; if the ADN holds the note as cancelled, it comes back with status: "cancelled". A 404 says the authority has no note for that DPS, meaning nothing was issued; an id that is not your company's (its CNPJ or CPF and municipality are part of it) is 400. Issue again, with a new key, only if the document is not there. And do not treat the end of the 24 hours as a green light: after that the key counts as new and a retry would really issue.

GET /invoices/{access_key}
Copy
curl "https://api.stackin.io/api/v1/invoices/$ACCESS_KEY?document_type=nfe" \
  -H "Authorization: Bearer $STACKIN_API_KEY"
GET /invoices/dps/{dps_id}
Copy
curl "https://api.stackin.io/api/v1/invoices/dps/$DPS_ID" \
  -H "Authorization: Bearer $STACKIN_API_KEY"

How to retry safely in your code

  1. The key is born with the business event and is stored before the first call, so it survives a restart of your process.
  2. Retry with the same key and the same body on a network failure on your side, a 409 in progress, 429, 503 and 502 with retryable: true, with growing waits between attempts and a cap on attempts.
  3. Stop on OUTCOME_UNKNOWN: flag the order for review, keep document_id and consult later.
  4. Stop on 422: it is a rejection of the data or a reused key, and retrying fails the same way. Fix it first.

Your own HTTP client's timeout falls into the first case. If it fires while Stackin is still processing, a retry with the same key gets 409 until the first call finishes and, after that, the recorded response. With the Python SDK, the loop looks like this:

Safe retry with the Python SDK
Copy
import time

from stackin import (
    APIError,
    ConnectionFailedError,
    DocumentType,
    Invoice,
    RateLimitedError,
)
from stackin.br import Product

invoice = Invoice(api_key="SDK_API_KEY")


class OutcomeUnknown(Exception):
    pass


def issue(order):
    for attempt in range(6):
        try:
            return invoice.issue(
                document_type=DocumentType.NFSE,
                client_name=order.client_name,
                tax_id=order.tax_id,
                items=[Product(description=order.description, unit_price=order.amount)],
                external_reference=order.id,
                idempotency_key=order.idempotency_key,
            )
        except ConnectionFailedError:
            wait = 2 ** attempt
        except RateLimitedError as error:
            wait = error.retry_after or 2 ** attempt
        except APIError as error:
            detail = str(error.detail)
            if "OUTCOME_UNKNOWN" in detail:
                raise OutcomeUnknown(detail) from error
            in_progress = error.status_code == 409 and "still in progress" in detail
            if not in_progress and error.status_code not in (502, 503):
                raise
            wait = 2 ** attempt
        time.sleep(wait)
    raise RuntimeError("authority not answering; try later with the same key")

The SDKs expose the status and the error's detail, where the code appears in parentheses (Authorizer error (OUTCOME_UNKNOWN): …); over plain HTTP, error.code and error.retryable say the same without parsing text. If a duplicate still slips through — issued by two systems with different keys, for instance —, GET /invoices?external_reference=... lists what was issued under your order's reference, and POST /invoices/{access_key}/cancel, also with Idempotency-Key, cancels the extra one within the authority's deadline.

See Idempotency in the API reference, the SDK version and the error codes. On the MCP server, issue_invoice, reissue_invoice and cancel_invoice take idempotency_key for the same reason.