Skip to content

Choosing deterministic code and bounded LLM fallbacks

Choosing deterministic code and bounded LLM fallbacks

Examples were not executed or tested in production.

Original English publication date: 2026-06-14T21:22:34.641+03:00 — Original English article

Welcome back to The Useful Byte at sysseder.com. AI tools can create pressure to route every task through a model, from database queries to CSS and business rules. Rather than claim a current consensus on Hacker News, TechCrunch or team Slack channels, let’s evaluate that architectural choice on its merits.

Not every problem needs generative AI. That is an engineering observation, not evidence that the industry has reached a particular stage of a hype cycle. Measure whether a model improves the actual task enough to justify its dependencies.

We will compare the latency, cost and correctness considerations of model-based extraction with a deliberately narrow deterministic parser. No survey of leading teams or benchmark is supplied; the examples below are proposals, not measured deployments.

The Hidden Tax of the "AI Everywhere" Architecture

A model can be considered for messy text parsing, support-ticket classification or extraction from a legacy PDF. Those are distinct tasks, however: layout extraction, semantic interpretation and schema validation have different failure modes, and a model API is not a universal substitute for all three.

Rapid prototyping does not settle production trade-offs. Examine latency, total cost, output variability and the consequences of wrong answers.

1. The Latency and Throughput Bottleneck

Web systems optimize response time through caching, indexing and smaller bundles. A model call adds inference, network and queueing time, but there is no universal 500 ms–2 s interval or single fastest model. Measure time to first output, total completion time and p50/p95 latency for the chosen workload, including retries, and decide whether streaming or asynchronous processing meets the user’s needs. [2]

2. The Cost of Tokens at Scale

Estimate cost from actual input/output tokens, request volume, retries and the current provider contract. Compare it with the compute, storage, operations and maintenance cost of a deterministic service. Local code is not free, and neither “orders of magnitude” nor “millions for pennies” follows without a workload and price basis.

3. The Nightmare of Non-Determinism

A fixed parser can return the same result for the same input under the same implementation. A low-temperature model call should not be treated as an absolute reproducibility guarantee. Version changes and ambiguous inputs require evaluation. Crucially, invalid output should be rejected by application validation, not allowed to crash a frontend; valid structure also does not prove factual correctness. [1]

An illustrative transaction extraction task

Let's look at a concrete scenario. Suppose you are building an expense tracking app. Users upload a raw string of text (e.g., from an SMS alert or an email receipt), and you need to parse out the amount, the currency, and the merchant.

For a hosted-model implementation, use a currently supported SDK/model and a schema-constrained output mode when available. JSON mode is not tool calling and does not by itself enforce field types. The non-network adapter below makes failure handling explicit; the injected propose function is a deployment-specific interface, not an implemented or tested provider client. It must use a privacy-approved provider and bounded request, token and retry budgets. [1]

type Transaction = {
  amountMinor: string; // Nonnegative integer minor units, not a binary float.
  currency: "USD" | "EUR" | "GBP" | "JPY";
  merchant: string;
};
type ModelReply =
  | { kind: "complete"; value: unknown }
  | { kind: "refusal" | "incomplete" | "error" };
type Propose = (text: string) => Promise<ModelReply>;

function validateCandidate(value: unknown): Transaction | null {
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
  const v = value as Record<string, unknown>;
  if (Object.keys(v).sort().join(",") !== "amountMinor,currency,merchant") return null;
  if (typeof v.amountMinor !== "string") return null;
  const amountMatch = /^(0|[1-9][0-9]{0,11})$/.exec(v.amountMinor);
  if (!amountMatch || amountMatch[0] !== v.amountMinor) return null;
  if (typeof v.currency !== "string" || !["USD", "EUR", "GBP", "JPY"].includes(v.currency)) return null;
  if (typeof v.merchant !== "string" || !v.merchant.trim() || v.merchant.length > 80) return null;
  if (/[\u0000-\u001f\u007f]/.test(v.merchant)) return null;
  return { amountMinor: v.amountMinor,
    currency: v.currency as Transaction["currency"], merchant: v.merchant.trim() };
}

export async function proposeTransaction(rawText: string, propose: Propose) {
  if (rawText.length > 2000) return null;
  try {
    const reply = await propose(rawText);
    return reply.kind === "complete" ? validateCandidate(reply.value) : null;
  } catch {
    return null;
  }
}
// A valid candidate still needs semantic review; do not post it to an account.
// No SDK, API key, provider connection or call was made for this article.

A hosted model introduces provider, connectivity, privacy and cost considerations. The source’s 95% success claim has no dataset behind it. A deterministic alternative can be excellent for a documented format, but cannot honestly claim to solve arbitrary receipts with a few regexes. The example below accepts only “Spent USD 120.50 at Merchant” (or EUR/GBP), and whole-number JPY; everything else returns null for review or an explicitly approved fallback.

