AI System DesignAI System Design FundamentalsModule 01 — Architecture fundamentals
Choosing Between Traditional Software, Machine Learning, LLMs, and Hybrid Systems
Question 14 of 47 · Updated
On this page
- 1. Start with the task, not the technology
- 2. Compare the four architecture families
- 3. An architectural decision tree
- 4. When conventional software is the correct design
- 5. When classical ML is the better choice
- 6. When an LLM is justified
- 7. Hybrid architecture: separate responsibilities
- 8. Evaluate architectural candidates with hard gates first
- 9. Worked quantitative comparison
- 10. Practical implementation: constrained architecture selection
- 11. Latency, availability and failure domains
- 12. Cost and operational complexity
- 13. Data and model lifecycle trade-offs
- 14. Evaluation must compare the same user task
- 15. Security and responsible architecture selection
- 16. Additional decision-making scenarios
- Scenario A — Invoice total calculation and invoice intake
- Scenario B — Delivery prediction
- Scenario C — Internal policy question answering
- Scenario D — A small business with sparse labeled data
- 17. A practical selection process for architecture reviews
- 18. Common mistakes and interview follow-ups
- 19. Interview-ready summary
- References and research transparency
Choose the simplest architecture that can demonstrably satisfy the required business behavior, data contract, quality, reliability, latency, cost and security constraints. Use conventional software for explicit computations and known rules, classical machine learning for uncertain predictions from representative data, large language models (LLMs) when flexible language understanding or generation adds value, and hybrid architectures when the task combines these capabilities. If no option meets the requirements, collect better evidence, change the permitted scope, or keep the task manual. Do not use AI simply because it is available.
Original curriculum question: How do you decide whether a problem requires traditional software, machine learning, an LLM or a hybrid AI system?
Module 01 — Architecture fundamentals | ASD-001. This lesson is about selecting the architecture of an entire product or workflow, not merely deciding whether a supervised ML problem has enough data. The existing Machine Learning lessons on problem suitability, rule-based programming and defining a target variable are prerequisites. The existing AI System Design interview structure lesson explains how to organize an interview response; here we establish the architectural alternatives and how to make a defensible choice between them. ASD-002 will examine requirements and acceptance criteria in depth, ASD-003 will develop capacity estimates, ASD-006 will cover decision-authority boundaries, and ASD-030 will compare adaptation approaches for AI products. This introductory lesson gives each of those subjects enough context without replacing their specialized treatment.
All example organizations, workload figures, measured-looking values and thresholds below are synthetic teaching assumptions. No actual product benchmark, current vendor pricing or production security certification is claimed.
1. Start with the task, not the technology#
A request such as "add AI to our support system" does not define an engineering problem. Ask what job the user is trying to complete, which inputs are available, which outputs are required, which authority decides whether the result is correct, and what happens if the system makes a mistake.
A support application may contain several qualitatively different tasks:
| Task | Nature of the problem | Plausible architecture |
|---|---|---|
| Verify a signed request and retrieve an order by ID | Explicit identity, authorization and lookup | Conventional software |
| Calculate an amount due from an approved pricing schedule | Exact arithmetic and versioned policy | Conventional software |
| Predict a delivery delay from historical and current operational signals | Uncertain numerical prediction | Classical ML or forecasting |
| Interpret a free-form question about a return policy | Language and contextual interpretation | Search, LLM, or both |
| Draft a response grounded in current order facts and policy | Flexible language with authoritative facts | Hybrid retrieval and generation |
| Approve and execute a refund | Authorized policy decision and transaction | Deterministic service, with review when required |
A single product does not require a single technology for every task. The choice is often per subsystem. Conventional software remains necessary for authentication, storage, concurrency, policy enforcement, monitoring and user interfaces even in an AI-heavy product.
A useful distinction is between what must be true by construction (authorization, arithmetic, contractual invariants), what must be estimated (demand, risk, latency, relevance) and what must be expressed or interpreted (human language, summaries, semantically varied requests). These distinctions are more helpful than sorting projects into an "AI" or "not AI" category.
Also ask whether automation is necessary at all. A low-volume task with severe consequences and no trustworthy way to assess output may be better handled by an authorized person, perhaps with a non-decision-making aid. An unavailable training target does not become a trustworthy target merely by switching to an LLM.
2. Compare the four architecture families#
The terms below describe system design choices rather than disjoint mathematical categories. An LLM is itself a machine-learning model. In this lesson, classical ML denotes narrower predictive models such as logistic regression, gradient-boosted trees, forecasting models and conventional ranking models; a small specialist neural model can serve a similar architectural role. LLM denotes a general-purpose language-model component. Hybrid means an intentional combination of components with different contracts.
| Dimension | Traditional software | Classical ML | LLM application | Hybrid architecture |
|---|---|---|---|---|
| Core computation | Explicit algorithms, queries and rules | Learned statistical mapping | Learned sequence interpretation/generation | Decomposed deterministic and learned tasks |
| Typical output | Exact value or defined state transition | Score, class, estimate, distribution | Text or proposed structured output | Validated result or controlled decision |
| Required evidence | Specification, authoritative input and tests | Representative examples, labels or a defensible learning objective | Representative evaluation set, current facts or other context as needed | Evidence for components plus integration and policy |
| Change mechanism | Modify code, data or rules | Update model, features or training data | Update model, prompt, retrieval or orchestration | Version and coordinate compatible components |
| Main failure modes | Bugs, stale rules, inconsistent state | Distribution shift, leakage, poor calibration | Unsupported claims, instruction attacks, inconsistent output | Component failures plus integration, routing and authority errors |
| Typical costs | Development, operations, databases, rule maintenance | Data/labeling, training, feature and model serving | Model calls or accelerator infrastructure, context, validation | Combined costs and coordination overhead |
| Best starting point | Stable, specified logic | Repeated prediction with measurable outcomes | Language-rich tasks requiring flexibility | Mixed requirements that cannot be satisfied by one approach |
These are tendencies, not guarantees. Conventional programs can have serious bugs and probabilistic algorithms. A learned model can run deterministically for fixed inputs, weights and runtime configuration. Deterministic decoding does not ensure truth, robustness or exactness. A rules service can be expensive if its policy evolves constantly; a small learned model can be cheap to operate at scale. Compare the actual proposed implementations.
3. An architectural decision tree#
The tree organizes questions; it is not a universal classifier. For instance, a language problem may be solved by a curated search index or a small supervised intent classifier without a generative model. An optimization solver may be appropriate even when the output is a complex schedule. A hybrid candidate can be evaluated from the start if the problem already contains clear heterogeneous subtasks.
A technology label does not determine permission to ship. Every alternative must be measured against the same defined use case, and a security or policy failure cannot be offset by a higher average quality score.
4. When conventional software is the correct design#
Prefer explicit logic when authoritative facts and the mapping from inputs to outputs can be specified reliably. Examples include account permission checks, tax calculations under an approved versioned policy, parsing a well-defined file format, joining records by canonical identifiers, sorting, exact catalog lookup, and checking that an operation respects an inventory constraint.
A traditional architecture might use a web API, database transaction, deterministic calculation and a versioned policy module. It still needs unit tests, integration tests, input validation, observability and failure handling.
Some problems appear intelligent but are fundamentally search or optimization. Finding an exact SKU is usually an index lookup. Finding a shortest route over known nonnegative edge weights can use a graph algorithm. Creating an inventory schedule under known capacity constraints can use a mathematical optimization solver. ML may improve uncertain inputs to these algorithms, but that does not mean the solver should be replaced by a language model.
The benefit is a clear contract: given authoritative input and a defined policy version, the expected result can be checked. The drawback is the effort required to encode and maintain rules for complex, evolving or ambiguous inputs.
Signs that a rules-only design is becoming unsuitable include a large exception tree that cannot be reliably maintained, substantial errors on naturally varied inputs, or an underlying unknown quantity that explicit rules can only approximate poorly. Measure that failure rather than assuming rules are inherently brittle.
5. When classical ML is the better choice#
Choose a narrow model when a repeated task involves estimating a quantity or pattern that is not fully specified but can be evaluated using appropriate observations. Examples include predicting delivery delays, forecasting demand, identifying likely equipment failure, and ranking items by measured relevance.
Start with a non-learning baseline or a simple model. For tabular prediction, linear or logistic regression and gradient-boosted trees are strong candidates. For seasonal forecasting, compare simple seasonal baselines with more sophisticated models. The architecture should not require a general-purpose generative model merely because the model needs to generalize.
A classical prediction service typically has a data/label pipeline, versioned feature definitions, training and validation, a model artifact, an inference interface and feedback monitoring. The learned output is an estimate with known evaluation limitations, not authoritative ground truth.
Data readiness involves more than row count:
- A defined target and prediction timestamp.
- Representative coverage of the actual deployment population and important failure cases.
- Historical inputs that would really be available when making a prediction.
- Label quality, delay, selection bias and appropriate permission to use the data.
- A temporal or otherwise valid evaluation design that tests generalization.
- A feedback path to detect performance degradation.
For an inventory forecast, daily sales are not always true demand because stockouts suppress observed sales. For a delivery estimate, excluding every cancelled delivery may bias evaluation. For classification, accuracy can be misleading when the positive class is rare.
If these issues cannot be addressed, the correct choice may be a simpler baseline with explicitly limited capability. Unsupervised models may identify unusual patterns without labels, but their operational usefulness still needs validation. "No labels" is not a reason to skip evaluation.
6. When an LLM is justified#
An LLM can be a useful component when the input or desired output is naturally expressed in diverse human language. Examples include interpreting free-form requests, extracting fields from varied documents, transforming text under an explicit contract, drafting a response and synthesizing evidence.
Before choosing an LLM, test whether exact search, templating, a finite grammar or a smaller language classifier solves the task. For a fixed set of ten intent labels, a narrow classifier may be more economical and easier to validate. For open-ended questions requiring nuanced explanation, an LLM may provide a material benefit.
A pretrained LLM can often begin with prompting or a small set of examples without training a new model. It still needs a representative evaluation set, suitable context and operational controls. Model training data is not an authoritative current business database. If answers depend on current order state or a versioned policy, retrieve or query the approved source at execution time.
Structured generation makes output easier to consume, but valid JSON does not establish that its values are correct. Independently validate required fields, types, ranges and business semantics. Where evidence is required, ensure citations point to actual applicable source passages and the claims are supported.
Model output, retrieved documents and user-provided text should all be treated as untrusted inputs at the appropriate boundaries. Do not give a model unrestricted access to credentials, databases or privileged operations. If a model proposes an action, validate it against current authority, policy and the user's intent. A model's assertion that an operation is approved is not approval.
A model may return unsupported statements, refuse a legitimate request, fail on uncommon languages, time out or produce contradictory structured fields. Define abstention, review or a deterministic fallback for these cases. It is not sufficient to prompt the model to be correct and trust every answer.
7. Hybrid architecture: separate responsibilities#
Most mature AI applications combine conventional services and learned components, but the term hybrid is meaningful only if the architecture makes the boundary explicit. A model should perform a bounded interpretation or estimation task. An authoritative service should own verified facts and state changes.
Consider a fictional support assistant that answers return-policy questions, predicts delivery delays and optionally helps the customer request a refund.
Notice the different contracts:
- The order service owns the order facts and authorization boundary.
- The delay model predicts an uncertain outcome, with an as-of time and an evaluated reliability profile.
- The language model may draft a response using evidence; it cannot invent an order state.
- The refund policy independently determines what actions are allowed, and the transaction service commits an authorized change.
- Human review handles ambiguous, unsupported or exceptional cases as permitted by policy.
If an LLM times out, exact order lookup can still operate. If the model predicting delays is unavailable, show the last verified operational status rather than a fabricated estimate. If the policy source is unavailable, do not invent eligibility for a refund. A well-designed hybrid therefore provides narrower failure domains and explicit degraded modes, although its additional components introduce integration complexity.
The architecture also illustrates why a hybrid is not always better. If the application only needs to retrieve an order by ID and calculate a fixed refund, adding language and prediction services increases cost and risk without solving a new task.
8. Evaluate architectural candidates with hard gates first#
Make the decision as a constrained comparison, not a popularity vote or a weighted score in which safety can be traded away.
First define what each candidate must do. Use one common task population, an agreed evaluation window, a realistic input mix and an independent source of expected outcomes. Include manual escalation and abstention outcomes in the denominator. If a system only handles easy tasks, report both its coverage and its conditional quality; do not claim 100% success on all work based on the subset it chose to answer.
Example hard gates for a fictional service:
| Gate | Question to ask |
|---|---|
| Functionality | Can the candidate perform the required user tasks with the right output contract? |
| Correctness | Does an independently measured conservative success estimate meet the minimum? |
| Safety and security | Are authorization, data handling and high-severity failure controls acceptable? |
| Latency | Does measured end-to-end latency meet the workload-specific target? |
| Cost | Does expected total cost stay within the approved budget? |
| Operational readiness | Can the team monitor, own, maintain and recover the design? |
Only compare the softer trade-offs after eliminating infeasible options. Typical objectives include minimizing cost per successful task, minimizing long-term maintenance effort, reducing latency, and preserving flexibility. A more sophisticated candidate can be preferable if it meaningfully improves outcomes within the constraints, but complexity should have a demonstrated purpose.
Confidence intervals, uncertainty in performance and cohort-specific behavior matter. A success point estimate just above the threshold may not justify production promotion if the evaluation is too small. Use appropriate statistical intervals for the sampling design; clustered users or sessions may require clustered analysis. Check high-severity error slices separately instead of relying only on an overall average.
If no candidate passes, revise the solution's scope, route difficult cases to an approved human workflow, improve data or renegotiate a legitimate business constraint. Do not silently loosen security or policy gates.
9. Worked quantitative comparison#
Imagine an invented task-routing service that receives support requests. All four alternatives are assumed to have been evaluated on the same representative workload with equivalent task definitions. The values below are fabricated examples of the inputs a design review might collect; they are not benchmark results and the lower bounds are supplied rather than statistically estimated here.
| Candidate | Success estimate | Conservative lower bound | End-to-end p95 | Cost per offered task | Controls |
|---|---|---|---|---|---|
| Rules-only | 91% | 89% | 20 ms | $0.002 | Pass |
| Narrow ML | 96% | 95% | 80 ms | $0.008 | Pass |
| LLM-centered | 98% | 96% | 900 ms | $0.040 | Pass |
| Hybrid | 98% | 97% | 140 ms | $0.012 | Pass |
Suppose the minimum conservative success bound is 95%, maximum p95 latency is 200 ms, and maximum cost per offered task is $0.02. Rules-only fails quality. The LLM-centered candidate fails latency and cost. Narrow ML and hybrid pass. If minimizing expected cost per successful task is the agreed objective, divide expected cost per offered task by the estimated probability of a successful task.
For narrow ML: $0.008 / 0.96 = approximately $0.00833 per successful task.
For hybrid: $0.012 / 0.98 = approximately $0.01224 per successful task.
Narrow ML wins under these assumptions. At a stricter minimum success lower bound of 97%, the hybrid becomes the only feasible choice. At a requirement of 99%, no candidate qualifies. The result changes with evidence and constraints, not with enthusiasm for one technology.
The example assumes all four options can produce the required type of result; if free-form grounded drafting is mandatory and the narrow classifier cannot produce it, that candidate fails the functionality gate regardless of its cost. The table's control flag is also only an assumed independently determined gate, not proof that the candidates are secure.
10. Practical implementation: constrained architecture selection#
The following Python example models a design-review decision rather than a runtime router or a trained AI model. It accepts already measured candidate outcomes and independently reviewed controls. It chooses the feasible candidate with the lowest expected cost per success, using latency and stable name as tie-breakers. The function does not estimate confidence intervals, run a security assessment or benchmark any model. It assumes the candidates have already passed the same functional-contract review.
PYTHONfrom dataclasses import dataclass, replace from math import isfinite @dataclass(frozen=True) class Candidate: name: str success: float # task success estimate per offered task lower_bound: float # validated lower confidence bound p95_ms: float # measured end-to-end percentile cost: float # expected total cost per offered task controls_pass: bool # independent policy/security review def choose(candidates, min_success, max_p95, max_cost): if not all(map(isfinite, (min_success, max_p95, max_cost))): raise ValueError('nonfinite requirements') if not 0 < min_success <= 1 or max_p95 <= 0 or max_cost < 0: raise ValueError('invalid requirements') feasible = [] seen = set() for c in candidates: if c.name in seen: raise ValueError('duplicate candidate') seen.add(c.name) if not all(map(isfinite, (c.success, c.lower_bound, c.p95_ms, c.cost))): raise ValueError('nonfinite measurement') if not 0 <= c.lower_bound <= c.success <= 1 or c.p95_ms < 0 or c.cost < 0: raise ValueError('invalid measurement') if (c.controls_pass and c.lower_bound >= min_success and c.p95_ms <= max_p95 and c.cost <= max_cost): feasible.append(c) return min(feasible, key=lambda c: (c.cost / c.success, c.p95_ms, c.name), default=None) rules = Candidate('rules', .91, .89, 20, .002, True) ml = Candidate('ml', .96, .95, 80, .008, True) llm = Candidate('llm', .98, .96, 900, .04, True) hybrid = Candidate('hybrid', .98, .97, 140, .012, True) rows = [rules, ml, llm, hybrid] assert choose(rows, .95, 200, .02) == ml assert choose(rows, .97, 200, .02) == hybrid assert choose(rows, .85, 200, .02) == rules assert choose(rows, .99, 200, .02) is None assert choose([replace(ml, controls_pass=False)], .95, 200, .02) is None assert choose([ml], .95, 80, .008) == ml assert choose([llm], .95, 200, .1) is None assert choose([hybrid], .95, 200, .01) is None assert choose([], .95, 200, .02) is None assert choose([replace(ml, name='z'), ml], .95, 200, .02) == ml for fn in [lambda: choose(rows, 0, 200, .02), lambda: choose([replace(ml, lower_bound=.99)], .95, 200, .02), lambda: choose([replace(ml, p95_ms=float('nan'))], .95, 200, .02), lambda: choose([ml, ml], .95, 200, .02)]: try: fn() except ValueError: pass else: raise AssertionError('invalid input accepted') print('14 checks passed')
Observed local execution with Python 3.13.5:
14 checks passedTen direct assertions check normal selection, increased and decreased quality requirements, no feasible option, failed controls, exact constraint boundaries, latency/cost rejection, empty input and deterministic tie-breaking. Four additional checks verify invalid requirements, inconsistent confidence bounds, nonfinite measurements and duplicate candidate rejection.
For N candidate architectures the function scans them once and selects the minimum feasible result, giving O(N) time and O(N) auxiliary space for names and feasible candidates. Because the minimum success requirement is strictly positive and the lower bound cannot exceed the point estimate, division by zero cannot occur for a feasible candidate.
The code uses floats for illustrative evaluation metrics and costs. Use appropriate currency units or decimal accounting for actual financial transactions. Real decisions may require several simultaneous cohort gates, maximum tolerated severe-error rates, service availability, uncertainty analysis and human approval. Those must be represented explicitly rather than buried in a single boolean if they affect the decision.
11. Latency, availability and failure domains#
A task requiring an immediate response cannot be designed solely around average inference time. Measure the entire request path: input validation, authorization, feature or evidence retrieval, model execution, output validation, network transfer, queue delay and any mandatory approval. Distinguish interactive latency from the total duration of a background workflow.
A direct SQL query or deterministic calculation may be appropriate when a strict low-latency result must be returned. A narrow model can often serve a bounded score quickly if feature assembly is efficient. LLM calls can involve context transfer, prefill, decoding and provider variability; measure time to first token and completion time separately when streaming. Streaming can improve perceived responsiveness without reducing total completion time.
A hybrid can run independent tasks in parallel or route only appropriate requests to expensive components. It can also become slower if every request passes through retrieval, several models, a validator and a tool. Choose the actual critical path rather than assuming hybrid implies lower latency.
A simple illustration: if 80% of requests use a 40 ms path and 20% use an 800 ms path, the mean is 192 ms, yet the p95 is 800 ms in this idealized two-value distribution. Average latency hides a slow path. Do not calculate p95 by averaging component p95 values, and do not treat streaming first-token latency as task completion.
For availability, if two mandatory serial services each have independent 99.9% availability, the idealized combined availability is 0.999 × 0.999 = 0.998001, or 99.8001%. Shared dependencies and correlated outages can make this independence assumption invalid. Optional components, local fallbacks and resilient dependency contracts can reduce the impact, but benchmark and test the actual end-to-end service.
| Failure | Design response |
|---|---|
| Rules are outdated or inputs are inconsistent | Stop the affected decision, identify applicable version, reconcile authoritative data |
| ML service or features unavailable | Use an approved baseline or label the estimate unavailable |
| LLM output invalid or unsupported | Reject it, retry only within a budget, abstain or request review |
| Retrieval source unavailable | Avoid unsupported claims; provide only verified available information |
| Authorization service unavailable | Fail closed for protected operations |
| Hybrid dependency partially fails | Preserve safe unaffected functions; reconcile side effects before retry |
Reliability is not just uptime. A system that returns an incorrect authorization or fabricated record with HTTP 200 has failed its task.
12. Cost and operational complexity#
Evaluate total cost over a realistic workload rather than the headline price of one model request.
total monthly cost =
fixed platform and engineering cost
+ workload-dependent compute and storage
+ provider/model charges
+ data collection, labeling and evaluation
+ monitoring, review, retry and remediation costThe exact accounting boundary should be agreed by stakeholders. Avoid double-counting staff effort or shared infrastructure. A low per-call price may not be cheap if the workflow retries frequently or requires several human checks.
For an illustrative workload of one million offered tasks per month, suppose a narrow ML architecture has $2,000 monthly fixed attributable cost and $0.006 incremental cost per task. Its total is $8,000. An LLM-centered design with $500 fixed cost and $0.04 incremental cost per task totals $40,500. A hybrid with $3,000 fixed cost and $0.009 incremental cost per task totals $12,000. These assumptions are invented and separate from the earlier design-review example.
The narrow ML and LLM costs are equal when:
2000 + 0.006 * N = 500 + 0.04 * N
N = 1500 / 0.034
N ≈ 44,118 offered tasks per monthBelow that crossing, the LLM-centered design may be cheaper under the assumed linear cost model, despite higher per-task cost. Above it, the narrow model is cheaper. Quality, functionality and security must still pass. Real pricing may be nonlinear because of batching, minimum capacity, reserved infrastructure, rate limits and provider agreements.
An architecture with a higher cost per request can be economical if it reduces human effort or avoids expensive errors, but those effects need credible measurement. Use cost per completed successful task and include abandoned work where appropriate. Compare error remediation, customer experience and staff maintenance burden, not just token price.
13. Data and model lifecycle trade-offs#
Traditional software generally needs a specification and authoritative data, not labeled training examples. Rules can be versioned and tested against known cases. Changing a policy can be a straightforward code or configuration change, but broad exception management can become costly.
A narrow ML design needs the target, feature availability, data access, evaluation and an ownership plan. Feature changes may require compatible transformations or retraining. Monitor relevant metrics over time, and do not treat a distribution change alone as proof that retraining improves outcomes.
An LLM application may use a fixed pretrained model and change prompts or retrieved knowledge rather than training. This can reduce initial model-development effort. It does not remove the need for representative task evaluation, source governance, version control, behavior regression testing and cost review. A provider model change or prompt edit can change system behavior even without modifying conventional business logic.
Hybrid architectures must coordinate the versions of both learned and deterministic components. A model can output a field that a downstream validator no longer recognizes; a policy can change while cached evidence still references an older version; a newly learned score can have a different calibration from what a decision layer expects. Define compatibility contracts and revalidate current authority before any state change.
Record architecture decisions in a lightweight, reviewable decision record:
| Field | Example |
|---|---|
| Problem | Route support requests and produce a valid response |
| Alternatives | Rules, narrow classifier, LLM-centered design, hybrid |
| Constraints | Approved functionality, p95, budget, security and review policy |
| Evidence | Baseline evaluation, representative failure cases, cost and load tests |
| Decision | Chosen architecture and reasons for rejecting alternatives |
| Revisit triggers | New language coverage, changed costs, unacceptable errors, volume growth |
| Ownership | Responsible team for data, policy, model and operations |
The decision record is not a one-time justification. It preserves the assumptions that made the choice reasonable and identifies evidence that would invalidate it.
14. Evaluation must compare the same user task#
Different architectures often expose different intermediate metrics. A rules engine may report rule coverage; an ML classifier reports accuracy or F1; a language model may report schema validity; a hybrid may report component pass rates. Those metrics help diagnose failures but do not establish which product is better.
Define a shared end-to-end outcome first. For support routing, success could mean the request reached the correct authorized queue with necessary context within the permitted time. For an answer-generation task, success may require factual correctness, relevant evidence and a useful response with no unauthorized disclosure. A refusal or escalation is correct only when the documented contract says so; it is not automatically a success or failure.
Use the same test inputs for each candidate where appropriate. Include rare cases, distribution shifts, missing dependencies, malformed inputs, multilingual requests and high-severity errors. For models, evaluate on data not used to tune or train the candidate. Where predictions are used to intervene, distinguish model performance from causal business improvement.
For deterministic functions, unit and property tests can assert exact expected outputs. For learned predictions, use held-out evaluation, calibration when relevant, subgroup and robustness analysis. For generated text, inspect factual grounding and task usefulness; automated scoring needs calibration against reliable human judgment. For integrated systems, test cross-component authority, timeouts, retries, stale state and fallback behavior.
Controlled experiments can compare product outcomes once candidate systems have met safety and functionality requirements. Do not expose users to a knowingly unsafe variant just to measure differences. ASD-002 will go deeper into selecting success criteria and operational acceptance gates.
15. Security and responsible architecture selection#
A conventional service needs ordinary security controls: identity, authorization, data validation, least privilege, auditability and dependency management. ML adds training-data and feature provenance, model artifact integrity, monitoring and potentially sensitive learned representations. LLM applications add prompt injection, untrusted generated output, possible disclosure through context and tool access, and potentially sensitive data sent to external providers.
Map trust boundaries before selecting a deployment pattern. Keep authoritative decisions and protected operations outside the model's discretionary control. For an LLM receiving retrieved documents, do not treat instructions found inside the document as instructions from the application. Restrict what external systems can be called, validate proposed parameters and recheck permission at execution time.
Sensitive tasks may require a private deployment, minimized inputs, strict retention, explicit approvals or an entirely non-AI workflow. An on-premises model is not automatically safer: access controls, logging, supply-chain integrity, evaluation and incident response still matter. A hosted provider is not automatically unsuitable: evaluate contractual, technical and data-handling requirements against actual evidence.
Do not use protected attributes or unjustified proxies to allocate opportunities or make high-impact decisions. Keep human accountability, appropriate consent, user recourse and independent review wherever the task requires them. Regulatory and contractual requirements vary by use case and jurisdiction; the choice needs proper legal and domain review. This lesson supplies engineering considerations, not legal advice or a compliance certification.
16. Additional decision-making scenarios#
Scenario A — Invoice total calculation and invoice intake#
For a structured invoice with known quantities and unit prices, compute totals using a conventional arithmetic service with exact monetary representation. For varied scanned invoices, OCR or a document-understanding model may be required to extract fields. An LLM can assist with interpreting uncommon layouts if it improves validated extraction quality. The final totals, currency, tax policy, duplicate checks and posting authorization remain deterministic and reviewable.
Do not replace exact addition with generation. A hybrid is appropriate only for the uncertain extraction component, not because the invoice itself is an AI use case.
Scenario B — Delivery prediction#
A tracking application needs a verified current status and a delivery estimate. Retrieve the authoritative scan events and route status using software. Use a narrow forecasting or regression model if representative past deliveries and point-in-time inputs support meaningful predictions. Provide an uncertainty range where validated. If the user asks what the estimate means, a template may suffice; an LLM is optional for open-ended language assistance, not the estimator itself.
The original Uber ETA case is an example of a deterministic routing baseline plus a learned correction. The broader architectural lesson is to preserve the known physical constraints and learn the uncertain residual.
Scenario C — Internal policy question answering#
If staff typically ask for an exact document ID, use search and direct links. If questions require synthesizing multiple approved documents in natural language, retrieval plus generation may improve the experience. Use permission-aware retrieval, evidence-linked answers and abstention for unsupported claims. A pure LLM without current authorized source access cannot establish today's internal policy.
If the request is to change a policy or perform an approved administrative action, use a separate authorized workflow. Generating a draft and committing a change are distinct tasks.
Scenario D — A small business with sparse labeled data#
Suppose a small team wants to categorize unusual messages but has only a few examples. Start with a rules or keyword baseline, collect representative reviewed outcomes, and test a pretrained classifier or language model if its data-handling contract permits. Avoid investing immediately in custom model training. Compare human review effort and error types with each approach.
If the required classification is high-risk and reliable evaluation is unavailable, restrict automation to suggesting a category for a reviewer. An LLM's apparent fluency does not establish an acceptable error rate.
17. A practical selection process for architecture reviews#
Use the following workflow for real projects:
- Define the user task, authoritative inputs, outputs, actions and unacceptable errors.
- Decompose the workflow into known rules, uncertain estimation, language interpretation and state changes.
- Build the simplest functional baseline. Include a manual or deterministic option if viable.
- Prototype only additional learned components that address a measured baseline limitation.
- Validate data rights, representative evaluation, safety and operational contracts before comparing quality.
- Measure complete task success, tail latency, resource usage, costs and failure behavior on a shared workload.
- Eliminate candidates that fail mandatory gates; select a feasible alternative by the agreed trade-off.
- Document assumptions, owners, rollout limits, fallbacks and revisit criteria.
The process avoids two extremes: building an overly complex AI system before understanding the task, and refusing learned approaches when they demonstrably improve a task that cannot be captured adequately with fixed logic.
Complexity must buy a measurable capability. Adding an LLM to a deterministic calculator adds no useful flexibility to the arithmetic itself. Adding a small model to prioritize uncertain inventory forecasts may help. Adding language generation to a support interface can improve communication, provided the facts and actions remain grounded and authorized.
18. Common mistakes and interview follow-ups#
Should all new software products use AI? No. If explicit algorithms, search, templates and rules already meet the requirements, more complex inference may make the system less reliable or economical.
Do classical ML models always need more data than LLM applications? Not necessarily. Pretrained models can reduce task-specific training needs, but still require representative evaluation and may require retrieval or fine-tuning. Some small predictive models work well with relatively modest, high-quality datasets.
If an LLM temperature is zero, is it safe for exact financial operations? No. Decoding configuration does not establish mathematical correctness or business authority, and runtime behavior may still vary. Use exact calculations and authorized transaction services.
Is hybrid architecture automatically the strongest candidate? No. Integration, latency, operational ownership and failure modes can outweigh additional capabilities. Use a hybrid only when the decomposition solves genuinely distinct problems or improves measured outcomes.
How should I decide when requirements change? Revisit the original decision record, test the current baseline against the new requirements, and reevaluate alternatives with comparable evidence. Do not replace a working system solely because a newer model exists.
What if all architectures fail? Report the unmet requirements, revise permitted scope, improve data or maintain human review. Do not silently compromise required safety, authorization or correctness.
19. Interview-ready summary#
I would first define the task, input and output contracts, business constraints and error consequences. If a stable specification and authoritative facts determine the result, I would implement conventional software. If the system must estimate an uncertain bounded quantity and there is representative evidence to train and evaluate it, I would test a narrow ML model. If naturally varied language interpretation or generation provides a measurable benefit, I would consider an LLM with appropriate source grounding and validation.
For mixed tasks, I would separate interpretation and prediction from authoritative facts, business policy and transaction execution. I would compare each candidate against the same task-level evaluation and enforce hard functionality, safety, quality, latency and cost requirements. Among feasible candidates, I would prefer the simplest architecture that meets the agreed objective, with explicit fallback behavior and a documented plan to revisit the decision when evidence changes. If none is feasible, I would narrow the task or retain accountable human execution rather than forcing AI into the system.
The core architectural principle is not "rules versus AI." It is using the right computational mechanism for each responsibility, with proof that the complete system serves the intended user safely and reliably.
References and research transparency#
The authorized offline research exception was applied. The references below are established research and official technical guidance relevant to baseline selection, ML maintenance, retrieval, risk management, service objectives and experimental evaluation. Their current content and link availability, and the current Supabase changelog, could not be live-verified. The three diagrams use standard triple-backtick Mermaid fences and were reviewed structurally; the local runtime has no Mermaid parser and frontend rendering was not tested. The Python implementation was executed locally using Python 3.13.5 and passed 14 checks. The examples and architectural evaluation figures are synthetic; no real model performance, costs or compliance outcomes were measured.
- Google — Rules of Machine Learning: Best Practices for ML Engineering
- Sculley et al. — Hidden Technical Debt in Machine Learning Systems
- Breck et al. — The ML Test Score: A Rubric for ML Production Readiness and Technical Debt Reduction
- Hastie, Tibshirani and Friedman — The Elements of Statistical Learning
- Lewis et al. (2020) — Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks
- NIST — AI Risk Management Framework 1.0
- NIST — Artificial Intelligence Risk Management Framework: Generative AI Profile
- Google SRE Workbook — Implementing SLOs
- OWASP — Top 10 for Large Language Model Applications
- Kohavi, Tang and Xu — Trustworthy Online Controlled Experiments
References
- 1.Google — Rules of Machine Learning: Best Practices for ML Engineeringdevelopers.google.com
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.Google SRE Workbook — Implementing SLOssre.google
- 9.OWASP — Top 10 for Large Language Model Applicationsgenai.owasp.org
- 10.
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython