How to avoid buying the same label twice: shipping API idempotency

Shipping API idempotency means a label request can be sent several times and still buy only one label. You get it by tying each purchase to a stable key from your own system, such as a shipment ID, and checking that key before every retry. ExperShip users apply this pattern to prevent duplicate labels.
Key takeaways
- A timeout on a label purchase is ambiguous: the carrier may have issued the label even though your code never saw the response.
- Generate one idempotency key per intended shipment, store it in a table with a unique constraint, and record the label ID the moment it comes back.
- Before retrying, look up the key and reconcile. Never blindly resend a POST that buys a label.
- Every duplicate label draws from your prepaid balance and may need a void, so prevention is cheaper than cleanup.
What is idempotency, and why does it matter for labels?
An operation is idempotent when running it once or ten times leaves the system in the same state. In HTTP terms, GET, PUT and DELETE are defined as idempotent, while POST is not (see RFC 9110 on idempotent methods). Buying a label is almost always a POST, so by default each call creates a new label, a new tracking number and a new charge.
That is fine until the network gets involved. If you are new to the building blocks, start with what a shipping API is and how it works, then see how to create a shipping label with an API. This article covers the failure mode those guides only hint at.
How do duplicate labels actually happen?
Rarely through a bug in the carrier. Almost always through ordinary retry behavior in your own stack. The usual culprits:
- Client timeout. Your HTTP client gives up after 10 seconds. The label was purchased at second 11. Your retry buys a second one.
- Double click. A warehouse operator clicks Buy Label twice on a slow screen.
- At-least-once queues. Most job queues redeliver a message if a worker crashes or does not acknowledge in time. Your job runs twice.
- Webhook redelivery. An order-created webhook from your store arrives twice, and each delivery triggers fulfillment.
- Worker crash after purchase. The label is bought, then the process dies before saving the tracking number. On restart, the job looks unfinished.
- Automatic HTTP retries. Some client libraries and proxies retry on 502, 503 or connection reset without telling you.
The common thread: you cannot tell the difference between "the request never arrived" and "it arrived but I never heard back."
What does a duplicate label cost you?
Each purchase deducts from your prepaid USD balance. The extra label then has to be voided, and void rules differ by carrier: windows, eligibility and refund timing are not uniform, and refunds are not instant. If the duplicate gets scanned or the wrong tracking number goes to a customer, you also have a support problem. For a seller doing 300 orders a day, even a 1% duplicate rate is three wasted labels daily plus the manual work of finding them.
On international shipments the mess is bigger, because each label carries its own customs documents and declared data. Two labels for one parcel can mean two sets of paperwork describing the same goods.
How do you design an idempotent label purchase?
Whether or not the API you call accepts an idempotency header (an IETF draft proposes a standard Idempotency-Key header), you should enforce it on your side. A client-side guard works with any API, including ones that do nothing for you. Check the ExperShip developer documentation for the current request fields before you wire this up.
Step 1: Choose a stable key
The key must identify the intent to ship, not the HTTP attempt. Good: your internal shipment ID plus an attempt generation number, like shp_8841:v1. Bad: a random UUID created inside the retry loop (every retry gets a new one, which defeats the point) or a hash of the rate, which can change between attempts.
Increment the generation (v2) only when a human deliberately re-buys after voiding, for example after an address correction.
Step 2: Store the key with a unique constraint
CREATE TABLE label_purchases (
idempotency_key TEXT PRIMARY KEY,
shipment_id TEXT NOT NULL,
status TEXT NOT NULL, -- pending | purchased | failed | unknown
label_id TEXT,
tracking_number TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);The primary key is your lock. Two workers racing to insert the same key cannot both win.
Step 3: Claim the key before calling the API
async function buyLabel(shipmentId, generation) {
const key = `${shipmentId}:v${generation}`;
// 1. Claim. Returns a row only if we inserted it.
const claimed = await db.query(
`INSERT INTO label_purchases (idempotency_key, shipment_id, status)
VALUES ($1, $2, 'pending')
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING idempotency_key`,
[key, shipmentId]
);
if (claimed.rowCount === 0) {
// Someone already tried. Return or reconcile, never re-buy blindly.
return await resolveExisting(key);
}
// 2. Call the label API (the only line that spends money).
try {
const label = await callLabelApi(shipmentId);
await markPurchased(key, label.id, label.trackingNumber);
return label;
} catch (err) {
if (isDefinitelyRejected(err)) { // 4xx validation error
await markFailed(key);
throw err;
}
await markUnknown(key); // timeout, 5xx, connection reset
throw err;
}
}Step 4: Treat timeouts as unknown, not failed
This is the step most teams get wrong. A 400-level validation error (bad ZIP code, unsupported service) is a definite no, so mark it failed and let the user fix it. A timeout, a 5xx or a dropped connection is an unknown. Do not retry the purchase yet.
Step 5: Reconcile unknowns before any retry
Write resolveExisting so it behaves by status:
- purchased: return the stored label. Done, no API call.
- failed: allow a fresh attempt, either by bumping the generation or flipping the row back to pending under a lock.
- pending (recent): another worker is mid-call. Wait or return "in progress."
- pending (older than, say, 2 minutes) or unknown: query the API for labels matching your shipment reference. If one exists, adopt it. If none exists after a reasonable wait, mark failed and retry.
For step 5 to work, put your shipment ID in the label's reference or order-number field whenever the API offers one. That gives you something to search by later.

