DevWithAbhinav
AS
Abhinav Srivastava Lead Engineer · 12+ yrs enterprise .NET & AWS · building AI agents with Microsoft Agent Framework
Phase 01 / 07

Requirements, Scoping & Feasibility Analysis

The single most expensive mistake in AI system design is applying a probabilistic engine to a deterministic problem — this phase exists to catch that before any architecture work starts.

the gist

Before drawing a single box, decide honestly whether this problem even needs an LLM — and write down the cost and latency numbers that will constrain every choice after this one.

60–80%cost cut from routing deterministic traffic away from the LLM
3–5xoutput tokens priced vs. input tokens
2,580msexample end-to-end latency budget, hop by hop

Most production AI failures trace back to skipping this phase — teams reach for an LLM because it's exciting, not because the problem demands probabilistic reasoning. Everything downstream — cost, latency, reliability — gets harder to fix later than to prevent here.

phase objectives

Deterministic vs. probabilistic classification

Does this task have one correct, computable answer given the inputs? "What's this customer's account balance?" is a database query — deterministic. "Summarize this contract's risk clauses" has no single correct string — that's where LLMs earn their cost. Get it wrong either direction and the system either becomes an unreliable, expensive lookup table, or breaks the moment inputs vary from what was anticipated.

fig. 1.1deterministic / probabilistic gate
request one correct, computable answer? yes Rules engine / lookup no LLM involved no Model call (LLM) genuinely ambiguous cases
The decision-tree gate: every request is classified before it's ever allowed to reach a model call.

Token economics, ROI modeling & NFRs

What does one interaction cost — input plus output tokens (output runs 3–5x pricier) times expected volume? Does the system beat the alternative on cost? TTFT, throughput and latency budget need to be derived from real user expectations before architecture decisions get made — a 500ms budget eliminates most multi-hop agentic RAG designs before a box gets drawn.

system components & topologies

The latency budget waterfall

Instead of one number ("under 3 seconds"), the budget is allocated across every hop. Breaking it down at design time means that when the SLA is violated in production, the team knows exactly where to look — without it, debugging latency becomes archaeology.

fig. 1.2latency budget waterfall — 2,580ms total
Network — 50ms Auth — 30ms Retrieval — 400ms Generation — 2000ms Post-processing — 100ms
Generation dominates the budget — exactly why streaming and model-tier choice matter most in Phase 2.

tooling & tech stack

Helicone / Langfuse

Cost modeling in a spreadsheet seeded with real provider pricing; validated post-launch.

Jira/Linear + ADRs

Requirements tracking plus a short markdown Architecture Decision Record — the answer, six months later, to "why didn't we just fine-tune?"

Little's Law + k6/Locust

Back-of-envelope throughput math on paper, validated later with real load tests.

trade-offs & challenges

The "let's use an LLM" trap

99% correct isn't acceptable for arithmetic that used to be a formula. Mitigation: require written justification any time probabilistic logic touches a compliance-sensitive computation.

TTFT vs. throughput tension

Streaming holds a connection open for the whole generation, straining the pool under concurrency. Mitigation: multiplexed protocols like SSE over raw long-lived sockets.

Cost model blind spots

Agentic/retry flows have a fatter cost tail — budget on P90, not average. Output tokens, priced 3–5x higher, make prompt-only estimates look artificially cheap.

NextPhase 02 → Architectural Decision Frameworks & Model Selection
Phase 02 / 07

Architectural Decision Frameworks & Model Selection

Phase 1 told you whether to use an LLM. Phase 2 commits you to which technique and which model — and to a decision-making process you can defend later, not "we picked GPT-4 because everyone does."

the gist

Climb the technique ladder one rung at a time — pick the minimum viable technique that meets the NFRs, and force a justification before reaching for the next, more expensive rung.

5 rungsPrompt Eng. → RAG → GraphRAG → Fine-Tuning → RLHF/DPO
5 axesthe decision-matrix score: freshness, specificity, latency, cost, explainability

phase objectives

Build vs. Buy, and technique selection

"Train from scratch" is almost never right for application teams — the real decision is API vs. self-hosted OSS, hinging on data sensitivity, cost at scale, and latency control. Teams reach for fine-tuning because it feels like "real ML work," when prompt engineering or RAG would solve the actual problem more cheaply.

Multi-model routing strategy

