Module 1 · Foundations · Lesson 2 of 14
The IChatClient Middleware Pipeline: Caching, Telemetry and Custom Guards
Predict calls and spans before running
A support endpoint receives A, A, B and an over-budget request. The pipeline runs a guard, cache, telemetry decorator and fake model in that order.
- Predict. Trace which requests reach the cache, telemetry and model.
- Test locally. In a separate copy move telemetry outside the cache. Compare request spans with provider calls. Account for cached usage separately.
Check the decision
Trace the four inputs through the pipeline before running. The decision question follows the local example.
Trace and explain
| Request | Reaches the cache? | Reaches inner telemetry? | Reaches the model? |
|---|---|---|---|
| First A | Fill in | Fill in | Fill in |
| Repeat A | Fill in | Fill in | Fill in |
| B | Fill in | Fill in | Fill in |
| Over-budget request | Fill in | Fill in | Fill in |
Explain which layer acts on each boundary.
Reference and worked examples
Intuition
Each chat decorator wraps the next client. The outer layer sees the request first and can return before inner layers run. Place request authorization before a cache, and count actual provider work where requests reach the provider.
Deep dive
- Build the chain. Use
AddChatClientorChatClientBuilder. The firstUseis outermost. Built-in options include function invocation, logging, default options, distributed caching and OpenTelemetry. - Cover both request paths. A custom
DelegatingChatClientcan overrideGetResponseAsyncandGetStreamingResponseAsync. Use that boundary for input limits, tenant options, redaction or appropriate resilience rules. - Scope a cache hit. Check the key policy for your package version. Include trusted authorization scope, history, effective model and relevant prompt/data context. Decide how expiry and invalidation work. Bypass the cache when testing fresh model behavior. Reuse effectful or changing tool results only under an explicit safe policy.
- Test cache fidelity. Cached JSON may preserve less than a provider's raw response. Test the relevant content on cached and uncached paths. Response caching and provider prompt-prefix caching have different contracts. Semantic caching can reuse a wrong answer when two prompts look similar.
- Observe only what you need. Configure tracing, metrics, sampling and export explicitly. Use
EnableSensitiveData = falsewhen content capture is prohibited. In 10.10.0,OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT=truecan enable the default. Metadata and other logs need separate privacy checks.
Code example: a four-component pipeline
- Restore the local project. Use the .NET 10 SDK,
Microsoft.Extensions.AIversion10.10.0, and compatibleMicrosoft.Extensions.DependencyInjectionandMicrosoft.Extensions.Caching.Memorypackages. Put Lesson 1's support types inFakeAI.csand this block inProgram.cs. After restore this fake runs offline with no model key. - Keep the fixture's scope. The memory cache lives in one process. Requests are sequential. The local ActivityListener records spans without a metrics listener, exporter or dashboard. The reflection-based chain display depends on implementation details. This program installs no tool invoker.
- Check the guard's boundary. It estimates non-streaming input text. It does not cover provider tokenization, other modalities, tool schemas, output, retries or concurrent spending. Bound input before enumerating it. Add equivalent streaming policy when your API supports it.
// A middleware pipeline around IChatClient: custom budget guard, response cache, OpenTelemetry and function
// invocation are all decorators, composed with ChatClientBuilder. The inner client is the FAKE scripted model.
using System.Diagnostics;
using FakeAI;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
var fake = new FakeChatClient((m, o) => new ChatMessage(ChatRole.Assistant, $"Answer to: {m[^1].Text}"));
var cache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions()));
// Capture the spans the OpenTelemetry middleware emits (a real app exports them with the OTel SDK).
var spans = new List<Activity>();
using var listener = new ActivityListener
{
ShouldListenTo = s => s.Name == "demo-ai",
Sample = (ref ActivityCreationOptions<ActivityContext> _) => ActivitySamplingResult.AllDataAndRecorded,
ActivityStopped = spans.Add,
};
ActivitySource.AddActivityListener(listener);
var services = new ServiceCollection();
services.AddChatClient(fake) // the order of Use* calls = outermost first
.Use(inner => new BudgetGuard(inner, maxInputTokens: 60))
.UseDistributedCache(cache)
.UseOpenTelemetry(sourceName: "demo-ai", configure: c => c.EnableSensitiveData = false);
using var sp = services.BuildServiceProvider();
var chat = sp.GetRequiredService<IChatClient>();
foreach (var q in new[] { "What is HybridCache?", "What is HybridCache?", "What is output caching?" })
{
var r = await chat.GetResponseAsync(q);
Console.WriteLine($"{q,-26} -> {r.Text,-36} model calls so far: {fake.Calls}");
}
try { await chat.GetResponseAsync(string.Join(' ', Enumerable.Repeat("very long question", 30))); }
catch (InvalidOperationException e) { Console.WriteLine($"budget guard: {e.Message}; model calls so far: {fake.Calls}"); }
Console.WriteLine($"spans recorded: {spans.Count}");
foreach (var a in spans.Take(1))
{
Console.WriteLine($"span name: {a.DisplayName}");
foreach (var tag in a.TagObjects.OrderBy(t => t.Key)) Console.WriteLine($" {tag.Key} = {tag.Value}");
}
Console.WriteLine("pipeline (outer -> inner): " + string.Join(" -> ", Chain(chat)));
static IEnumerable<string> Chain(IChatClient c)
{
for (IChatClient? x = c; x is not null; x = (x as DelegatingChatClient)?.GetType().GetProperty("InnerClient", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)?.GetValue(x) as IChatClient)
yield return x.GetType().Name;
}
/// <summary>Non-streaming demo: reject over-budget text estimates before calling the next client; not a hard billing limit.</summary>
sealed class BudgetGuard(IChatClient inner, int maxInputTokens) : DelegatingChatClient(inner)
{
public override Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken ct = default)
{
var snapshot = messages.ToList();
int estimate = Tokens.Estimate(snapshot);
if (estimate > maxInputTokens) throw new InvalidOperationException($"estimated {estimate} input tokens > budget {maxInputTokens}");
return base.GetResponseAsync(snapshot, options, ct);
}
}Why are there two inner telemetry spans for the three successful requests?
Show answer
Correct answer: A
The fixture samples its source and awaits requests sequentially. Only the two misses reach that particular decorator.
Option B: The fixture does not reject an unauthenticated request; the repeated request returns early from the outer cache.
Option C: The count follows the two cache misses, not a rule that drops every third telemetry span.
Option D: The inner implementation is a fake; span count does not establish a paid-model invocation.
Hint: Draw the early-return path.
Output (.NET 10, Microsoft.Extensions.AI 10.10.0, FAKE model)
Run the project and check the layer reached by each request. Compare cached response usage with new model calls. Telemetry names and fields can vary by package version and sampling.
Code walkthrough
- Follow a hit and a miss. A hit can return before inner telemetry. Use an outer request span, inner model spans and explicit cache metrics to distinguish them.
- Locate rejection. The guard applies before cache access and model work. A rejected request can still use application resources.
- Read sampled metadata. Inspect the model, finish reason and usage when supplied. Keep fake estimates and replayed usage separate from real provider accounting. Record missing usage as unknown.
Failure modes
- Missing trusted cache scope, model/prompt/data version or authorization checks. Partition/cache-key explicitly; test that the chosen key implementation actually includes the intended context.
- Telemetry with
EnableSensitiveData = truein production: prompts containing personal data end up in your APM. - Confusing input limits, user quotas and provider budgets. Keep authorization/safety checks on every request; provider-spend guards may belong at the miss/attempt boundary with atomic reservations and reconciliation.
- Caching responses that depend on time or on tool results (prices, order status).
- Forgetting to override
GetStreamingResponseAsyncin custom middleware, so streaming calls skip your guard.
Interview angle
Scenario: several API endpoints share one model budget.
- Authorize before reuse, and choose the trusted cache scope deliberately.
- Separate request, cache and provider telemetry. Track tool rounds and retries.
- Reserve and reconcile spend across requests. Enable only the content logging your policy permits.
Practice questions
- In
builder.Use(A).Use(B), which runs first on a request?
Answer: A. The first Use is the outermost layer.
- How can you record all app requests and still distinguish calls that reach the model?
Answer: Use an outer request span, inner provider spans and explicit cache hit/miss metrics.
- What does
EnableSensitiveDatacontrol?
Answer: It controls raw input/output capture by this telemetry decorator. In 10.10.0 an environment setting can enable the default; explicitly false disables that capture. It does not sanitize all metadata, errors or other instrumentation.
- Name a risk of response caching in a multi-tenant app.
Answer: Cross-tenant leakage when the cache key does not include tenant or user scope.
Related on TechInterviewNotes
- Lesson: Output caching, HybridCache and rate limiting (same decorator idea for HTTP)
- Lesson: Cache keys, tenant boundaries and cache-aside reads
- Course: Prompt Engineering for .NET Developers
Practice
TechInterviewNotes Editorial Team · Updated 24 Nov 2026 ·