Which failure leads to which fix?
| Scenario | What you see | What the guard does |
|---|---|---|
| Client timeout at 10 s | No response, label may exist | Marks unknown, reconciles by reference before retry |
| Operator double click | Two requests, same shipment | Second insert hits the unique key, returns first result |
| Queue redelivers job | Same job runs twice | Second run finds status purchased, skips the API call |
| Duplicate order webhook | Same order ID arrives twice | Shipment is created once per order ID, so the key is stable |
| Crash after purchase, before save | Row stuck in pending | Stale-pending check looks up the label and adopts it |
| Address fixed, deliberate re-buy | Old label voided by a human | Generation bumps to v2, new key, new purchase |
What about retries and backoff?
Retries are good when they are safe. Once purchases sit behind the guard above, you can retry aggressively on reads (rates, tracking, address checks) and cautiously on writes. For label purchases use exponential backoff with jitter, such as waits of 1, 2 and 4 seconds with up to 500 ms of random jitter, and cap attempts at 3 to 5. Set the HTTP timeout generously for the purchase call, since label generation can take longer than a rate quote. Short timeouts create the very ambiguity you are trying to avoid.
Disable any automatic retry in your HTTP client or gateway for the purchase endpoint, so that only your guarded code decides when to resend.
Do webhooks need the same treatment?
Yes. Webhook senders generally retry until they get a 2xx, so you will receive duplicates and out-of-order events. Store each event ID and ignore ones you have processed. Tracking updates are naturally safe to apply twice, but anything that triggers money or inventory (buying a label, sending a customer email) is not. The shipping tracking API and webhooks guide covers delivery mechanics.
How do you test it?
- Kill the worker between the API call and the database write. After restart, confirm exactly one label exists.
- Fire the same job twice in parallel (20 threads works well) and assert a single row and a single purchase.
- Inject latency so the call exceeds your timeout, then confirm the status becomes unknown and reconciliation adopts the label.
- Run a daily audit query that flags any shipment with more than one active label.
SELECT shipment_id, COUNT(*)
FROM label_purchases
WHERE status = 'purchased'
GROUP BY shipment_id
HAVING COUNT(*) > 1;Frequently asked questions
What is an idempotency key in a shipping API?
It is a unique value you attach to a request so the same request, sent more than once, produces one result. For labels, use a stable ID for the shipment you intend to ship, not a fresh random value per attempt.
Is a failed or timed-out label request safe to retry?
Not automatically. A 4xx validation error is safe to fix and resend. A timeout or 5xx is ambiguous, so look up whether a label already exists for that shipment before buying again.
Can I just void duplicate labels afterward?
Sometimes, but void windows and refund timing vary by carrier, and the charge may sit unrefunded for days. Preventing the duplicate is cheaper than chasing refunds.
Does idempotency matter if I only ship a few orders a day?
Yes, though the cost is smaller. Double clicks and a single timeout can still waste a label. The guard is about 30 lines of code and removes the problem for good.
Ship reliably from day one
ExperShip lets you buy, print, track and automate labels across carriers, with the API included on the Growth plan. Start your 30-day free trial (no card needed to sign up) and build the guard above against a real label flow.