Not every query deserves the most expensive, most capable model. A routing policy decides, per request, which model handles it — based on task complexity, context window, and cost target. This is a deliverable in its own right, even if implemented as a simple classifier.

fig. 2.1cascade model router
query cheap classifier complexity tier? Haiku-class — simple/short code-specialized model Opus-class — complex reasoning
The router itself must be cheap — a small model or non-LLM classifier — or it erases the savings it's supposed to create.

system components & topologies

The decision matrix

Score the problem 1–5 across five axes. Static facts + tone shift → Prompt Engineering. External/frequently-changing knowledge → RAG. Multi-hop reasoning over interconnected entities → GraphRAG. Durably changing behavior or format → Fine-tuning/LoRA.

tooling & tech stack

Claude / OpenAI / Gemini

Proprietary APIs — frontier capability, managed reliability, zero infra overhead.

Llama / Mistral / Qwen

Self-hosted OSS, served via vLLM, TGI, or Ray Serve — full data residency, own the ops burden.

LoRA / QLoRA — PEFT, Axolotl

Parameter-efficient fine-tuning, dramatically cheaper than full fine-tuning.

LiteLLM / OpenRouter / Martian

Model-agnostic routing gateways behind a unified API.

Neo4j / GraphRAG / Neptune

Graph databases and entity/relationship extraction for GraphRAG.

trade-offs & challenges

RAG vs. fine-tuning confusion

The rule of thumb worth memorizing: RAG for facts, fine-tuning for format/voice/task-specialization. Fine-tuning to "teach the model the product catalog" is almost always a RAG problem in disguise.

Vendor lock-in risk

Hardcoding to one provider's quirks means switching later means rewriting application logic. Mitigation: abstract behind a gateway with provider-agnostic schemas.

Router misclassification

A router sending a complex query to a cheap model doesn't error — it silently returns a worse answer. Mitigation: default to the larger model when confidence is low, and validate with shadow-routing.

The throughline: what's the cheapest thing that actually works? Prove it before scaling.
NextPhase 03 → Data Engineering, Vectorization & Governance
Phase 03 / 07

Data Engineering, Vectorization & Governance

Building the retrieval substrate that grounds the system in truth — and enforcing access control at the retrieval layer, not just the UI.

the gist

Most "the AI gave a wrong answer" bugs don't come from the model — they come from bad retrieval feeding it bad context. Filter access before scoring, never after.

pre-filterACL applied inside the vector DB query, not after
15 mina typical documented staleness SLA

phase objectives

Ingestion — idempotent, incremental, lineage-tracked

Idempotent: re-running the pipeline shouldn't duplicate vectors. Incremental: the whole corpus shouldn't need reprocessing on every change. Lineage-tracked: every chunk traces back to its source, version, and ingestion timestamp.

Chunking + embedding tuned to domain structure

A legal contract, a Slack export, and an API reference have completely different natural units of meaning — getting this wrong is one of the most common causes of vague, fragmented RAG answers.

Hybrid retrieval, tuned for recall and precision

Vector search alone misses exact-match cases (a SKU, an error code); keyword search alone misses semantic paraphrases. Combine both, plus graph traversal when Phase 2 calls for it.

system components & topologies

Governance enforcement point — pre-filter, not post-filter

ACL/metadata filters apply inside the vector DB query itself, restricting which vectors are even scored — never as a step run after retrieval to strip out unauthorized results. This is the single most consequential point in the whole phase.

fig. 3.1pre-filter vs. post-filter
bad — post-filter score top-20 strip unauthorized ← leakage risk good — pre-filter ACL filter first score allowed only ← never in candidate set
Restricted documents are never retrieved, scored, or seen by the model — there's no path for leakage.

Hybrid search topology

Query → [BM25/keyword] + [dense vector] + [optional graph traversal] → fusion (RRF or cross-encoder reranker) → top-K to the model. A cross-encoder is more accurate but too slow for the whole corpus, so it only reranks the cheap first pass's top candidates.

tooling & tech stack

Pinecone / Weaviate / Qdrant / pgvector

Vector databases — pgvector when Postgres is already running and fewer moving parts is worth it.

Airflow / Dagster / Unstructured.io

Ingestion orchestration and layout-aware parsing of PDFs, Word docs, HTML.

text-embedding-3 / Voyage / BGE / E5

Managed or self-hosted embedding models.

Presidio / OPA

