Paranoid Code
Have you ever heard about “Paranoid code”? I have.
Not from a book or a conference talk. From my first few e-commerce integrations with Shopify, where I connected systems that were never meant to talk to each other… some of them were never meant to talk to anything at all.
All these different systems had one thing in common. There was always a place where a response field marked as “required” was randomly missing.
This taught me something. The best integration code isn’t clean or clever. It’s paranoid. When you can’t 100% rely on any part of the flow, you guard everything. I mean everything.
- That webhook payload? A snapshot from 2 seconds ago. The data already changed.
- That “required” field in response? Optional on Saturday at 2 AM.
- Typed as number? Comes as a string. A float string. Sometimes with
.as a separator, sometimes,. - That enum with 5 values? There’s a 6th one now. They forgot to tell you.
What paranoid code actually looks like
When we map Shopify orders to an ERP, every field gets guarded. Here’s the kind of thinking that goes into price extraction:
// every single field has a fallback — because we've seen them all be null
const amount = parseFloat(presentmentPrice?.amount || "0");
const discount = allocations?.length
? allocations.reduce((sum, a) => sum + parseFloat(a?.amount || "0"), 0)
: 0;
const taxRate = taxLines?.[0]?.rate ?? 0; // tax-exempt orders have no tax lines at all
Three lines of “just get the price” — but each one has a fallback. We’ve seen amount be null, undefined, and an empty string. We’ve seen orders with zero tax lines. We’ve seen allocations show up as an empty array, null, or not exist at all.
And then there’s the ERP’s decimal format — it needs up to 9 decimal places, but no trailing zeros (except minimum 2):
// ERP rejects "49.9" but accepts "49.90". Also rejects "49.900000000". Cool.
function formatForErp(value) {
return value
.toFixed(9) // → "49.900000000"
.replace(/0+$/, "") // → "49.9"
.padEnd(2, "0"); // → "49.90" ← this is what the ERP wants
}
Is this overkill? The ERP rejected our orders until we got this exact format right.
Parsing addresses from the EU VIES service
Here’s one of my favorite paranoid parsers. When you validate a company’s VAT ID against the EU VIES service, it returns their registered address as a single text block. Different formats per country:
SK: "Lipová 12\n94901 Nitra" ← 5-digit zip, no separator
CZ: "Krátká 7\n602 00 Brno" ← 3+2 digit zip with space
PL: "ul. Zielona 33\n30-102 Kraków" ← 2-dash-3 digit zip
Three countries, three zip code formats, sometimes with extra lines for country name. Here’s the approach:
// detect which line has the postal code — because each country formats it differently
function findPostalCodeLine(lines) {
for (let i = 1; i < lines.length; i++) {
if (/^\d[\d\s-]{2,8}\d\s+/.test(lines[i])) return i; // matches SK, CZ, PL formats
}
return lines.length >= 2 ? 1 : -1; // fallback: assume line 2
}
// "Hlavná 1035/26" → { street: "Hlavná", number: "1035/26" }
// that /26 is common in CZ/SK addresses — without the [\w/]* you lose half the number
function parseStreet(line) {
const match = line.match(/^(.+?)\s+(\d+[\w/]*)$/);
return match ? { street: match[1], number: match[2] } : { street: line, number: "" };
}
The VAT ID that hides in event messages
Shopify doesn’t have a dedicated VAT ID field. When a B2B customer with tax exemption places an order, the VAT ID shows up in the order’s event messages. So we have to mine it out:
// primary: clean IDs like "SK2012345678"
const PRIMARY = /\b(SK|CZ|PL)\d{8,12}\b/i;
// fallback: messy ones like "SK 2012345678" or "CZ-12345678"
const FALLBACK = /\b(SK|CZ|PL)[\s-]?(\d{8,12})\b/i;
function findVatId(eventMessages) {
for (const message of eventMessages) {
const match = message.match(PRIMARY) || message.match(FALLBACK);
if (match) return normalizeVatId(match);
}
return null; // no VAT ID found in any message
}
Two regexes — primary for clean IDs, fallback for ones with spaces or dashes. We iterate through all event messages because the VAT ID could be in any of them. This runs on every B2B order.
The response that won’t unwrap
One of the ERPs we integrate with has… character. When you ask for a list of items, sometimes you get an array. Sometimes you get an object wrapping an array. Sometimes it’s nested two levels deep. Same endpoint, different days.
// the ERP wraps arrays differently depending on... the phase of the moon?
function findArraySomewhere(response) {
if (Array.isArray(response)) return response;
for (const val of Object.values(response)) {
if (Array.isArray(val)) return val; // { items: [...] }
if (typeof val === "object" && val !== null) {
for (const inner of Object.values(val)) {
if (Array.isArray(inner)) return inner; // { data: { items: [...] } }
}
}
}
log.error("no array found in response, giving up");
return [];
}
Similarly, for SOAP responses, XML parsers return a single item as an object but multiple items as an array. So every SOAP response gets normalized:
// XML parser returns 1 item as object, 2+ as array. Thanks.
function normalize(items) {
if (!items) return [];
return Array.isArray(items) ? items : [items];
}
Three lines. Prevents crashes on every single SOAP response.
Safe logging in paranoid systems
When something goes wrong (and it will), you need to log it. But logging in integration code is its own minefield: circular references crash your JSON serializer, sensitive tokens end up in logs, and error objects might not be actual Error instances.
// JSON.stringify + circular references = 💥
function safeStringify(obj, maxLength = 500) {
try {
const seen = new WeakSet();
const json = JSON.stringify(obj, (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) return "[Circular]";
seen.add(value);
}
return value;
});
return json.slice(0, maxLength);
} catch {
return "[Unserializable]";
}
}
// catch(error) — but what IS error, really?
function getErrorMessage(error) {
if (error instanceof Error) return error.message;
if (typeof error === "string") return error;
try { return JSON.stringify(error); } catch {}
return String(error); // last resort
}
Four fallback levels for extracting an error message. Because in integration code, the catch block receives unknown — and it really is unknown.
The rules I follow
After enough of these, I’ve settled on a few principles:
- Never trust the type. Parse everything. A “number” field will eventually be a string.
- Never trust presence. A “required” field will eventually be missing.
- Fail gracefully, never silently. If something is wrong, log it loudly and continue if possible.
- Make everything idempotent. The same payload processed twice should produce the same result.
- Always have a reconciliation job. Something will slip through. Have a way to catch it.
The thing is, in e-commerce there’s a lot of good software. And then there’s software that has… character. The kind where you find patterns that don’t exist anywhere else.
Most integration bugs don’t come from bad logic. They come from trusting systems that had different assumptions than you did. The paranoid code is the code that survives.