
CFDI Stamping API Integration: Architecture That Survives PAC Failures
A CFDI stamping API integration looks simple on a whiteboard: build the XML, sign it, send it to your PAC, store the UUID that comes back. In production it is a distributed system with an external dependency you do not control, a legal document at the end of it, and failure modes that cost real money: duplicate invoices, orders with no invoice, and cancellations stuck halfway. This article is about the engineering behind that call — data model, idempotency, queues, error handling, security and testing — and the trade-offs between the common approaches. If you are looking for the operational year-end checklist instead, read our guide on how to prepare your billing system for the 2027 CFDI changes.
Context: what 2027 does and does not change
According to a bulletin from the PAC SW Sapien, the 2027 tax package was published in the Diario Oficial de la Federación on November 13, most of its changes apply from January 1, 2027, and no new CFDI version or new complements were announced. The same bulletin notes that RESICO now admits individuals with income up to 5 million pesos and companies up to 50 million pesos.
For engineers, that is the useful signal: the XML schema is not your main risk this year. Your risk is the integration itself — and data that changes underneath it, such as customers moving to a different tax regime. Both are architecture problems, not template problems.
Why CFDI stamping API integrations fail in production
Most broken integrations share the same shape:
- The stamp call runs inside the checkout request. The customer waits on your PAC. If the PAC is slow, your checkout is slow; if it is down, you either block sales or silently skip invoices.
- Timeouts are treated as failures. A timeout does not mean the PAC did not stamp. It means you do not know. Retrying blindly is how duplicate CFDIs are born.
- The invoice row is mutable. Teams overwrite the customer's RFC, name or postal code on the same record that was already stamped, and lose the ability to explain what was actually sent.
- Errors are a single bucket. A validation error that will fail forever gets retried every minute, while a transient network error gets marked as final.
- Cancellation is an afterthought. It is implemented as a boolean flag instead of a process with its own states.
Each of these has a well-known fix. None of them requires a new framework.
A data model that separates intent from result
Keep three concepts apart: the business document (what you want to invoice), each attempt to stamp it, and the stamped result. The stamped result is immutable.
CREATE TABLE invoice (
id UUID PRIMARY KEY,
order_id UUID NOT NULL,
series TEXT NOT NULL,
folio BIGINT NOT NULL,
idempotency_key TEXT NOT NULL UNIQUE, -- deterministic, see below
receiver_snapshot JSONB NOT NULL, -- RFC, name, regime, ZIP, CFDI use as sent
payload_hash TEXT NOT NULL, -- hash of the canonical pre-stamp XML
status TEXT NOT NULL, -- draft|queued|stamping|stamped|failed|unknown|cancel_requested|cancelled
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (series, folio)
);
CREATE TABLE stamp_attempt (
id UUID PRIMARY KEY,
invoice_id UUID NOT NULL REFERENCES invoice(id),
started_at TIMESTAMPTZ NOT NULL,
finished_at TIMESTAMPTZ,
outcome TEXT, -- ok|validation_error|transient_error|timeout
pac_code TEXT,
pac_message TEXT
);
CREATE TABLE stamped_cfdi (
invoice_id UUID PRIMARY KEY REFERENCES invoice(id),
uuid TEXT NOT NULL UNIQUE, -- folio fiscal
xml_object_key TEXT NOT NULL, -- write-once storage
xml_sha256 TEXT NOT NULL,
stamped_at TIMESTAMPTZ NOT NULL
);
Three details matter here. The receiver_snapshot freezes the customer's tax data at the moment of issuing, so later edits to the customer profile never rewrite history. The UNIQUE (series, folio) constraint makes it physically impossible for your own code to assign the same folio twice. And attempts live in their own table, so support can answer "what happened to this invoice?" without reading logs.
Idempotency: the timeout problem
The hardest case is the one where you sent the request and never got a response. The PAC may have stamped the document or not. The safe rule: an unknown outcome is a state, not an error.
def stamp(invoice_id):
inv = lock_invoice(invoice_id) # SELECT ... FOR UPDATE
if inv.status in ("stamped", "cancelled"):
return # already done, no-op
if inv.status == "unknown":
found = pac.find_by_reference(inv.idempotency_key, inv.series, inv.folio)
if found:
return persist_stamped(inv, found) # recover, do not re-send
# only re-send when your PAC guarantees the lookup is authoritative
attempt = start_attempt(inv)
try:
result = pac.stamp(signed_xml(inv), timeout=REQUEST_TIMEOUT)
persist_stamped(inv, result) # same transaction as status change
except PacValidationError as e:
finish(attempt, "validation_error", e)
set_status(inv, "failed") # needs a human or a data fix
except (Timeout, ConnectionReset) as e:
finish(attempt, "timeout", e)
set_status(inv, "unknown") # reconcile before any retry
except PacTransientError as e:
finish(attempt, "transient_error", e)
set_status(inv, "queued") # retry with backoff
How you implement find_by_reference depends on your provider. Some PACs return the previously stamped document when they receive the same XML again; others expose a query by your own reference. Read your PAC's documentation for exactly this behavior before you write retry logic — it is the single most important question to ask a provider. The idempotency key itself should be deterministic, for example derived from the order ID plus the document type, so a second worker processing the same order computes the same key and hits the unique constraint instead of creating a second invoice.
Queues and the outbox pattern
Take stamping out of the request path. When an order is paid, write the invoice row and an outbox event in the same database transaction; a worker picks up the event and stamps.
[checkout] --tx--> invoice(status=queued) + outbox(event=stamp_requested)
|
outbox relay
v
queue: cfdi.stamp --> worker --> PAC
| |
retry w/ backoff stamped_cfdi + email/PDF
|
dead-letter queue --> ops dashboard
The outbox guarantees you never have a paid order whose stamp request was lost because the message broker was unavailable at the wrong millisecond. The trade-off is latency: the customer gets the invoice seconds later instead of in the checkout response. For most B2B and e-commerce flows that is acceptable; if your business requires the invoice on screen immediately, keep a synchronous attempt with a short timeout and fall back to the queue on any non-success.
Retries should use exponential backoff with jitter and a ceiling, and they should apply only to transient errors. After the ceiling, move the message to a dead-letter queue that a person actually looks at.
Classify errors before you retry
Map every PAC response to one of four classes and store the class, not only the message:
- Validation (permanent). The document is wrong: receiver data that does not match, an invalid catalog key, inconsistent totals. Never retry automatically. Route to the team or the customer who can fix the data, then create a corrected document.
- Transient. Network errors, rate limiting, temporary unavailability. Retry with backoff.
- Unknown. Timeouts and dropped connections after the request was sent. Reconcile first, retry only if reconciliation proves nothing was stamped.
- Configuration. Expired or wrong credentials, certificate problems. Stop the whole queue and alert; retrying each invoice only floods your logs.
Keep the mapping table of PAC codes in configuration, versioned, with tests. Providers add and change codes, and you want that update to be a reviewed change, not a hotfix.
Receiver data and catalogs are versioned data
Changes like the RESICO expansion described in the 2027 package bulletin mean some of your customers may change tax regime. Treat receiver tax data as something with a validity period:
- Store the customer's tax profile with
valid_fromand the source (customer form, uploaded tax certificate, manual edit by staff). - Validate the profile when it changes, not only when an invoice is issued, so the error reaches the person who can fix it.
- Copy the profile into
receiver_snapshotwhen the invoice is created. - Load SAT catalogs (tax regimes, CFDI uses, payment forms, product keys) as versioned tables with a loader job, instead of hardcoded enums in application code.
Cancellation is its own workflow
Model cancellation as a separate process with its own states (cancel_requested, cancel_pending, cancelled, cancel_rejected), its own attempts table and its own reconciliation job. Cancellation is not always immediate, so a polling job that asks the PAC for the current status is part of the design, not a workaround. Always record the reason and, when a substitute document exists, the link between the two UUIDs. Never delete the original XML.
Security: certificates, keys and credentials
- The CSD private key and its password belong in a secrets manager or KMS, never in the repository, environment files on developer laptops, or the database in plain text.
- Restrict the signing step to one service with a narrow identity. The rest of the system asks that service to sign; it never reads the key.
- Scrub logs: XML payloads contain RFCs, names and amounts. Log the invoice ID and hash, not the document.
- Store stamped XML in write-once (object-lock or equivalent) storage and keep the SHA-256 in the database to detect tampering.
- Track certificate expiry dates and alert well before they arrive; an expired certificate turns every invoice into a configuration error at once.
Testing against a PAC you do not control
- Use your PAC's test environment in CI for a small contract suite: one valid invoice, one known validation error, one cancellation.
- Wrap the PAC client behind an interface and build a fake that can simulate slow responses, timeouts after success, and duplicate submissions. The "timeout after success" case is the one that finds real bugs.
- Run a daily reconciliation job comparing your
stamped_cfditable with what your PAC reports for the same period, and alert on any difference.
Trade-offs worth deciding explicitly
- Single PAC vs. failover to a second PAC. A second provider improves availability, but switching after an unknown outcome can produce the same document stamped twice. Only fail over on errors that prove the first PAC did not stamp.
- Build vs. buy the invoicing layer. A billing SaaS removes this work but constrains your data model and workflows. Building it makes sense when invoicing is tied to complex flows — marketplaces, subscriptions or a network marketing platform where store orders, returns and distributor payouts all touch billing.
- Sync vs. async. Async is more reliable; sync is simpler for the user. A hybrid with a short timeout and queue fallback is usually the right middle ground.
Implementation checklist
- Stamping runs from a worker, fed by an outbox written in the same transaction as the order.
- Deterministic idempotency key with a unique constraint;
UNIQUE (series, folio). - An
unknownstatus and a reconciliation path for timeouts. - PAC error codes mapped to validation, transient, unknown and configuration.
- Backoff with jitter, a retry ceiling and a monitored dead-letter queue.
- Receiver tax data snapshotted per invoice; profiles versioned.
- SAT catalogs loaded as versioned data.
- Cancellation modeled as a workflow with status polling.
- CSD keys in a secrets manager; signing isolated; XML never logged.
- Write-once XML storage with stored hashes; daily reconciliation with the PAC.
Common mistakes
- Retrying on timeout without checking whether the document was already stamped.
- Generating the PDF or sending the email before the UUID is persisted.
- Reusing a folio after a failed attempt without knowing whether the attempt really failed.
- Editing a stamped invoice in place instead of issuing a corrected document.
- Treating the PAC's test environment as proof of production behavior, including response times.
If your current billing code has grown around these problems, it is often cheaper to rebuild the stamping layer as a small, well-tested service than to patch it again. That is the kind of work our team does in custom software development.
Frequently asked questions
Should I call the PAC synchronously during checkout?
Only with a short timeout and an automatic fallback to a queue. The checkout should never fail because the PAC is slow, and a timeout must leave the invoice in an unknown state, not failed.
How do I avoid duplicate CFDIs when a request times out?
Use a deterministic idempotency key, a unique constraint on series and folio, and reconcile with your PAC before any retry. Confirm in your provider's documentation how it handles a resubmitted document.
Does the 2027 tax package require a new CFDI version?
According to the SW Sapien bulletin, no new CFDI version or new complements were announced. Data changes, such as customers switching to RESICO, still need to flow correctly through your system.
Comments
No comments yet. Be the first to share what you think.