PII masking at ingestion, and policy-as-code for ABAC rules evaluated at query time.

trade-offs & challenges

Chunking is a tuning knob, not a one-time decision

Too-small loses context; too-large dilutes the embedding. Mitigation: run chunk-size sweeps against the eval set, don't guess a number that "seemed reasonable."

RBAC-at-retrieval is the #1 RAG security gap

Many teams enforce access control only at the app layer, while the vector DB has no ACL awareness — a crafted prompt can surface chunks the user shouldn't see.

PII leakage through retrieval

Masking a customer's name before embedding can make that chunk unfindable later. Mitigation: mask for indexing, but gate the unmasked original behind the same ABAC policy.

NextPhase 04 → Agentic Workflows, Memory & Orchestration
Phase 04 / 07

Agentic Workflows, Memory & Orchestration

Choosing an agent topology proportional to task complexity — and making tool-calling deterministic and safe.

the gist

Default to the simplest agent topology that could work. Every agent-to-agent handoff is a place context gets lost, latency accumulates, and cost multiplies.

1 agentthe default — most production systems should live here
N×latency and cost multiplier for N agents in a chain

phase objectives

Topology proportional to task complexity

"Multi-agent" sounds sophisticated and is tempting, but every hand-off is a place things degrade. Start with the simplest topology; only add agents when the task genuinely decomposes into distinct roles.

Deterministic, safe tool-calling

The decision to call a tool can be probabilistic, but its execution should be as deterministic and safe as any other backend operation — validated schemas, idempotent side effects.

Short-term vs. long-term memory, kept distinct

Short-term: coherence within a session. Long-term: preferences and recurring facts across sessions. Conflating them produces a memory system that's neither a good buffer nor a good store.

fig. 4.1single-agent loop vs. multi-agent orchestration
single-agent — the default reason → act → observe multi-agent — earn it research draft review send each arrow = a full extra LLM call + a lossy handoff
Escalate to multi-agent only for genuine separation-of-concerns or parallelism — never because it sounds more sophisticated.

tooling & tech stack

LangGraph / AutoGen / CrewAI

Orchestration — state-machine or role-based conversation, or a bare Temporal/Step Functions state machine.

Redis / Zep / Mem0

Short-term session memory vs. dedicated long-term semantic memory stores.

Pydantic / Zod

Schema validation enforcing strict I/O contracts on every tool definition.

trade-offs & challenges

Multi-agent overhead

N agents ≈ N× the latency and cost of a single well-designed loop. Default single-agent; escalate only for genuine role separation or parallelism.

Runaway loops

Infinite retries or a planner/critic ping-pong. Mitigation: hard max-iteration count and a token/cost ceiling, with a graceful hand-off to a human.

Memory pollution

Long-term memory accumulates stale, contradictory facts. Mitigation: only persist explicitly confirmed facts, and define a conflict-resolution rule on read.

The throughline: default to the simplest topology, and treat every added agent, memory, and tool exposure as something that has to earn its place.
NextPhase 05 → Guardrails, Security & Evaluation
Phase 05 / 07

Guardrails, Security & Evaluation

Making the system safe to expose to real users, and measurable enough to improve with confidence — in CI/CD, not ad hoc.

the gist

The model's context window is a new attack surface — it can be persuaded by anything in it, including a retrieved document it never should have trusted as an instruction.

3 metricsthe RAG triad — faithfulness, answer relevance, context precision/recall
0the number of exceptions thrown by a silently misclassifying router

phase objectives

Defend against the OWASP Top 10 for LLMs

In a traditional web app the backend logic is trusted; in an LLM system the model itself is a decision-maker persuadable by anything in its context — including a retrieved document or a tool's output.

Real-time input/output guardrails

A layer inspecting both what goes in and what comes out, in real time, in the request path — fast enough not to blow the Phase 1 latency budget.

A repeatable evaluation harness in CI/CD

Turning "does this feel better?" into a number that runs automatically on every change — without it, every prompt tweak is a gamble evaluated by vibes.

fig. 5.1the guardrail pipeline
Input input guardrailjailbreak / PII / toxicity LLM output guardrailhallucination / format / PII Response
Guardrails run as fast, cheap classifiers — never another full LLM call stacked in series.

tooling & tech stack

NeMo Guardrails / Llama Guard

Programmable rails and purpose-built safety classifiers.

