AI System DesignAI System Design FundamentalsModule 11 — Architecture contracts and integration
Comparing AI Architectures with Workload-Based Prototypes and Architecture Decision Records
Question 26 of 47 · Updated
On this page
- 1. Turn an architecture debate into falsifiable hypotheses
- 2. Define the decision and the experiment contract
- 3. Choose the correct prototype fidelity
- 4. Construct a representative workload rather than an average request
- 5. Controlled benchmarking: what is held constant and what may differ
- 6. Instrument the entire useful task
- 7. Latency distributions and throughput: avoid incompatible denominators
- 8. Scalability, resource use and failure behavior
- 9. Worked whole-system comparison
- 10. Statistical uncertainty: pair equivalent tasks and repeat runs
- 11. Pareto analysis: remove dominated options without hiding trade-offs
- 12. Weighted decision matrix and sensitivity
- 13. Executable example: matched benchmark analysis and Pareto filtering
- 14. Reproducibility and the experiment registry
- 15. Architecture decision records: convert evidence into an accountable commitment
- 16. Risk, reversibility and staged commitment
- 17. Second scenario: batch versus incremental analytics
- 18. Common mistakes and acceptance checklist
- 19. Interview-ready answer
- References and research transparency
Compare architectures by testing explicit hypotheses on the same representative user workload, excluding candidates that fail mandatory requirements, and recording the resulting trade-offs and uncertainty in a versioned architecture decision record (ADR). A prototype is an instrument for reducing decision risk, not evidence merely because it runs. Evaluate complete useful task outcomes, latency distributions, goodput, failure behavior, resource use and lifecycle costs. Keep evidence tied to workload and release identities; select a feasible Pareto-efficient design using transparent stakeholder priorities and document what would invalidate the decision.
How would you compare competing AI architectures using workload-based prototypes and architecture decision records?
ASD-085 | Module 11 — Architecture contracts and integration | Progressive learning order 13. ASD-001 defines architecture families and initial selection; ASD-002 defines requirements and acceptance; ASD-003 provides analytical capacity estimates; ASD-005 evaluates sourcing and lifecycle economics. ASD-008 covers migration of a live prototype. This lesson adds an architecture-level experimental procedure: hypotheses, fair comparisons, workload evidence, uncertainty, decision matrices, sensitivity, risk and durable ADRs. Specialist LLM lessons already cover realistic tail-latency workloads, adaptive benchmark fidelity and multiple-comparison bias when tuning serving configurations. The agent lesson compares single and multi-agent systems. Those techniques are prerequisites; the emphasis here is integrating experiments across whole-system alternatives, recording consequential architecture commitments and deciding when to reconsider them. ASD-030 will separately compare prompting, retrieval, fine-tuning and training as model/knowledge strategies. This is not a recommendation for a specific model or a repeat of GPU-level benchmarking.
All architectural results, workload statistics, rates, dollar values and timelines below are invented teaching examples, not measured vendor or production performance. The standard-library Python analysis fixture was genuinely executed; it does not run an AI service.
1. Turn an architecture debate into falsifiable hypotheses#
Suppose a research-support product answers questions over approved documents, extracts structured facts and produces long reports. Engineers propose several designs. One prefers a simple synchronous application, another a routed retrieval and inference pipeline, and a third a distributed workflow with multiple independently scheduled stages. A decision based on diagram complexity, a single demo or an attractive average latency is not defensible.
Write the decision in a form that could be wrong. For example:
- H1: separating retrieval and heavy generation into independent resource pools preserves interactive goodput during bursts of long report jobs, at an acceptable cost premium.
- H2: a bounded routing stage reduces unnecessary model work without unacceptable loss of supported task quality or coverage.
- H3: a distributed job workflow improves recovery of accepted reports under worker failure enough to justify the operational cost.
- H4: adding a verification stage reduces unsupported claims on difficult cases, but may violate the latency contract for interactive requests.
For each hypothesis record the mechanism, expected outcome, competing explanation, measurement method, evidence that would refute it and conditions where it is expected to hold. A hypothesis such as "microservices are more scalable" lacks a defined bottleneck and workload. "Independent worker pools sustain 80 interactive tasks/s while processing 10 report jobs/s with the specified deadline and resource budget" is testable.
Distinguish the architecture decision from individual parameter tuning. An architecture hypothesis concerns boundaries, orchestration, data movement, failure isolation, resource allocation or operating responsibility. A tuning experiment might change batch size inside the same design. Tuning can be necessary to make a fair comparison but should not become an uncontrolled search in favor of a preferred candidate.
Start with a strong baseline, including the simpler or existing approach. A candidate should not win merely because it was compared against a deliberately inefficient implementation. Give each design an agreed optimization budget, common task contract and comparable resource/accounting assumptions.
2. Define the decision and the experiment contract#
Use ASD-002's requirements as inputs; do not redefine quality after observing the candidate outputs. For the fictional research product, stakeholders agree on the following prototype decision requirements. These are illustrative and must be set with actual owners for a real system.
| Dimension | Example contract |
|---|---|
| Function | Complete supported question, extraction or report task with the agreed schema and evidence requirements |
| Quality | At least 94% accepted task outcomes under the evaluation rubric, plus critical slice checks |
| Interactive response | At the required offered load, p95 time to terminal outcome no greater than 1,200 ms, with a separate valid-completion gate |
| Long job | Durable acceptance, observable progress and completion within a job-class deadline |
| Capacity | Sustain 80 offered interactive tasks/s under the required mixed workload and failure envelope |
| Security | Current resource authorization, permitted data processing, no unauthorized effects |
| Economics | Compare actual attributable trial costs and estimated lifecycle cost per useful outcome |
| Operations | Named owners, bounded recovery, deployment and rollback evidence |
| Risk | Unresolved mandatory controls block production approval |
Different task classes have different deadlines and output contracts. Do not pool a ten-minute report with a 1-second lookup and use a single latency number to assert compliance. An async design can return a fast acknowledgment but still fail to finish the accepted job. Measure task submission-to-result and queue age as well as acknowledgement latency.
Define the experimental unit: logical user task, session, tenant, scheduled job, or independent run. A logical task can contain retries, multiple model calls and human review. Counting each attempt as a successful independent sample inflates both quality and throughput. Freeze the expected population and account for every offered task, including admission rejection, timeout, invalid output, abstention, cancellation and unobserved outcome under a defined disposition rule.
There are two distinct comparisons. An equal-budget experiment tests what each architecture can deliver under the same hardware/spend limit. An equal-service experiment asks what each costs to achieve the same product contract. Both can be useful, but don't present equal-budget quality and equal-service cost as if measured in one configuration.
3. Choose the correct prototype fidelity#
A proof of concept answers whether a mechanism is plausible. It may use a local dataset, mocked authorization or a single request. A production-representative prototype tests selected architectural risks with realistic data distributions, concurrency, dependencies, resource limits and failure boundaries. Neither is a production launch by itself.
| Artifact | Question it can answer | Evidence it cannot establish alone |
|---|---|---|
| Analytical model | Is an option obviously infeasible under expected demand and costs? | Actual runtime bottlenecks and task quality |
| Proof of concept | Can a proposed mechanism work on a bounded example? | Sustained service levels or safe operations |
| Component prototype | Does one risky component meet a measured local envelope? | Complete task behavior across dependencies |
| Integrated workload prototype | Do selected end-to-end paths satisfy representative requirements? | Every production condition or long-term reliability |
| Controlled pilot | Does the approved limited deployment work for real eligible users? | Universal safety or unchanged future behavior |
Build the minimum prototype fidelity that can resolve the uncertainty. For H1, simulate both job and interactive arrivals, then exercise representative scheduling and actual resource isolation. For H3, persistence and recovery cannot be mocked if durable accepted-job recovery is the claim. For H4, independently score outputs and measure total latency including verification. Mock a dependency only if the assumption is clearly bounded and does not predetermine the disputed behavior.
A prototype that uses a simulated external API may test routing overhead but cannot establish real provider latency, quotas, outages or contract compliance. A single-node workload cannot demonstrate multi-zone recovery. A quality fixture that includes only easy inputs cannot establish difficult-cohort success. Maintain an evidence register of what each prototype does and does not implement.
The ladder is not mandatory for every change. A low-risk reversible choice might need only a component comparison. An irreversible migration or consequential workflow may require full-scale testing and independent review before approval. Cost of information should be proportional to decision stakes.
4. Construct a representative workload rather than an average request#
A workload is a joint distribution over tasks, input characteristics, arrivals, dependencies, resource demand and outcomes. Average token count, average request rate or average document length is insufficient. Preserve correlations that drive bottlenecks: larger documents may need longer output; complex queries may trigger more retrieval or tool calls; many tenants may submit scheduled reports at the same time.
A workload manifest should specify:
| Dimension | Example stratification |
|---|---|
| Task mix | Short lookup, multi-document synthesis, structured extraction, long report |
| Input | Document size, languages, formats, context length and difficult evidence |
| Arrival | Open-loop schedule, burst periods, tenant concentration, background jobs |
| Dependencies | Cacheability, retrieval fan-out, external latency/error distributions |
| State | Warm/cold caches, fresh/stale indexes, model warm-up, current permissions |
| Outputs | Target length, structured constraints, abstention and handoff |
| Failure conditions | Dependency slowdown, replica loss, quota limits, lost acknowledgement |
| Population | Approved representative trace or generated workload with documented calibration |
Suppose the intended interactive mix is 60% short lookup, 30% synthesis and 10% extraction, with a separate scheduled report stream. Stratify difficult and low-frequency critical cases rather than assume proportional sampling gives enough evidence for rare failures. If difficult cases are oversampled, weight them back to the intended population for aggregate estimates while preserving unweighted slice results. Do not count report traffic inside interactive QPS unless the contract defines it.
Use authorized, privacy-safe traces, anonymized or synthetic fixtures, source snapshots and approved data rights. Removing names alone does not necessarily de-identify private prompts. Preserve meaningful workload structure without copying protected raw customer data to unapproved providers. Separate historical replay and live exposure. Disable side effects in benchmarking unless an explicitly authorized isolated test environment exists.
For greenfield products without traces, state the plausible workload assumptions and test low/base/high mixes. Validate against pilot usage before committing expensive architecture changes. A distribution that fits one product phase may fail once user behavior changes.
5. Controlled benchmarking: what is held constant and what may differ#
The comparison must isolate the architectural hypothesis while allowing each viable architecture to operate as designed. Use identical logical tasks, source snapshot, authorized capabilities, acceptance rubric and offered arrival schedule when comparing alternatives. Fix infrastructure and software versions where possible, record differences that are intrinsic to the architecture, and measure all extra work.
Control:
- Input task identities, document and feature versions, source authorization, output contract and deadline.
- Evaluation rubric, rater guidelines, scoring software and adjudication procedure.
- Workload schedule, test duration, warm-up, cold/warm runs, cache reset or explicitly matched cache state.
- Hardware class, region, shared dependency quotas and noise sources, or the stated equal-service allocation.
- Model, prompt, retrieval, runtime and tool releases, except where the architecture deliberately varies them.
- Retry, cancellation and admission semantics; count all attempts and costs.
- Candidate tuning budget and separation of development versus confirmation workloads.
It is not always fair to force identical resource configuration: a separated topology may intentionally allocate different CPU and GPU pools. Compare under the same resource cap or the same service contract, explain which, and disclose configuration. If the candidate uses a different model and a different scheduler, a whole-product comparison can still establish the combined design's outcome, but it cannot isolate the scheduler's causal contribution. Use ablations or factorial experiments for that attribution.
For performance runs, randomize or interleave run order where feasible to reduce systematic drift from thermal conditions, cloud contention or vendor load. Use isolated resource allocations or paired time blocks so one candidate cannot starve another. Repeated runs on a shared service can still be correlated. Record observed interference rather than assume independent samples. A fixed seed aids reproduction but does not make a stochastic or remote service deterministic.
Use an untouched confirmation workload after exploratory tuning. Predeclare primary outcomes, acceptance rules and how many comparisons the confirmation will support. A team that tries dozens of model/routing configurations then reports the highest score from the same holdout has selected noise as well as signal. The specialist LLM benchmark-bias lesson covers correction methods in depth; here apply the principle to the architecture decision evidence.
6. Instrument the entire useful task#
Measure from the client-visible offered task to its terminal outcome. Trace internal stages but do not substitute internal speed for completed work. A result is useful only if it satisfies the quality and functional rubric, applicable deadline and required controls.
The common evaluator should not favor a particular implementation's wording or internal format beyond the agreed contract. Blind human assessors to candidate identity where feasible; randomize presentation order; use deterministic validators for schemas, arithmetic, evidence references and prohibited fields; investigate disagreement and adjudicate. An LLM judge can assist at scale but its bias, validity and agreement with domain reviewers must be evaluated. Do not let the same model architecture certify itself without independent evidence.
For a research task, a successful outcome may require correct claims grounded in authorized source evidence, valid structured output, required citations and deadline compliance. For a report, a durable job receipt plus correct final artifact is needed. For a workflow that abstains on unsupported inputs, distinguish a correct abstention (if that is the intended rubric outcome) from a failed task; count coverage separately. A forced answer can look more available while increasing unsupported claims.
Retain paired observations under logical IDs: candidate release, task class, accepted flag and reason, offered timestamp, terminal timestamp, attempt count, queue and execution durations, model/token work, resource allocation, attributable cost and evaluation reference. For distributed tracing record version, context, parent/child links and retry attempt IDs. Protect sensitive content; a trace is not a license to copy raw private prompts.
7. Latency distributions and throughput: avoid incompatible denominators#
Use percentiles appropriate to the task class, with a documented estimator. A p95 of 900 ms means an estimated 95th percentile under the measured population and convention; it is not an upper bound for every request. Record p50, p95, p99 where sample size supports them, timeout/admission rate and distribution by important workload slice. Record both terminal-outcome latency and successful-result latency; a fast rejection can reduce overall latency while degrading service.
For streaming, measure first useful token or first usable partial result, inter-token behavior and full completion. Do not compare first-token latency for one system with final-answer latency for another. For asynchronous work, measure durable acceptance latency, queue age, time to useful completion and unresolved jobs. For timeouts, use the specified terminal deadline or censored-data treatment rather than erase slow tasks. If the outcome is missing, classify it explicitly and investigate before declaring a run complete.
For a window of duration T with N offered tasks and S useful completions within their own deadlines:
offered rate = N / T
useful success fraction = S / N
goodput = S / T
cost per useful completion = total attributable cost / SThe observation window must be defined. If tasks are admitted near the end and finish later, either include a drain and account for the actual interval appropriately, or use a fixed-cohort deadline evaluation and explicitly define the denominator. Do not count drained completions with an incompatible duration. If S=0, cost per useful completion is undefined/infinite, not zero.
Open-loop arrivals are useful for reproducing independent external demand. A closed-loop test with fixed concurrency can reduce offered load when the system slows and hide overload. Both have legitimate purposes: closed-loop represents users or workers that wait before submitting the next task; open-loop represents external arrivals independent of service latency. Measure scheduled arrivals, actual dispatch delay and dropped load-generator events to avoid coordinated omission. Ensure the generator is not the bottleneck.
Do not add per-stage p95 values to prove end-to-end p95. Stage latencies can be correlated and fan-out paths wait for maxima, not sums of independent medians. Measure full task duration under matched workloads. Use traces to diagnose bottlenecks and analytical models to predict regimes, not replace observed evidence.
8. Scalability, resource use and failure behavior#
Construct throughput-versus-offered-load and latency-versus-load curves, not just one point at idle. Compare useful goodput at the required operating point, maximum sustainable goodput under the agreed SLO, and headroom under failure and burst conditions. "Maximum throughput" without quality and latency constraints can reward queue accumulation and rejected requests.
Vary one dimension at a time where practical: offered rate, long-input share, background job intensity, number of replicas, cache state or failure domain. Include ramp, sustained and recovery periods long enough to expose autoscaler lag, warm-up, queue buildup, memory fragmentation, connection-pool exhaustion and resource leaks. A ten-second benchmark cannot establish an hour-long job lifecycle or daily workload.
Measure CPU core-seconds, memory high-water marks, GPU/accelerator utilization and memory, token work, disk/log IO, network and dependency quotas, provisioned idle resources and review time. High utilization is not itself a goal; a 99% busy pool with poor tail latency may be unacceptable. Compare resource efficiency per useful outcome and provisioned cost under actual mixed demand. Quantify replication and fallback capacity rather than assume the busiest-path result applies after a failure.
For reliability, test concrete faults in approved isolated environments: worker termination before and after durable acceptance, a slow retrieval dependency, exhausted quota, cache loss, stale model release, partial external response, and loss of a replica. Verify user outcomes, authoritative receipts, queue recovery, duplicate-effect prevention and recovery time. A fault injection that terminates an unimportant mock does not demonstrate recovery of a real critical dependency.
Record failure domain, injection timing, expected behavior, actual state, cleanup and reproducibility. Never perform destructive fault tests against a live user workload without explicit authorized safeguards. Use synthetic read-only or isolated effect sinks. A successful load test is not a security audit, and passing selected faults does not prove the stated availability for all incidents.
9. Worked whole-system comparison#
Assume three candidates for the interactive research workflow at 80 offered tasks/s for an illustrative fixed 100-second measurement window, with every offered task resolved and counted in that window under the chosen terminal-outcome convention. All receive 8,000 logical tasks. The report workload is tested separately under the same mixed-resource conditions, and its gate is considered in eligibility.
- A: simple synchronous modular path with a shared worker pool.
- B: routed retrieval plus bounded independent inference/interactive pool.
- C: distributed staged workflow with an additional evidence-checking service.
The numbers below are hypothetical experiment summaries, not actual measurements. Accepted counts are quality-valid, deadline-compliant and control-compliant tasks under the common rubric. The p95 is for time to terminal outcome over all offered tasks; the valid-completion requirement prevents fast failure from passing on latency alone.
| Metric | A | B | C |
|---|---|---|---|
| Offered tasks | 8,000 | 8,000 | 8,000 |
| Useful completions | 7,280 | 7,600 | 7,760 |
| Useful success fraction | 91% | 95% | 97% |
| p95 terminal latency | 850 ms | 950 ms | 1,150 ms |
| Useful goodput | 72.8/s | 76/s | 77.6/s |
| Attributable trial cost | $144 | $152 | $232.80 |
| Cost per useful completion | $0.01978 | $0.02000 | $0.03000 |
| Required security and recovery evidence | Pass in scenario | Pass in scenario | Pass in scenario |
If the preregistered *observed* useful-success gate is at least 94%, A fails irrespective of its lower latency and nominal cost. B and C meet the illustrative observed quality and p95 gates. In a real study, passing requires the separately agreed uncertainty and slice evidence, not just these observed percentages. Assume for this worked decision that other mandatory report, critical-slice, confirmation and control gates have also passed for B and C; this is an explicit scenario assumption, not evidence generated by the table.
C has two percentage points more useful success, equivalent to 160 additional useful completions in the sample, but costs $80.80 more and has slower p95. The incremental trial cost per additional useful completion is $80.80/160=$0.505, a marginal comparison distinct from average cost per completion. Whether it is worth paying depends on the value and risk distribution of the additional resolved cases, including whether they are otherwise handled by staff. Do not use average benefit as a universal valuation of critical tasks.
If 1,000,000 offered tasks/month have the same mix and trial unit economics scale linearly, B's trial cost per offered task is $152/8000=$0.019; C's is $0.0291. The extrapolated difference is $10,100/month for approximately 20,000 additional useful tasks. This is a simplified variable-cost projection, not TCO: actual fixed fleets, stepwise capacity, discounts, human review and operational staffing can change it. ASD-005 covers full lifecycle cost.
Now suppose a peak-burst test reveals that B's useful goodput stalls at 78/s while C can deliver 95/s under its latency/quality contract. If future required demand is 90 useful completions/s, B may no longer be feasible at its current configuration. Re-test or re-size B, rather than extrapolate the original comparison beyond its validated envelope.
10. Statistical uncertainty: pair equivalent tasks and repeat runs#
Small point differences can be noise. A 95% observed success rate on 100 tasks is not the same strength of evidence as 95% on 100,000 independent representative tasks. Use appropriate binomial intervals for independent binary outcomes, and paired comparisons when candidates receive the same tasks. For repeated queries from the same user or tenant, or time-correlated workload runs, use cluster-aware resampling or a suitable hierarchical analysis. Individual requests may not be independent experimental units.
In a hypothetical paired comparison of 1,000 tasks, assume B and C both succeed on 920; only B succeeds on 30; only C succeeds on 50; neither succeeds on 0. Then B succeeds on 950 (95%), C on 970 (97%) and the paired difference is +2 percentage points. The 80 discordant pairs are the informative observations for a paired binary comparison. An approximate standard error of the mean difference under independent task pairs is sqrt((0.08−0.02²)/1000)≈0.00892, or 0.892 percentage points. A simple approximate normal 95% interval is 0.02 ± 1.96×0.00892, about [0.0025,0.0375], or [0.25,3.75] percentage points. This is a teaching calculation, not a guarantee of coverage for finite dependent data. Use exact or appropriate paired methods where assumptions demand them, such as McNemar's test for a null of equal marginal success and a paired bootstrap or other justified interval for the effect.
Define a practically meaningful effect before testing. Statistical evidence of a small positive improvement does not justify additional operational complexity if stakeholders require at least five percentage points. Conversely, lack of statistical significance is not proof of equivalence. If a cheaper alternative is acceptable with at most a one-point loss, define and test a noninferiority margin with a design appropriate to that question. Do not derive the margin from the observed result.
Latency and throughput depend on system state and cross-request interaction. Resampling individual latencies from a single run can underestimate uncertainty about run-to-run conditions. Use independent or blocked repeated runs, examine empirical distributions and report uncertainty at the correct experimental unit. For rare tail events, use sufficiently long representative runs and report uncertainty rather than a precise-looking p99. Track effect sizes and confidence intervals alongside raw counts, failures and missing labels.
Separate exploratory experiments from confirmation, and define how multiple alternatives, slices and primary outcomes affect error control. Predeclare which gates are mandatory and which metrics are descriptive. Avoid cherry-picking the winning run, unplanned early stopping and treating all observed request samples as independent. Benchmark selection bias can be reduced by confirming the selected design on untouched workloads and across meaningful operating regimes.
11. Pareto analysis: remove dominated options without hiding trade-offs#
After excluding infeasible or unconfirmed candidates, represent each candidate by its objectives, oriented consistently: maximize useful success and goodput; minimize tail latency, cost, operational burden and risk where quantified. A dominates B if A is at least as good on every chosen objective and strictly better on at least one. The nondominated candidates form a Pareto frontier.
For the earlier B and C, neither dominates the other on the reported outcomes. B is cheaper and faster; C is more successful and has greater goodput. A fourth hypothetical feasible candidate D with 94.5% useful success, p95 1,100 ms, goodput 75.6/s and cost $0.025 per useful completion would be dominated by B on all four reported quantitative objectives, assuming equivalent scope and controls. If D uniquely satisfies a relevant unmeasured operational need, include that dimension before rejecting it.
A frontier depends on the objective set, measurement noise and operating conditions. An empirical point estimate may appear to dominate another within sampling error. Use uncertainty intervals, practical equivalence tolerances or robust dominance analysis; distinguish obvious poor candidates from uncertain comparisons. Missing metrics must not be silently interpreted as favorable. A mandatory security failure is not merely another Pareto dimension: exclude that candidate first.
Do not use weighted scores as a substitute for a visible frontier. A single score can hide that a design trades a small cost gain for a large latency increase or a critical failure. Publish the underlying metrics, ranges and evidence status.
12. Weighted decision matrix and sensitivity#
A weighted matrix is useful once all options meet mandatory constraints. Convert metrics to an agreed utility scale with documented anchors independent of the candidates, rather than min-max normalizing only the current shortlist. Otherwise introducing an inferior candidate can change the ranking of the others. Qualitative criteria need explicit scoring rubrics and accountable assessors. Avoid double counting strongly related objectives such as cost per task and gross monthly cost unless stakeholders intentionally value both distinct effects.
For illustration, assume stakeholders score B and C on a 0–100 utility scale with preagreed anchors. These utilities are hypothetical elicited ratings, not mathematically derived from the earlier metric table.
| Criterion | Weight | B utility | C utility |
|---|---|---|---|
| Useful outcome quality | 35% | 80 | 95 |
| Response performance | 25% | 90 | 70 |
| Lifecycle economics | 25% | 90 | 60 |
| Operability and reversibility | 15% | 80 | 60 |
| Weighted utility | 100% | 85.0 | 74.75 |
B score = 0.35×80 + 0.25×90 + 0.25×90 + 0.15×80 = 85.0. C score = 0.35×95 + 0.25×70 + 0.25×60 + 0.15×60 = 74.75. B is preferred under those preferences. Change weights to 70%, 10%, 10%, 10% respectively: B becomes 82, C becomes 85.5, reversing the preference. This exposes a decision dependent on stakeholder values, not an objectively superior architecture. Reconcile priorities with accountable owners and retain the original metrics.
Sensitivity should include demand mix, model quality, service cost, failure recovery, staffing, latency and migration constraints, not only weight changes. Calculate plausible low/base/high cases and threshold values where preference changes. Consider correlated uncertainties: long report growth may increase both cost and tail latency. Where outcomes are close and decision reversible, select a bounded pilot rather than claim precision the data lacks.
A risk assessment complements scoring: identify failure mechanism, affected workflow, severity, likelihood or uncertainty, detectability, mitigation, residual risk and owner. Mandatory risks are gates, not weighted preferences. For unknown risk, document the missing evidence, time-bound decision scope and experiment needed. If no option is feasible, record that outcome and narrow scope or retain a manual safe route.
13. Executable example: matched benchmark analysis and Pareto filtering#
This local standard-library Python example analyzes synthetic task-level observations rather than benchmark actual services. It uses a nearest-rank p95 of terminal-outcome latency, a deadline-compliant accepted-task fraction, total cents per useful completion, useful goodput, paired percentile bootstrap over logical task IDs, and a four-objective Pareto frontier after externally supplied mandatory approval. Cost uses integer cents in the fixture; the division returns a floating-point average. The bootstrap is an illustrative analysis method, not a universal confidence procedure.
PYTHONfrom dataclasses import dataclass, replace from math import ceil, isfinite from random import Random @dataclass(frozen=True) class Trial: task: str accepted: bool latency_ms: float # time to terminal outcome, including timeout cost_cents: int def summarize(rows, expected_ids, seconds, deadline_ms): rows = tuple(rows) ids = [r.task for r in rows] if (not rows or len(ids) != len(set(ids)) or set(ids) != set(expected_ids) or not isfinite(seconds) or seconds <= 0 or deadline_ms <= 0): raise ValueError('incomplete or invalid run') if any(type(r.accepted) is not bool or not isfinite(r.latency_ms) or r.latency_ms < 0 or type(r.cost_cents) is not int or r.cost_cents < 0 for r in rows): raise ValueError('invalid observation') latencies = sorted(r.latency_ms for r in rows) good = sum(r.accepted and r.latency_ms <= deadline_ms for r in rows) return (good / len(rows), latencies[ceil(.95 * len(rows))-1], sum(r.cost_cents for r in rows) / good if good else float('inf'), good / seconds) def paired_bootstrap(a, b, deadline, draws=2000, seed=7): def keyed(rows): rows = tuple(rows) result = {r.task: int(r.accepted and r.latency_ms <= deadline) for r in rows} if not result or len(result) != len(rows): raise ValueError('duplicate or empty tasks') return result x, y = keyed(a), keyed(b) if x.keys() != y.keys() or draws < 40: raise ValueError('unpaired tasks or too few draws') diffs = [y[k] - x[k] for k in sorted(x)] rng = Random(seed) samples = sorted(sum(rng.choices(diffs, k=len(diffs))) / len(diffs) for _ in range(draws)) return (sum(diffs) / len(diffs), samples[ceil(.025*draws)-1], samples[ceil(.975*draws)-1]) def frontier(metrics, approved): # All objectives minimized after mandatory evidence gates. eligible = {k: (-v[0], v[1], v[2], -v[3]) for k, v in metrics.items() if k in approved and all(isfinite(x) for x in v)} def dominates(a, b): return all(x <= y for x, y in zip(a, b)) and any(x < y for x, y in zip(a, b)) return sorted(k for k, v in eligible.items() if not any(dominates(w, v) for j, w in eligible.items() if j != k)) ids = ['t'+str(i) for i in range(20)] a = [Trial(k, i < 16, 100 if i < 19 else 600, 2) for i, k in enumerate(ids)] b = [Trial(k, i < 18, 200, 3) for i, k in enumerate(ids)] ma = summarize(a, ids, 10, 500) mb = summarize(b, ids, 10, 500) assert ma == (.8, 100, 2.5, 1.6) assert mb == (.9, 200, 60/18, 1.8) assert summarize([replace(r, accepted=False) for r in a], ids, 10, 500)[2] == float('inf') assert summarize([replace(r, latency_ms=501) for r in a], ids, 10, 500)[0] == 0 assert paired_bootstrap(a, b, 500)[0] == .1 assert paired_bootstrap(a, b, 500) == paired_bootstrap(a, list(reversed(b)), 500) assert paired_bootstrap(a, a, 500) == (0, 0, 0) assert frontier({'a':ma,'b':mb}, {'a','b'}) == ['a','b'] assert frontier({'a':ma,'b':mb,'c':(.7,300,4,1)}, {'a','b','c'}) == ['a','b'] assert frontier({'a':ma,'b':mb}, {'b'}) == ['b'] for fn in (lambda: summarize(a[:-1], ids, 10, 500), lambda: summarize(a+[a[0]], ids, 10, 500), lambda: summarize([replace(a[0], cost_cents=-1)]+a[1:], ids, 10, 500), lambda: paired_bootstrap(a, b[:-1], 500), lambda: paired_bootstrap(a, b+[b[0]], 500)): try: fn() except ValueError: pass else: raise AssertionError('invalid run accepted') print('15 checks passed')
Observed local execution with Python 3.13.5:
15 checks passedTen direct assertions and five exception checks validate exact metric arithmetic, no-success cost handling, late-result exclusion, paired difference, deterministic pairing independent of input order, identical-arm comparison, preservation of competing nondominated alternatives, rejection of a dominated candidate, externally gated eligibility, missing and duplicate tasks, negative costs and invalid paired task sets.
For candidate a, 16/20 tasks satisfy quality and deadline; the 19th sorted latency is 100 ms, cost is 40/16=2.5 cents per useful result and goodput is 16/10=1.6/s. Candidate b has 18/20 useful tasks, p95 200 ms, cost 60/18≈3.333 cents and goodput 1.8/s. The paired point difference is +0.1. Notice that a's p95 is 100 ms despite one 600 ms terminal outcome, demonstrating how a percentile can hide an extreme result in a small sample. Neither candidate dominates the other across the chosen objectives.
The implementation expects prevalidated normalized records and a unique expected-task manifest. It does not authenticate or fetch records, validate every configuration type or missing label, establish independent task sampling, represent separate quality/safety gates, model censorship, or account for run-level correlation. The synthetic accepted flag stands for the externally applied common rubric. The denominator assumes all offered tasks are accounted for and the supplied window is the correct measurement duration. For production experiments validate those assumptions independently; use explicit outcome reasons and class-specific deadlines. The bootstrap helper assumes already validated rows, independent representative pairs and positive draws; its percentile interval on a tiny discrete fixture is not a production statistical conclusion. For repeated tenants or blocked runs, resample the correct clusters. The seeded random generator establishes reproducibility of the fixture, not statistical independence of real systems. The frontier uses exact point comparisons and treats any nonfinite metric as ineligible; robust dominance requires additional uncertainty policy.
For n tasks, sorting the terminal latencies costs O(n log n) time and O(n) space. Pairing uses expected O(n) hash operations plus sorting IDs; B bootstrap draws of n task differences cost O(Bn + B log B) time and O(B+n) memory in this implementation. For k candidates with a fixed number of objectives the naive frontier is O(k²). These complexity statements describe the analysis code, not inference or production throughput.
14. Reproducibility and the experiment registry#
An architecture comparison may be revisited months later. Record enough evidence that a qualified reviewer can reconstruct what was tested, why and within which constraints. A notebook screenshot or selected metric table is not sufficient.
A versioned run manifest should include:
| Field | Required evidence |
|---|---|
| Experiment identity | Hypothesis, task contract, protocol and evaluation release |
| Candidate identity | Code commit, config and infrastructure manifest, model/prompt/tool/feature versions |
| Workload | Dataset/trace digest, task IDs, population weights, arrival and background-job schedules |
| Environment | Hardware, region, runtime/library versions, quota, cache state, warm-up and noise controls |
| Execution | Run ID, actual start/end, seeds, measured offered load, fault conditions, aborted runs |
| Outcomes | Per-task reason, latency, quality evaluation, resource and cost ledger |
| Analysis | Code version, percentile/CI method, pairing/stratification, missing-data disposition |
| Governance | Authorized source data, retention, access, reviewer and approved scope |
| Limitations | Mocked dependencies, unsupported slices, nonreproducible external behavior |
Use immutable or governed artifact references and hashes. A digest establishes byte identity, not evidence quality. Some dependencies are not reproducible exactly: vendor model aliases may change, accelerator kernels can be nondeterministic and external services may exhibit time-dependent behavior. Record the actual model release or explicitly state unknown version, record observed operating conditions and repeat confirmation when dependencies materially change. Reproduction of analysis on frozen output is distinct from reproducing the generation itself.
Maintain exploration results, not just the winner. Preserve failed runs with reasons; exclude a broken load generator only under a predefined invalid-run rule. If evidence must be deleted for privacy or contractual reasons, retain permissible metadata and document inability to rerun. Do not retain sensitive prompts indefinitely just to make a benchmark repeatable.
15. Architecture decision records: convert evidence into an accountable commitment#
An ADR is a concise, versioned statement of an architectural choice, its context, alternatives, rationale and consequences. It is not a substitute for design documentation, nor a place to dump every benchmark observation. Link to the evidence rather than copy only favorable results. Record decisions that matter across teams, are expensive to reverse, change authority or deployment boundaries, or establish long-lived contracts.
Suggested lifecycle: proposed, accepted for a specified scope, superseded or rejected. An accepted ADR records an approved design choice, not necessarily permission to deploy to production. Production release gates and sign-offs remain separate. Preserve prior ADRs and link superseding records; do not rewrite past rationale as if later facts were known.
Example ADR (fictional):
ADR-014: Independent interactive inference pool with routed retrieval
Status: Accepted for controlled pilot; production approval pending
Owners: Product architecture, reliability and domain evaluation leads
Context:
Research workspace; 80 interactive offered tasks/s, mixed report traffic.
User task contract, data processing constraints and quality gates: req-v4.
Shared worker contention is the decision risk.
Alternatives:
A: Shared synchronous modular path.
B: Routed retrieval and isolated interactive inference pool.
C: Distributed workflow plus verification service.
Evidence:
workload-manifest-v3, experiment-run-set-12, confirmation-set-2.
A observed useful success 91%, below illustrative 94% gate.
B: 95%, p95 950 ms, $0.020 per useful completion.
C: 97%, p95 1150 ms, $0.030 per useful completion.
Table values here are fictional; real ADR must link actual evidence.
B and C are nondominated. Other mandatory gates assumed passed.
Decision:
Pilot B on eligible scopes using stable task and authorization contracts.
Keep C as an alternative if quality requirements or workload change.
Consequences:
Additional runtime operation, network boundary and version compatibility.
Avoid full distributed workflow complexity for the initial product scope.
C may be valuable for high-complexity requests under a separate decision.
Risks / validation still required:
Burst recovery, real quota changes, operational ownership and pilot outcomes.
No full production approval from this prototype comparison.
Reversibility:
Stable domain ports and compatible job/receipt semantics.
Approved recovery path; no duplicate effects during shadow testing.
Reassessment:
Confirmed SLO or quality regression, sustained workload outside envelope,
material provider cost or terms changes, critical-slice failures,
or validated evidence of lower lifecycle cost at equivalent outcomes.In a real ADR include the decision date, decision authority and explicit links to versioned requirements, actual experiment results, security and privacy review, capacity and financial estimates, rollout plan and operational ownership. Document rejected alternatives and why, including those ruled out by missing evidence rather than actual failure. Record assumptions and open questions, not only benefits.
If the decision affects a schema or permission boundary, link the approved contract and migration strategy. If it establishes a new dependency, record ownership, support and exit plan. For independent AI releases, specify how future model or prompt changes must demonstrate compatibility with the selected architecture. A model version change can invalidate quality and resource conclusions even if the architecture diagram stays unchanged.
16. Risk, reversibility and staged commitment#
Architectural decisions differ in reversibility. A routing configuration behind a compatible interface may be cheap to reverse; committing to a proprietary data format or moving authoritative state may be expensive. The evidence threshold should reflect the cost and harm of a wrong choice.
Use a time-boxed proof of concept for an uncertain mechanism, an isolated workload prototype for a resource or failure hypothesis, and an approved pilot for residual user-facing uncertainty. Estimate cost of experimentation against cost of an incorrect decision. Spending $5,000 to reduce uncertainty before a large irreversible investment may be worthwhile; spending months comparing equivalent low-risk internal libraries may not be.
Keep alternatives reversible through stable domain ports, versioned data contracts, export paths and independent policy enforcement. Do not promise rollback if new state cannot be represented by the older system. ASD-008 covers whole-product migration, and ASD-007 covers incremental extraction. A decision record should state the recovery boundary and remaining cost of switching, not claim feature flags make every decision reversible.
Measure actual adoption, task quality, cost and reliability after deployment. Trigger reassessment when the workload mix or peak exceeds the tested envelope, a provider or model release changes semantics or price, a new privacy obligation alters feasible processing, incident/recovery evidence contradicts assumptions, or operating costs exceed an approved threshold. Set owner and review cadence appropriate to the change risk. A reassessment trigger is a request to investigate, not a command to automatically migrate.
17. Second scenario: batch versus incremental analytics#
Suppose an inventory analytics product generates location-level forecasts. The architectural question is whether a nightly batch pipeline or an incremental event-driven pipeline provides enough additional operational value to justify its complexity. Hold the target, evaluation population, feature availability rules and action authority constant. Prototype the nightly design against historical schedule replay and the incremental design against realistic event arrival, late updates and backpressure.
A credible experiment measures forecast availability before decision cutoffs, prediction quality on aligned target windows, correction propagation, complete run accounting, source load, recovery from missed or duplicate events, and operational cost. It must not evaluate the batch system using features unavailable at its cutoff or give the incremental system future information during replay. Evaluate the actual decision outcome rather than claiming lower processing latency automatically improves forecasting.
If both designs meet the decision freshness contract, the simpler batch architecture may be preferred under actual cost and recovery evidence. If a meaningful share of decisions cannot wait for the next batch, a bounded incremental design may be justified for those contexts. A hybrid may materialize a daily baseline and refresh affected entities on approved events. The ADR should record which workloads need which path, how late data and correction lineage are handled, and when growth or changed freshness requirements justify reconsideration. ASD-004 addresses execution-mode semantics; this experiment tests their value under a particular workload.
18. Common mistakes and acceptance checklist#
| Mistake | Correction |
|---|---|
| Compare attractive demos | Use representative logical tasks, source and arrival contracts |
| Benchmark one average prompt | Preserve workload distributions, correlation and critical slices |
| Compare candidates with different task rubrics | Use independent common evaluation |
| Use fast failures to improve p95 | Pair latency with useful completion and error measures |
| Report attempted requests as goodput | Count valid deadline-compliant task outcomes |
| Ignore retries and idle resources | Include all attributable work and lifecycle costs |
| Select highest score from many tuning runs | Separate exploration and confirmation |
| Treat correlated requests as independent | Use correct paired, clustered or run-level analysis |
| Allow weighted score to offset a mandatory failure | Exclude infeasible or unconfirmed options first |
| Hide a trade-off behind one score | Report nondominated choices and sensitivity |
| Claim a simulated dependency proves production performance | Document fidelity and test the disputed mechanism |
| Write an ADR that only lists the winner | Record context, rejected alternatives, evidence and consequences |
Before acceptance, verify a predeclared experiment contract, representative workload manifest, complete paired outcomes, independent quality and control evaluation, matched load/resource accounting, repeated runs at required operating and fault conditions, appropriate uncertainty and sensitivity analysis, and traceable experiment artifacts. Check the selected design against every mandatory gate, record residual risk and ownership, specify reversibility and review triggers, and maintain a separate production release gate. If evidence is incomplete, record a conditional decision or request a targeted experiment rather than certify production readiness.
19. Interview-ready answer#
I would begin with the architecture decision and testable hypotheses derived from agreed requirements. I would choose the simplest strong baseline and design prototypes at the fidelity needed to resolve the material risks. I would use the same representative task population, authorized evidence, arrival schedules and acceptance rubric, clearly distinguishing equal-budget from equal-service comparisons. I would measure useful task success, latency distributions, goodput, reliability under specified faults, resource use and full attributable cost, including retries and failures.
I would analyze matched tasks and repeated runs with uncertainty appropriate to their dependencies, confirm promising candidates on untouched workloads, and exclude alternatives that fail or lack evidence for mandatory requirements. I would compare the feasible Pareto frontier, use a transparent weighted matrix only where stakeholder preferences are needed, and test sensitivity to workload, cost and priorities. Finally, I would publish an ADR recording context, options, evidence, rationale, consequences, residual risks, owners, recovery and explicit reassessment triggers. I would distinguish a prototype decision from production approval and use a controlled pilot where uncertainty remains.
The goal is not to prove a favored architecture is best. It is to make a defensible, reproducible choice for a specified workload and know when the evidence no longer supports it.
References and research transparency#
Authorized offline research exception applied. The sources below identify established architecture decision guidance, primary research, standards and technical documentation. Current link availability, live contents and the Supabase changelog were not verified. Four standard triple-backtick Mermaid diagrams received structural review; parser execution and frontend rendering were not tested. The exact Python analysis fixture was executed locally on Python 3.13.5 with all 15 checks passing. No actual AI inference, load generator, hardware, vendor, statistical calibration study, security evaluation, fault injection or production prototype was run. The workload and financial scenarios are fictional; the code tests analysis arithmetic and selected invariants, not production architecture feasibility.
- Michael Nygard — Documenting Architecture Decisions
- Software Engineering Institute — The Architecture Tradeoff Analysis Method
- MLCommons — Inference Benchmarks
- Google SRE Workbook — Canarying Releases
- Google SRE Workbook — Implementing SLOs
- Dean and Barroso — The Tail at Scale
- NIST/SEMATECH — e-Handbook of Statistical Methods
- Efron (1979) — Bootstrap Methods: Another Look at the Jackknife
- Sculley et al. — Hidden Technical Debt in Machine Learning Systems
- NIST — AI Risk Management Framework 1.0
- FinOps Foundation — FinOps Framework
- OpenTelemetry — Traces
- ACM — Artifact Review and Badging
References
- 1.Michael Nygard — Documenting Architecture Decisionscognitect.com
- 2.
- 3.MLCommons — Inference Benchmarksmlcommons.org
- 4.Google SRE Workbook — Canarying Releasessre.google
- 5.Google SRE Workbook — Implementing SLOssre.google
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.FinOps Foundation — FinOps Frameworkfinops.org
- 12.OpenTelemetry — Tracesopentelemetry.io
- 13.
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython