Black Friday Deals For Authors Are On Now!

Leanpub Header

Skip to main content

Production-Grade RAG with C# and .NET

Building Retrieval-Augmented Generation Systems with C#, the Microsoft Agent Framework, and Azure

Production-Grade RAG with C# and .NET
This book is 100% completeLast updated on 2026-11-29

 The second edition of the .NET RAG book that measures before it tunes. Build Contoso SmartDocs in C#, from a first measured baseline to a reproducible production capstone, with authorization at every boundary, a regression gate and a release floor, failure labs and Microsoft Agent Framework 1.28.0. Twenty-nine chapters, 825 pages, runnable .NET 10 code.

Minimum price

$34.99

$46.99

You pay

Author earns

$

Also available for 2 book credits with a Reader Membership

Buying multiple copies for your team? See below for a discount!

PDF
Discussion Forum
About

About

About the Book

Production-Grade RAG with C# and .NET, Second Edition, is about the gap between a RAG demo that works and a system you can trust. The demo answers the easy question. The system has to say when the documents can't answer, keep two users with different permissions apart, and survive an index update without losing the last version that worked.

It is written for .NET developers with a few years of C# behind them who want to ship something useful over their company's documents. You don't need to know the Microsoft Agent Framework, vector databases or graph databases before you start. The only prerequisite is C#.

Across twenty-nine chapters in seven parts and 825 pages, you build Contoso SmartDocs, a knowledge assistant in front of six document silos, from a small console program in Chapter 1 to a composed, validated application in Chapter 29. The code targets .NET 10 and C# 14 with Microsoft Agent Framework 1.28.0, Microsoft.Extensions.AI 10.11.1, the ModelContextProtocol SDK 2.4.0 and Qdrant.Client 1.20.0.

What you'll build, part by part:

•         Foundations. When RAG is the right tool, a reproducible .NET environment, and a first measured baseline on a pinned 40-case gold set, taken before you tune anything.

•         The RAG pipeline. Embeddings, document contracts and reliable ingestion, chunking with Contextual Retrieval, multimodal evidence, vector indexes, indexing representations, hybrid retrieval, reranking, and context assembly with citations and streaming.

•         Access and query intelligence. Authorization first, with one disclosure guard applied at search, the reranker, caches, citations, tools, agents and sessions. Then metadata filters, query construction, routing and conversational rewriting.

•         Graph and hybrid storage. Graph data with entity resolution, and single-store hybrid on PostgreSQL, Qdrant and Azure AI Search (plus a SQL Server recipe), held to one set of conformance cases, with a plain account of what those cases do and don't prove.

•         RAG design patterns. Measured enhancements such as HyDE, RAG-Fusion and CRAG, structural and vectorless retrieval, GraphRAG with deferred graph retrieval, MCP as a secure contract, and bounded agents with workflows and memory.

•         Production concerns. Evaluation and release decisions, with a regression gate kept apart from an absolute quality floor and a dated run against real local models; latency and cost, freshness and model migration, security testing, governance, and five reproducible failure labs that break things on purpose.

•         The capstone. Named compositions validated at startup, a supported storage topology, index generations for cutover, and a release dossier with known limits.

Every SmartDocs listing is copied from a file in the companion repository and names that file on its first line. When a chapter prints output, the code produced it. Numbers that could not be measured or sourced are not in the book, and facts that change with releases carry a date.

"Production-grade" here means a reference architecture with production disciplines, not a turnkey deployment. The book keeps what the code guarantees and tests apart from the exercises and the known gaps. The local backends (Qdrant, PostgreSQL with pgvector, Neo4j, Ollama and the ONNX reranker) passed a dated live run; the Azure deployment shape compiles and is tested offline but has never been deployed, and the book says so. The repository has one page that lists each level of evidence.

Nine appendices round it out: worked solutions for the Practice exercises; a quick reference of the design patterns; a backend comparison workbook you fill in with your own measurements; an embedding experiment protocol; a Python-to-.NET Rosetta for readers arriving from LangChain, LlamaIndex or RAGAS; a guide to the companion repository; a debugging checklist that runs from symptom to cause to fix; a catalog of every prompt template the chapters use; and the math behind RAG. A References and Further Reading section and an index close the book.

The free sample is all of Part I, Foundations: Chapters 1 to 3, ending on the measured baseline.

The companion code lives at https://github.com/RachidD68/production-grade-rag-with-csharp-and-dotnet, on the main and edition-2 branches (tag v2.0.0): thirty runnable sample projects beside the SmartDocs solution. dotnet test from the repository root needs no service and no API key; the tests that need a live service or a second build skip themselves and name the RUN_* variable that turns them on, and the real-model reranker test stays skipped until you add the model files.

Team Discounts

Team Discounts

Get a team discount on this book!

  • Up to 3 members

    Minimum price
    $81.00
    Suggested price
    $109
  • Up to 5 members

    Minimum price
    $128
    Suggested price
    $172
  • Up to 10 members

    Minimum price
    $245
    Suggested price
    $329
  • Up to 15 members

    Minimum price
    $349
    Suggested price
    $469
  • Up to 25 members

    Minimum price
    $525
    Suggested price
    $705

Bundle

Bundles that include this book

Author

About the Author

Rachid DAHIR

I design systems for the long haul.

As a software architect, technical author, and educator based in Morocco, I've spent more than a decade building enterprise-grade .NET solutions in financial services, healthcare, and large-scale enterprise environments — where reliability, performance, and clean architecture are not optional.

I write for developers who are ready to move past tutorials. My books share a deliberate standard: production-grade code only — no toy examples, no shortcuts that would never survive a code review; every concept explained, demonstrated, then practiced; every advanced topic taught with the same patience as an introductory one — because complexity is never an excuse for a poor explanation.

Whether you're a mid-career developer leveling up, a solution architect consolidating best practices, or an enterprise team standardizing modern .NET, my goal stays the same: clarity without compromise.

When I'm not writing code or prose, I explore mathematics, AI research, and natural health.

Contents

Table of Contents

Front Matter

  • Preface
  • How to Read This Book
  • Read This First: RAG Vocabulary at a Glance
  • About the Author

Part I — Foundations

  1. Choosing RAG for the Right Problem
    • What Production-Grade Means in This Book
    • What an LLM Is, and Why Parametric Memory Hallucinates
    • Five Building Blocks: LLMs, Retrieval, RAG, Agents, and Workflows
    • The Honest Comparison: RAG, Long Context, Fine-Tuning, and Direct Tools
    • Cost Is a Calculation, Not a Ratio
    • When Not to Use RAG
    • The Evolution Arc: From the 2020 Paper to Graphs and Agents
    • MCP, RAG, and Agent Skills: Three Different Boundaries
    • Two Phases and One Evidence Trail
    • Your First RAG in Ten Minutes
    • What Counts as a Successful First Run
  2. The .NET Toolkit and Reproducible Environments
    • The cohort this book is built on
    • The two abstractions the code is built on
    • Ollama: use OllamaSharp, not Microsoft.Extensions.AI.Ollama
    • AddSmartDocsCore unpacked
    • Resilience has to reach the transport
    • Configuration: appsettings.json and user-secrets
    • Migrating from Semantic Kernel to MAF
    • TokenCounter, the utility you'll use everywhere
    • The companion solution layout
    • A reproducible environment
    • The package map: what to add, and when
    • Local development: native services, not cloud-by-default
  3. Your First Measured RAG Baseline
    • What a baseline is, and what it isn't
    • Pin the gold set before you look at an answer
    • Run the composition you mean to measure
    • One record per case, failures included
    • Four outcomes, not one score
    • Measure retrieval at one consistent unit
    • Run the first measured baseline
    • Compare runs case by case
    • Replacing the stand-ins with real models
    • A passing gate is not a good system

