Most backend HTTP bugs are reversible. Charge a customer twice and you can issue a refund. Insert a duplicate database row and a unique constraint catches it.
Physical printing is different. Once thermal paper comes out of a Zebra label printer or an Epson kitchen printer, there is no DELETE request. A duplicate shipping label means a warehouse packer sticks two copies on two boxes — or wastes paid carrier postage. A duplicate kitchen receipt means the line cooks prepare the same dish twice during dinner rush. And a silently dropped print job is even worse: an order sits unshipped or unmade until an angry customer calls.
In production cloud printing, almost every duplicate or missing ticket comes from three predictable failure modes. Here is how they happen and how to eliminate them cleanly.
The three ways production print jobs go wrong
1. Network timeout after the server already accepted the job
Your fulfillment service sends POST /v1/print-jobs with a 5-second timeout. The cloud API receives the request, creates the job, and pushes it to the warehouse agent — then the response stalls on a flaky NAT or mobile uplink. Your HTTP client times out and retries. Without idempotency protection, the server sees a brand-new request and prints a second label.
2. Upstream webhook replays (Shopify, Stripe, POS gateways)
E-commerce and POS platforms guarantee at-least-once delivery for order webhooks. If your handler takes a few seconds to generate a PDF and return 200 OK, the platform retries the same orders/paid event. If each webhook handler call submits a print job directly, every slow response produces a duplicate ticket.
3. Offline computers or printers during peak hours
If your backend treats HTTP 201 Created as "the paper came out," you have a blind spot. The computer next to the printer might be asleep, the USB cable unplugged, or the thermal roll jammed. Without subscribing to terminal job states, the order looks printed in your database while nothing ever left the tray.
Step 1: Make every submission idempotent with Idempotency-Key
PrintBase supports the Idempotency-Key header on POST /v1/print-jobs (up to 128 printable ASCII characters without spaces, scoped per organization).
Instead of generating a random UUID inside your retry loop, derive a deterministic key from the business event:
- Shipping label for an order:
order-${orderId}-shipping-label-v1 - Kitchen ticket for an order:
order-${orderId}-kitchen-ticket-v1 - Intentional operator reprint:
order-${orderId}-shipping-label-reprint-${reprintId}
Here is what happens when the same key is sent more than once:
| Scenario | PrintBase response | Quota & paper impact |
|---|---|---|
| First submission succeeds | 201 Created with { id, status: "queued" } | 1 job created, 1 sheet printed |
| Network retry with same key + same payload | Original 201 Created receipt + header Idempotency-Replayed: true | No duplicate job, no extra quota |
| Same key reused with a different payload | 409 Conflict (IDEMPOTENCY_CONFLICT) | Rejected safely; catches key-collision bugs |
| Transaction failed before committing | Error status (5xx / validation error) | Key and quota are not consumed; safe to retry |
One subtle detail worth remembering: idempotency prevents duplicate job creation, not intentional reprints. When a packer genuinely tears a label and clicks "Reprint" in your UI, generate a fresh key (for example, appending an incrementing reprintAttempt or a new UUID stored on your reprint audit row) so the new print is explicitly recorded as a separate logical submission.
Step 2: Retry safely on the backend (Node.js example)
With a deterministic Idempotency-Key, retrying timeouts and 5xx responses becomes safe by construction:
interface SubmitLabelInput {
orderId: string;
printerCode: number;
labelPdfUrl: string;
reprintNumber?: number;
}
export async function submitShippingLabel({
orderId,
printerCode,
labelPdfUrl,
reprintNumber,
}: SubmitLabelInput) {
const idempotencyKey = reprintNumber
? `order-${orderId}-label-reprint-${reprintNumber}`
: `order-${orderId}-label-v1`;
const payload = JSON.stringify({
printer_code: printerCode,
content_type: 'pdf',
content_url: labelPdfUrl,
copies: 1,
});
const maxAttempts = 3;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const response = await fetch('https://api.printbase.cloud/v1/print-jobs', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.PRINTBASE_API_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': idempotencyKey,
},
body: payload,
signal: AbortSignal.timeout(8000),
});
if (response.ok) {
const job = await response.json();
const replayed = response.headers.get('Idempotency-Replayed') === 'true';
return { ...job, replayed };
}
// Do not retry 4xx errors (invalid content, conflict, bad auth)
if (response.status >= 400 && response.status < 500) {
const err = await response.text();
throw new Error(`PrintBase rejected job (${response.status}): ${err}`);
}
} catch (error) {
if (attempt === maxAttempts) throw error;
}
await new Promise((resolve) => setTimeout(resolve, attempt * 1000));
}
}Notice how clean this is: even if Shopify delivers orders/paid twice at the exact same second, both workers compute order-10482-label-v1. The first creates the job; the second receives the original receipt with Idempotency-Replayed: true and stores the exact same job.id without printing a second label.
Step 3: Separate "queued" from "printed" using webhooks
POST /v1/print-jobs returns quickly with { "status": "queued" }. From there, every job moves through a clear state machine:
queued -> dispatched -> printing -> completed
\-> failed (with reason_code)Instead of assuming success on 201 Created or burning API calls polling in a loop, register a PrintBase webhook for print_job.completed and print_job.failed. Every failure event carries a structured data.reason_code so your app can react appropriately:
reason_code | What happened | Recommended action in your app |
|---|---|---|
AGENT_OFFLINE | The store/warehouse PC running the PrintBase Agent lost connectivity | Alert the store dashboard or route to a fallback printer |
PRINTER_OFFLINE | The agent is online, but the USB/network printer is powered off or unplugged | Highlight the specific printer in your UI; hold or reroute the job |
DOWNLOAD_FAILED | The agent could not fetch content_url (expired signed URL, DNS/firewall issue) | Regenerate a fresh signed URL or send base64 content inline with a new key |
PRINT_ERROR | Local OS spooler or driver returned an error | Log diagnostics and surface a one-click "Reprint" button |
INVALID_CONTENT | Malformed PDF or empty payload | Fix template generation; do not blindly auto-retry |
Here is a minimal Express webhook handler that updates your order table and triggers an alert when a printer goes offline:
import crypto from 'node:crypto';
import express from 'express';
const app = express();
function verifySignature(rawBody: string, header: string, secret: string) {
const parts = Object.fromEntries(
header.split(',').map((kv) => kv.split('=') as [string, string])
);
if (!parts.t || !parts.v1) return false;
const expected = crypto
.createHmac('sha256', secret)
.update(`${parts.t}.${rawBody}`)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(parts.v1, 'hex'),
Buffer.from(expected, 'hex')
);
}
app.post(
'/hooks/printbase',
express.raw({ type: 'application/json' }),
async (req, res) => {
const rawBody = req.body.toString('utf8');
const sig = req.header('X-PrintBase-Signature') || '';
const eventId = req.header('X-PrintBase-Event-Id') || '';
if (!verifySignature(rawBody, sig, process.env.PRINTBASE_WEBHOOK_SECRET!)) {
return res.status(401).send('Invalid signature');
}
// Deduplicate webhook deliveries using X-PrintBase-Event-Id
const event = JSON.parse(rawBody);
if (event.type === 'print_job.completed') {
await markOrderPrinted(event.data.job_id);
} else if (event.type === 'print_job.failed') {
await markOrderPrintFailed({
jobId: event.data.job_id,
reasonCode: event.data.reason_code,
printerName: event.data.printer_name,
eventId,
});
}
res.status(200).send('ok');
}
);Production checklist for zero-surprise printing
Before shipping automated printing to a live warehouse or restaurant, run through five quick checks:
- Always send
Idempotency-Keyderived from your order or fulfillment ID — never rely on HTTP retries being duplicate-free by luck. - Use a new key only for intentional reprints, and keep a reprint counter on your order record so support can tell why a second label existed.
- Prefer
printer_codefromGET /v1/printerswhen storing station-to-printer bindings in your database. - Watch
print_job.failedwebhooks and distinguish connectivity errors (AGENT_OFFLINE,PRINTER_OFFLINE) from content errors (DOWNLOAD_FAILED,INVALID_CONTENT). - Test offline recovery before launch: unplug a test thermal printer, fire a job, confirm your UI shows the failure alert, plug it back in, and verify your one-click reprint succeeds cleanly.
Try it in 5 minutes
PrintBase includes a permanent free tier (100 jobs/month, no credit card required) with full Idempotency-Key support, and paid plans start at $8/month with signed webhooks and multi-device support.
- Read the Print Jobs API reference for
Idempotency-Keyand status details - Download the PrintBase Agent for Windows, macOS, or Linux
- Compare tiers on the Pricing page or create a free account