Ragas / TruLens / DeepEval / promptfoo

RAG-triad eval metrics and CI-friendly prompt regression testing.

garak

An LLM vulnerability scanner, analogous to a security scanner for a web app.

trade-offs & challenges

Guardrail latency tax

Stacking classifier calls adds to TTFT. Mitigation: cheap deterministic checks inline, heavier LLM-based guardrails only for cases the cheap pass flags as ambiguous.

LLM-as-Judge is not ground truth

A judge model favors longer, more confident-sounding answers regardless of correctness. Mitigation: periodically calibrate judge scores against human-labeled sets.

Eval sets go stale

A launch-time golden set stops representing real traffic as the corpus and users shift. Mitigation: mine production logs for hard cases and fold them in on a cadence.

NextPhase 06 → LLMOps, Infrastructure & Resilience
Phase 06 / 07

LLMOps, Infrastructure & Resilience

Operationalizing for production-scale reliability and cost control — treating prompts, models, and indexes as first-class deployable artifacts.

the gist

This is the phase that separates a working prototype from something that stays up at 3am when a provider has an incident.

1 gatewaysingle point of control for every model call
2 cachesexact-match prompt caching vs. cross-user semantic caching

phase objectives

A model gateway

Abstracts providers, handles failover, enforces rate limits. Without it, provider-specific logic gets scattered across the codebase, and switching providers means touching every call site.

Caching layers

Prompt caching reuses an exact repeated prefix — cheap, precise. Semantic caching reuses an answer to a similar-but-not-identical question — more powerful, riskier.

CI/CD for prompts, models & indexes

A prompt change is a deployment, with the same rigor as a code deployment — versioned, tested against regressions, rollback-capable.

fig. 6.1model gateway — five jobs
application model gateway routingload-balancefailoverqueueingcost attribution
A single ingress point — the same pattern as an API gateway in microservices, behind model providers instead.

tooling & tech stack

LiteLLM Proxy / Kong / Portkey

Gateway products, or AWS Bedrock's built-in cross-region failover for an AWS-native stack.

Redis + GPTCache

Exact and semantic caching, alongside native provider prompt-caching APIs.

GitHub Actions + promptfoo/Ragas

Eval suites as a merge gate turning Phase 5's harness into an enforced deployment gate.

vLLM/TGI on KServe / Ray Serve

Self-hosted serving with GPU autoscaling — or managed endpoints trading control for less ops burden.

trade-offs & challenges

Failover correctness

Failing over mid-conversation can silently change tone or safety posture. Mitigation: only failover between models validated as equivalent-tier, and log every event.

Cache staleness vs. hit rate

Semantic caching can serve an outdated answer. Mitigation: bind TTL to the data-freshness SLA, and wire invalidation to source-update events.

Rate-limit retry storms

Uniform retry-with-backoff can synchronize a burst right as a provider recovers. Mitigation: circuit breakers, jittered backoff, load-shedding.

NextPhase 07 → Monitoring, Observability & Feedback Loops
Phase 07 / 07

Monitoring, Observability & Feedback Loops

Closing the loop — knowing what the system is doing in production, catching degradation before users complain, feeding real signal back into evaluation.

the gist

User complaints are a lagging indicator. By the time enough people notice, a meaningful volume of degraded responses has already shipped.

3 kindsof drift — data, embedding, and output/semantic
2 signalsexplicit feedback (low volume, clear) vs. implicit (high volume, noisy)

phase objectives

Full traceability, request by request

Not "is it up" — but "is this individual request behaving correctly, and can I reconstruct exactly what happened when something goes wrong?"

Detect degradation before users complain

This is what separates reactive operations from proactive ones — catching the signal earlier than a support ticket.

Feed real signal back into evaluation

Without a return path, observability is just a read-only window; with it, the system actually improves over time from real usage.

fig. 7.1the continuous improvement flywheel
Production Trace + feedback Golden eval set CI/CD gate
Without the return path this is a dashboard. With it, the system gets better from real usage.

tooling & tech stack

LangSmith / Phoenix / Langfuse

Trace/span-level observability purpose-built for LLM call chains.

OpenTelemetry (GenAI conventions)

Vendor-neutral instrumentation — no lock-in to one platform's SDK.

Arize / WhyLabs / PSI

Embedding and data drift monitoring.

Segment/Amplitude + Label Studio