Part II — The RAG Pipeline

  1. Embeddings and Retrieval Benchmarks
    • What an embedding actually is
    • Token limits and silent truncation
    • Cosine, dot product, Euclidean: which one to use
    • Asymmetric embeddings: query vs document
    • The 2026 embedding leaderboard
    • Domain adaptation: when default embeddings aren't enough
    • The EmbeddingService domain port
    • Batching and rate-limit handling
    • Multilingual: one model or query translation
    • Matryoshka representations and dimension trimming
    • Benchmarking embeddings on your own corpus
  2. Document Contracts and Reliable Ingestion
    • Where the naive re-ingest path breaks
    • Name the identities before naming the tables
    • Primary evidence and derived representations
    • The registry: one record per document
    • Prepare, validate, publish, collect
    • Running the lifecycle end to end
    • Making the registry durable
    • Events that arrive late, twice, or not at all
    • Deletion is its own operation
    • One lifecycle, two scopes
    • Freshness is a measurable promise
    • Testing the contract
  3. Chunking and Contextual Retrieval
    • Why chunking is the highest-leverage tuning knob
    • The four classic strategies
    • The chunk-size question
    • Characters versus tokens: sizing chunks the model's way
    • Where every classic strategy breaks: the context problem
    • Anthropic's Contextual Retrieval
    • The numbers Anthropic reported
    • Measuring the ladder on SmartDocs
    • The cost question, and prompt caching
    • When the document is code: Roslyn-aware chunking
    • Wiring chunking into the SmartDocs pipeline
    • When contextual retrieval isn't worth it
    • A cheaper cousin: Late Chunking
    • The ChunkingPlayground sample
  4. Multimodal Evidence from Documents
    • What multimodal embedding models do
    • Three architectural patterns
    • One space, one dimension: the constraint everyone forgets
    • PDF processing: the silent killer
    • A visual answer needs a visual locator
    • Tables: the in-between case
    • Wiring multimodal into SmartDocs
    • Grounding an answer in the image itself
    • Test missing and contradictory modalities
    • When pure text wins
  5. Vector Indexes and Storage Decisions
    • What HNSW actually does
    • Tuning HNSW: the three knobs that move recall
    • How much RAM will this need?
    • The .NET landscape in late 2026
    • IVectorStore: the abstraction SmartDocs actually uses
    • Storage keys, and why upsert is idempotent
    • Payload co-location: keep the text next to the vector
    • Creating a collection: the pitfalls
    • Filtering: where the predicate runs
    • One contract, three stores: adapter conformance tests
    • Quantization: the memory lever
    • The index format is part of the contract
    • Measuring it: recall@k and latency percentiles
    • The comparison sample
    • Hybrid stores (forward reference)
    • Choosing the right backend
  6. Indexing Representations and Parent Evidence
    • Strategy 1: full-chunk indexing (the default)
    • Strategy 2: summary indexing
    • Strategy 3: sub-chunk (small-to-big) indexing
    • Strategy 4: hypothetical-question (query) indexing
    • One identity per representation
    • Resolving hits to parent evidence
    • What the strategies actually score
    • Choosing per use case
    • The cost surface
    • Wiring into SmartDocs
    • Keeping the index fresh: updates, deletes, and re-embedding
  7. Dense, Lexical, and Hybrid Retrieval
    • Dense retrieval (vector search)
    • Lexical retrieval (BM25 and friends)
    • Hybrid retrieval: dense and lexical together
    • Reciprocal Rank Fusion: the math
    • Measuring hybrid on the SmartDocs gold set
    • Tuning hybrid: the constant, weights, and oversampling
    • Fusion inside the store
    • Late interaction (briefly)
    • Choosing K
    • Diversity: trimming redundant results
    • Score thresholding and abstention
    • The retriever contract
    • Wiring into SmartDocs
  8. Reranking and Evidence Selection
    • What a cross-encoder does differently
    • Choosing a reranker
    • The IReranker interface
    • The headline numbers, and the measurement trap
    • LLM-as-reranker
    • A self-hosted cross-encoder (ONNX BGE)
    • Latency budget for rerank
    • When NOT to rerank
    • Thresholding after rerank
    • Authorize the candidate pool before an external reranker
    • Wiring into the SmartDocs pipeline
  9. Context Assembly, Citations, and Streaming
    • Context engineering: a budget for every token
    • The pipeline shape
    • The augmentation step
    • Generation: streaming with IChatClient
    • Sources in context versus sources cited
    • The API endpoint: SSE
    • Error handling and partial responses
    • The Blazor consumer
    • The same context through an agent
    • Cost of a query: the prompt budget
    • Putting it together: the trace of one query

Part III — Access and Query Intelligence

  1. Authorization Across the RAG Pipeline
    • Where evidence crosses a boundary
    • Scope comes from the authenticated request
    • One guard, one rule
    • Boundary one: the vector store exit
    • Boundary two: before text leaves the process
    • Boundary three: caches
    • Boundary four: replayed answers and citations
    • Revocation is a normal path, with a number
    • Watching every boundary in one run
    • Tools, agents, graphs and sessions
    • Testing the composed path
  2. Metadata Filters and Query Construction
    • The two filtering positions
    • Designing the metadata schema
    • Filter expressions: MetadataFilter
    • The tenant contract
    • Query construction: from natural language to filter
    • The filter-then-search pipeline
    • Self-Query: a special case worth knowing
    • When the filter is too tight: relaxation
    • Operators beyond equality
    • Validating extracted values against the vocabulary
    • Security filters are auth-derived, never extracted
    • A few more filtering concerns
    • When NOT to construct queries
    • Filter caching
    • Wiring into SmartDocs
  3. Routing and Conversational Retrieval
    • Why route at all
    • The IQueryRouter interface
    • Three routing strategies, plus a cascade
    • The cheap-to-expensive cascade
    • Confidence, fallback, and the refuse path
    • Structured-output robustness
    • Conversational queries: the rewrite problem
    • Query rewriting with ConversationalQueryRewriter
    • When the rewrite should be a question
    • Managing conversation history beyond a magic number
    • A rewrite inherits subjects, never permissions
    • Wiring it all together
    • Fan-out and fusion: when a query hits more than one silo
    • The router and rewriter are an injection surface
    • Cost economics of routing and rewriting
    • Routing telemetry: cost and errors per route