// Uses the Transaction type above; requires a TypeScript target supporting BigInt.
export function parseTransactionDeterministic(rawText: string): Transaction | null {
  if (rawText.length > 2000) return null;
  const m = /^Spent (USD|EUR|GBP|JPY) (0|[1-9][0-9]{0,8})(?:\.([0-9]{2}))? at ([^\r\n]{1,80})$/.exec(rawText);
  // JS $ can match before a final newline: require an exact full-string match.
  if (!m || m[0] !== rawText) return null;
  const [, currency, whole, fraction, merchantText] = m;
  if (currency === "JPY" ? fraction !== undefined : fraction === undefined) return null;
  const merchant = merchantText.trim();
  if (!merchant || /[\u0000-\u001f\u007f]/.test(merchant)) return null;
  const amountMinor = currency === "JPY"
    ? BigInt(whole)
    : BigInt(whole) * 100n + BigInt(fraction!);
  return { amountMinor: amountMinor.toString(),
    currency: currency as Transaction["currency"], merchant };
}
// Deliberately rejects ambiguous $/¥ symbols, grouping commas, negative amounts,
// decimal commas, multiple transactions and unknown formats. Not a general receipt parser.

Let's compare the two approaches side-by-side:

  • Latency: compare both implementations on the same representative inputs and hardware/network conditions. Report distributions, failures and retry costs. No 0.05 ms, 300–1000 ms or other benchmark was run here.
  • Cost: a local parser avoids a per-call model charge, but still consumes engineering and computing resources. Compare total cost for the required accuracy and coverage.
  • Security: this pure parser sends no input to a provider and has no model prompt-injection channel. That is not zero overall risk: logs, dependencies, downstream rendering and later fallback calls can leak or misuse data. Escape displayed merchant text and retain access controls. [3]
  • Reliability: determinism helps reproducible testing; it does not prove that extracted values are correct. Test accepted formats, rejections, boundary values, Unicode and malformed input, and evaluate false acceptance separately from coverage. No tests were executed for this example.

The Hybrid "Fallback" Architecture

A hybrid system is one option, not proof of what the “best engineers” use. Deterministic code can handle a narrow accepted grammar, while an LLM may propose interpretations for unstructured inputs when privacy and quality requirements permit. Human review or a clearer input form may be a better fallback.

A proposed hybrid flow separates validation, privacy checks and fallback rather than routing every request to a model:

Incoming request → bounded deterministic parser → accepted result after validation. Unsupported input → privacy and policy check → approved model proposal or human review → semantic validation before use.

In this architecture, when data enters the system:

  1. First apply input limits and the documented deterministic parser.
  2. Return accepted, validated results. A grammar match is not a calibrated confidence score, and no sub-millisecond latency is promised.
  3. For unsupported inputs, choose review, a clearer form or an approved model call. Do not transmit sensitive receipts automatically just because a regex failed. Validate and, where consequences warrant it, review model proposals before use.

The savings depend on the measured fraction of correctly accepted local requests, fallback token usage and operating costs. A 90% reduction in calls would not automatically mean a 90% reduction in total cost. The source provides no evidence for either percentage.

When You SHOULD (and Shouldn't) Reach for AI

To help you navigate architectural decisions at your job or on your side projects, here is a quick rule-of-thumb checklist of when to stick to traditional code versus when to leverage generative AI models.

Prefer deterministic components for

  • Mathematics: use verified calculations for authoritative results. A model can help explain or invoke a calculator, but generated numeric text alone should not become an accounting or control-system result.
  • State management and business logic: Keep your routing, state machines, and business rules inside deterministic code (e.g., database constraints, state libraries).
  • Known-schema mapping: use explicit transformations plus schema validation. Zod can define and validate types and transformations; it does not infer a correct business mapping by itself.
  • Simple search: For searching database fields, use Postgres indexes, full-text search, or Elasticsearch before jumping straight to Vector Databases and semantic embedding models.

Consider AI after evaluation for

  • Semantic search: embeddings or other learned ranking methods can help with conceptual queries such as “cozy winter feelings” in a photo library. This need not involve a generative LLM on every request; evaluate relevance, latency and privacy against simpler search.
  • Creative generation and summarization: Summarizing lengthy articles, generating personalized email drafts, or brainstorming.
  • Translation and classification: models may help translate natural languages or classify support-ticket sentiment. Evaluate language coverage, domain accuracy and harmful misclassification; “dynamic languages” is not the right term for the human languages being translated.

Conclusion

As developers, our ultimate goal is to build reliable, maintainable, cost-effective, and fast software that solves real problems. Sometimes, the most exciting tool in the developer toolkit is not the shiny new LLM—it is a well-optimized SQL index, a robust regular expression, or a carefully designed state machine.

Do not add a model solely to follow a trend. Choose the simplest approach that meets measured requirements, keep consequential rules explicit, and use AI where evaluation shows a useful benefit. This is a design recommendation, not a claim about which teams are most successful.

What about you? Have you had to roll back an "AI feature" in favor of a deterministic solution? Or have you successfully built a hybrid architecture that keeps latency down? Let me know in the comments below!

Until next time, happy coding!

Primary sources checked on 28 October 2026

  1. OpenAI Structured Outputs
  2. OpenAI latency optimization
  3. OWASP prompt injection

Post a Comment

Previous Post Next Post