Paul Bădărău

OpenAI API Integration Checklist for Production Apps

A production checklist for OpenAI API features: strict response contracts, validation, failure paths, cost limits, versioned prompts and deploy-time evals.

The request gets 25 seconds to finish before the server drops the connection and tells the user it couldn't analyse their meal. That's the timeout on a food-logging feature I shipped for iPhone and Android, where someone types "chicken wrap, chips and a Coke" or sends a photo, and a Cloudflare Worker calls gpt-4o-mini to return calories, protein, carbohydrates, fat, and an itemised breakdown for the user to review before saving.

Calling the model is the trivial bit. Production work means deciding which outputs the app is allowed to trust, protecting a metered endpoint, keeping slow upstream failures predictable, and accepting that valid JSON isn't the same thing as a correct answer. My own shipped feature still lacks several of those controls, and this checklist is what I check before calling an integration done.

The response has to be a contract before it can be useful

Whenever model output feeds a database, a payment check, a permission rule, or a typed client screen, it needs a strict shape. Both the text and photo routes in my food Worker request strict JSON Schema at temperature 0.3 with extra properties disallowed, which stops chatty preambles, stops carbs drifting into carbohydrates_g, and stops unexpected keys from breaking mobile decoders.

Schema enforcement only checks syntax, not domain truth; it won't tell you whether 1,400 calories makes sense for a side salad, whether the item calories add up to the meal total, or whether the model misidentified a plate of pasta. Right now my Worker relies on the provider's schema check plus manual user review before Save, without an independent server validator, nutritional plausibility bounds, or item-total reconciliation. The next version needs to reject negative macros, flag material mismatches between item sums and totals, and return an editable draft instead of silently trusting numbers that look precise. The same rule applies anywhere else: reject unrecognised ticket categories, cross-check extracted dates and currency amounts against the source document, and put destructive proposals in front of a person.

Define what happens after timeouts and retries

Upstream model APIs get slow, rate-limit callers, throw server errors, and drop connections. My Worker enforces a 25-second timeout and maps upstream rate limits and server errors to 503, while the iOS and Android apps retry retryable failures once after two seconds and surface malformed requests straight to the user. Retry policy is product behaviour: an interactive screen warrants one quick retry, a background report queue wants exponential backoff, and a checkout flow wants none.

Any path that mutates state also needs an idempotency key, a request fingerprint, and enough persisted state to return the original result on reconnect so a mobile retry never creates duplicate entries or invoices. Because my food Worker is stateless and the mobile app saves locally, duplicate writes don't happen yet, though I'd still add a short-window client request ID and hash compressed image bytes so transport retries don't double-bill vision calls. When the network or provider is down, never fabricate a result; keep the user's typed description as an unsaved draft and offer manual entry or a retry later.

Request limits leave other abuse paths open

Before calling OpenAI, the Worker hashes a platform-scoped device ID and enforces daily counters in Cloudflare KV: 100 AI requests a day for attested callers and 10 for unattested callers or the IP fallback, with photos compressed toward 1 MiB JPEG before base64 upload. That caps single-device spend and keeps mobile uploads fast, yet App Attest isn't verified cryptographically in the Worker yet; checking for a non-sentinel header adds friction without proving a genuine device, and per-device caps still leave total monthly spend unbounded.

Production cost control requires four limits working together:

  1. A per-request cap covering input size, output tokens, tools, image count, and model.
  2. An identity cap per user, device, or workspace over a defined window.
  3. A product cap tying heavy model work to paid plans.
  4. A global budget limit that alerts and degrades intentionally when daily or monthly spend hits its ceiling.

My current Worker covers parts of the first two and has zero token telemetry, per-request cost tracking, cache-hit metrics, or global spend caps, leaving production call volume and latency distribution unmeasured. I'd log model, prompt version, route, input class, token counts, duration, status, and estimated cost at the Worker boundary without storing raw meal text or image bytes, and cache only safe, normalised inputs keyed by prompt and model version.

Prompts need versions and changes need evidence

Prompts are production behaviour, so give every prompt a stable identifier such as food-text-v1 and store that version alongside the result, telemetry, and eval runs. My food prompt tells the model to assume standard portions when none are given, which is a product choice you want to trace when a support ticket arrives. Treat model upgrades the same way: before switching because a dashboard promises lower cost or higher intelligence, run your known cases and compare schema validity, domain checks, latency, and cost.

Build a small evaluation corpus of 30 to 50 consented, scrubbed examples covering short inputs, ambiguous portions, mixed meals, regional dishes, prompt-injection attempts, blurry photos, and non-food images. Each case needs clear property assertions: valid JSON, non-negative numbers, rough total reconciliation, honest uncertainty when portions are missing, and the intended failure shape on non-food images. My Worker tests currently cover the health endpoint and malformed request bodies, which proves input validation while leaving model output quality untested; keep metered network calls out of unit tests and run the real eval set as a pre-deploy gate. If the task depends on retrieved source documents instead of prompt tweaks, settle RAG vs fine-tuning first.

Logs should explain a failure without collecting the meal

The food Worker discards meal payloads after responding, leaving the native app to store the accepted description and decoded estimate locally. Server logs should record the request ID, a rotating or hashed caller ID, route, model, prompt version, input class, image size bucket, status class, duration, provider request ID, token usage, and estimated cost, while logging which validation rule failed instead of raw user text.

Never ship API keys to clients, never log plain device IDs or attestation headers, and never mistake an HTTP 200 for an accurate estimate. User edits, rejections, retries, and fallbacks to manual entry are the real quality signals, and until you measure them alongside an offline fallback, domain validator, and global spend cap, the integration isn't finished.