Part IV — Graph and Hybrid Storage

  1. Graph Data and Entity Resolution
    • What a graph database stores that a vector store doesn't
    • Neo4j with Neo4j.Driver 6.5.1
    • Building the entity graph at ingest time
    • Entity resolution: from extracted names to one node
    • Provenance: every node remembers where it came from
    • Cypher in 60 seconds
    • The graph retriever interface
    • Bounded traversal under an authorization scope
    • Route to one, or run both and fuse
    • Vector + graph: GraphRAG (forward reference)
    • When NOT to reach for a graph
    • Wiring into SmartDocs
    • Testing graph code without a live Neo4j
  2. Hybrid Backends in Practice
    • The single-store options in late 2026
    • Postgres + pgvector + tsvector: the practical default
    • Qdrant native hybrid
    • Azure AI Search: hosted hybrid and the semantic ranker
    • A recipe for SQL Server and Azure SQL
    • The Microsoft Agent Framework pattern over Azure AI Search
    • Choosing among the three
    • One base filter, three dialects
    • Keeping three engines honest: the conformance cases
    • When two stores still win
    • Wiring into SmartDocs

Part V — RAG Design Patterns

  1. Measured RAG Enhancements
    • Measure before you enhance
    • HyDE: Hypothetical Document Embeddings
    • RAPTOR: Recursive Abstractive Processing for Tree-Organized Retrieval
    • RAG-Fusion: query expansion with RRF
    • Step-back prompting: retrieve the principles first
    • Self-RAG: when to retrieve at all
    • CRAG: Corrective RAG
    • Lost in the middle: ordering chunks in the prompt
    • Contextual compression: trimming chunks before generation
    • Chunk pre-injection: loading context before the first turn
    • Composing patterns
    • What we're not covering
    • Wiring into SmartDocs
  2. Structural and Vectorless Retrieval
    • The kind of corpus this works on
    • Building the structural index
    • Retrieval over the structural index
    • Getting from a question to an identifier
    • When structural beats vector cleanly
    • Folding structural into your stack
    • Authorizing the structural leg
    • Lexical retrieval: the other embedding-free pillar
    • Choosing a vectorless retriever
    • Normalizing the identifier before you look it up
    • Identity across versions, documents and parsers
    • From retrieved nodes to a cited answer
    • Things that bite at scale
    • Measuring it: the VectorlessRetrieval sample
  3. GraphRAG and Deferred Graph Retrieval
    • The global-question problem
    • GraphRAG: the eager indexing pipeline
    • GraphRAG by the numbers
    • When graphs actually help
    • The three query methods
    • LazyGraphRAG: the cost-shifting trick
    • The cost picture
    • When to choose eager
    • One graph, two modes
    • Implementation in SmartDocs
    • What GraphRAG can't do
  4. MCP Contracts and Secure Boundaries
    • What MCP actually is
    • The two standard transports
    • The .NET MCP SDK
    • Authorization at the boundary: one context, one guard
    • When the server needs something from the caller: multi-round-trip requests
    • The client side: calling MCP tools from a MAF agent
    • Notifications and subscriptions
    • The MCP-vs-A2A-vs-OpenAPI decision tree
    • Security: the part the spec leaves to you
    • Tool granularity: the design decision that decides UX
    • Composing MCP servers
    • Observability and deployment
    • Testing MCP servers
    • The two SmartDocs servers
  5. Bounded Agents, Workflows, and Memory
    • From single-agent RAG to multi-agent workflows
    • Bounding the run: budgets the code enforces
    • The Workflow graph: conditional and parallel edges
    • Agentic memory: semantic, episodic, procedural
    • Agent Skills: procedural memory you can version
    • CodeAct (a.k.a. Code Mode): one generated program instead of N tool calls
    • From demo to production: the concerns the prototype skips
    • Tool design for agents (vs APIs for humans)
    • Putting it together: the SmartDocs production agent
    • The MultiAgentOrchestration sample

