Exponential retries
API calls can fail for transient reasons: network timeout, rate limit (429), or an isolated upstream 5xx. The recommended strategy is to retry with exponential backoff + jitter, always reusing the same Idempotency-Key so a retry that did reach the server doesn’t generate a duplicate document.
Full implementation for Node.js with axios. Note that 4xx errors other than 429 aren’t retried: they indicate a problem with the request that no retry can fix.
import axios from 'axios';
async function emitirRobusta(facturaData) {
const idempotencyKey = crypto.randomUUID();
const maxReintentos = 5;
for (let intento = 0; intento < maxReintentos; intento++) {
try {
const { data } = await axios.post(
'https://api.pos.lxsyscr.com/api/v1/facturas',
facturaData,
{
headers: {
'X-Api-Key': process.env.LXS_API_KEY,
'Content-Type': 'application/json',
'Idempotency-Key': idempotencyKey
},
timeout: 30000
}
);
return data;
} catch (err) {
const status = err.response?.status;
// Final errors: do not retry
if (status >= 400 && status < 500 && status !== 429) {
throw err;
}
// Last attempt
if (intento === maxReintentos - 1) throw err;
// Backoff
const retryAfter = err.response?.headers['retry-after'];
const waitMs = retryAfter
? parseInt(retryAfter) * 1000
: Math.min(1000 * Math.pow(2, intento), 30000) + Math.random() * 1000;
await new Promise(r => setTimeout(r, waitMs));
}
}
}If the server returns the Retry-After header, it must always be respected: it takes priority over your own backoff calculation. See also error codes and idempotency.