Feedback pipelines joined to trace IDs, feeding a human-labeling queue.

trade-offs & challenges

Drift alerts without action paths

An alert with no owner and no response trains people to ignore alerts. Mitigation: every drift type maps to a documented runbook with a named owner.

Feedback loop bias

Explicit feedback overrepresents power users and the highly frustrated. Mitigation: weight implicit signals more, and run periodic blind quality sampling.

Attribution in multi-agent systems

Pinpointing which component caused a regression needs span-level granularity — flat request logging doesn't have the resolution.

This phase closes the loop: drift signals and feedback feed back into Phase 5's eval set, which gates Phase 6's CI/CD deployments, which are observed again here.
NextCapstone → Enterprise Knowledge & Action Assistant
Capstone

Enterprise Knowledge & Action Assistant

Where everything from Phases 1–7 gets applied to one concrete system, so the decisions can be seen interlocking rather than existing as seven separate frameworks.

the scenario

One assistant, three execution paths: RBAC-scoped document Q&A (RAG), live data lookups via SQL tool-calling, and real workflow triggers — forcing every phase's decisions to interact with each other.

applying the seven phases

01
Classification & NFRs. Document Q&A is genuinely probabilistic; "what's my PTO balance" is a deterministic lookup wearing conversational clothing. Three execution paths, not one pipeline — RAG tolerates TTFT < 800ms, SQL lookups need p95 < 2s.
02
Routing & tiering. A router classifies intent into knowledge_query / data_query / action_trigger. RAG gets a mid-tier model; SQL/action get a fast, cheap model built for structure; cross-domain questions escalate to the largest model.
03
Retrieval & governance. Documents are ACL-tagged per source system. Pre-filter RBAC means a Sales employee can't surface HR salary data — those chunks are never candidates in the first place.
04
Orchestration. A LangGraph orchestrator with three nodes maps to the three intents. SQL runs under a read-only role; workflow writes are idempotent and pause for human confirmation before executing.
05
Guardrails. SQL calls pass through an allow-list guardrail against the known schema. RAG answers run a faithfulness check before returning. Workflow triggers get logged as high-risk spans regardless of guardrail pass/fail.
06
Infrastructure. The gateway sits in front of the router with equivalence-validated failover. Semantic caching applies only to the knowledge path — SQL/action answers are user-specific and never cached across users.
07
Observability. Full OTel tracing per step. Faithfulness scoring runs on 100% of RAG responses at this volume — not sampled. Thumbs-down feedback routes to human review and folds into the golden eval set weekly.
fig. cs.1end-to-end pipeline topology
Employee (UI) ── HTTPS ──▶ API Gateway (AuthN/AuthZ) ──▶ Intent Router
                                                              │
                              ┌───────────────────────────────┼───────────────────────────────┐
                              ▼                               ▼                               ▼
                     RAG Retriever Node              SQL Tool-Calling Node           Workflow Trigger Node
                     hybrid search + RBAC filter      read-only role + schema         idempotent + confirmation
                              │                               │                               │
                              ▼                               ▼                               ▼
                     Vector DB (ACL-tagged)          Live DB (read replica)          Workflow Engine (Temporal)
                              └───────────────────────────────┴───────────────────────────────┘
                                                              ▼
                                                       Model Gateway
                                             failover · prompt + semantic cache
                                                              ▼
                                              LLM (routed by complexity tier)
                                                              ▼
                                                     Output Guardrails
                                            faithfulness · PII/toxicity · format
                                                              ▼
                                                    Response → Employee
                                                              ▼
                                            Observability & Feedback Loop ──▶ back into Phase 5 eval set
Three execution paths converge on shared gateway, guardrail, and observability infrastructure — built once, reused by every path.

why this holds up under interview scrutiny

A staff-level interviewer isn't scoring whether a vector DB box and an LLM box got drawn. They're checking whether every arrow can be explained — why the SQL path hits a replica, why RBAC filtering happens inside the vector DB query, why workflow triggers pause for confirmation while RAG answers don't. Each is a specific failure mode from one of the seven phases; the diagram is a compressed record of seven phases' worth of "here's what goes wrong, and here's the decision that prevents it."

Enddevwithabhinav.in · AI System Design & SDLC
get in touch

Open to senior/lead remote roles

Especially where enterprise .NET meets AI agent engineering — reach out, or see the Microsoft Agent Framework build this playbook draws on.