Part VI — Production Concerns

  1. Evaluation and Release Decisions
    • Why eval is the unsexy multiplier
    • The five metrics that matter
    • Grade the answer you shipped, not the answer you wrote
    • The .NET-native eval library: Microsoft.Extensions.AI.Evaluation
    • RAGAS and DeepEval: when to leave .NET
    • LLM-as-judge: how it actually works (and where it fails)
    • Building the seed dataset
    • The release gate
    • Controlled baseline promotion
    • A regression gate is not a quality bar
    • Latency and cost as eval metrics
    • Ground-truth evaluation, the framework-native way (Agent Framework 1.28.0)
    • The eval-driven development loop
    • Evaluating for safety, not just quality
    • Online versus offline evaluation
    • What the eval can't tell you
  2. Latency, Cost, Caching, and Backpressure
    • A cost model you can recompute
    • The cache stack
    • The other half of cost: send fewer tokens
    • The latency budget per pipeline stage
    • .NET-specific performance levers
    • Resilience: one retry layer
    • Backpressure: refusing work early and honestly
    • Provisioned throughput and spillover
    • Observability: traces, metrics, cost
    • Avoid the premature optimizations
  3. Freshness, Generations, and Model Migration
    • Freshness as a first-class metric
    • Three ingest strategies
    • Orphan chunks and re-chunking on update
    • Index generations: publishing a whole index
    • Embedding drift: the silent killer
    • The Drift-Adapter pattern
    • Cache invalidation under document churn
    • GDPR Article 17 and the right to erasure
    • Schema migrations
    • Backfill scheduling
  4. Security Testing and Incident Response
    • The threat model
    • Layer 1: input layer
    • Layer 2: embedding layer
    • Layer 3: retrieval layer
    • Layer 4: output layer
    • Audit logs
    • Secret scanning at ingest
    • Supply-chain security
    • MCP-server trust hierarchy
    • Keyless authentication and infrastructure
    • Agentic-action security: least privilege and human approval
    • Testing the security boundaries
    • Incident response
  5. Governance and Evidence of Compliance
    • Start with intended use and owners
    • Impact assessments before deployment: DPIA and FRIA
    • Provider vs deployer: who owes what
    • The shape of the EU AI Act obligations
    • Conformity assessment, CE marking, and EU-database registration
    • The data-flow inventory
    • Citations as traceability evidence
    • Audit logs as action evidence
    • Consent and transparency
    • Lawful basis is not consent
    • Data residency, sovereignty, and cross-border transfers
    • Faithfulness as a contractual quality bar
    • Bias, fairness, and non-discrimination
    • Model cards and technical documentation
    • Annex IV technical documentation is not the model card
    • Human oversight
    • Post-market monitoring and serious incidents
    • Right to explanation
    • Copyright, corpus licensing, and output IP
    • The compliance dashboard
    • The right to erasure meets the embedding
    • The TrustByDesign sample, end to end
  6. Production Failure Labs
    • Evidence before edits
    • How the labs are built
    • Lab 1: the small tenant that gets nothing
    • Lab 2: the new generation nobody reads
    • Lab 3: tenant B reads tenant A's cached answer
    • Lab 4: deleted, but still answering
    • Lab 5: it compiles, then it fails
    • Turning a test red
    • Three incidents without a lab
    • Writing the incident record

Part VII — Capstone Project

  1. The Reproducible Production Capstone
    • Start from a named composition
    • The reference topology
    • Bicep: the resource graph as code
    • A pipeline that fails for the right reason
    • NuGet packaging for the public surface
    • Secret management
    • Smoke tests after deploy
    • Production hardening
    • Day-2 operations
    • The pre-flight checklist
    • The release dossier
    • Known limits of the reference deployment
    • Capacity planning
    • The day after launch
    • An alternative shape: vertical slices
    • Where this book ends and your work begins
    • Closing

Appendices

  • Appendix A — Solutions
  • Appendix B — Design Patterns
  • Appendix C — Backend Comparison Workbook
  • Appendix D — Embedding Experiment Protocol
  • Appendix E — Python to .NET Rosetta
  • Appendix F — Companion Repository Guide
  • Appendix G — Debugging Checklist
  • Appendix H — Prompt Engineering Patterns
  • Appendix I — The Math Behind RAG
  • References and Further Reading
  • Other Books You’ll Enjoy
  • Index

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub