In questo articolo

🧨 Perché un LLM va protetto come ogni dipendenza remota

Un modello linguistico, locale o cloud, è una dipendenza di rete come un'altra: a volte risponde in due secondi, a volte in venti, a volte non risponde. Se la mia API chiama il modello senza difese, ogni guasto del provider diventa un guasto mio.

In pratica vedo quattro situazioni. Servono quattro risposte diverse, e non sono la stessa risposta: ritentare aiuta con un errore passeggero, ma peggiora un provider già in crisi.

  • Errore passeggero (rete, 503, 429): ritento dopo una breve attesa → retry con backoff.
  • Risposta lentissima: smetto di aspettare → timeout per tentativo.
  • Provider in crisi: smetto di chiamarlo per un po' → circuit breaker.
  • Provider fuori uso: rispondo con un altro modello → fallback.

🧭 Cosa costruisco: due decorator di IChatClient

Costruisco una Minimal API in .NET 10 sopra l'astrazione IChatClient di Microsoft.Extensions.AI. Le difese sono decorator: classi che implementano IChatClient, ne avvolgono un altro e aggiungono un comportamento. Il resto dell'app non sa nulla di retry o fallback: dipende solo da IChatClient.

Il motore delle policy è Polly v8 (Polly.Core). Microsoft.Extensions.AI non include un fallback tra modelli, quindi lo scrivo io: sono poche decine di righe.

  • ResilientChatClient: un DelegatingChatClient con una pipeline Polly (retry → circuit breaker → timeout). Uno per ogni modello.
  • FallbackChatClient: prova i client in ordine e passa al successivo solo per errori che lo giustificano.
  • ChaosChatClient: un decorator da sviluppo che simula un'interruzione, per vedere le policy in azione.
Architettura della soluzione
Architettura: una richiesta POST /chat entra nel FallbackChatClient, che prova prima il client primary (llama3.2:3b) e poi il fallback (qwen2.5:0.5b); ogni client ha una pipeline con retry, circuit breaker e timeout verso Ollama.

Due client, ciascuno con la sua pipeline; il fallback scatta solo quando serve.

⬇️ Passo 1 · Progetto e pacchetti

Mi servono il .NET 10 SDK e Docker. Creo la soluzione, la Minimal API e il progetto di test, poi aggiungo i pacchetti. OllamaSharp fornisce un client Ollama che implementa già IChatClient.

Terminale · crea il progetto
dotnet new sln -n LlmResilience
dotnet new web -n LlmResilience.Api -o src/LlmResilience.Api
dotnet new xunit -n LlmResilience.Tests -o tests/LlmResilience.Tests
dotnet sln add src/LlmResilience.Api tests/LlmResilience.Tests
dotnet add tests/LlmResilience.Tests reference src/LlmResilience.Api

cd src/LlmResilience.Api
dotnet add package Microsoft.Extensions.AI
dotnet add package OllamaSharp
dotnet add package Polly.Core

fscamuzzi/llm-resilience-dotnet-polly-fallback · GitHub ↗

Soluzione, API e test. Codice completo nel repo: https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback

🐳 Passo 2 · Ollama con Docker Compose

L'unica dipendenza esterna è Ollama. Lo avvio con Docker Compose, con un healthcheck e un servizio one-shot che scarica i due modelli: uno più capace come primary (llama3.2:3b) e uno minuscolo come fallback (qwen2.5:0.5b).

In produzione il primary sarebbe tipicamente un modello cloud e il fallback un modello locale o di un altro provider: il codice non cambia, cambiano solo le due registrazioni.

docker-compose.yml
services:
  ollama:
    image: ollama/ollama:latest
    container_name: llm-resilience-ollama
    ports:
      - "11434:11434"
    volumes:
      - ollama-data:/root/.ollama
    healthcheck:
      test: ["CMD", "ollama", "list"]
      interval: 10s
      timeout: 5s
      retries: 12
      start_period: 10s

  ollama-init:
    image: ollama/ollama:latest
    container_name: llm-resilience-ollama-init
    depends_on:
      ollama:
        condition: service_healthy
    environment:
      OLLAMA_HOST: http://ollama:11434
    entrypoint: ["/bin/sh", "-c"]
    command:
      - |
        ollama pull llama3.2:3b &&
        ollama pull qwen2.5:0.5b
    restart: "no"

volumes:
  ollama-data:

fscamuzzi/llm-resilience-dotnet-polly-fallback · GitHub ↗

Ollama, healthcheck e download dei modelli. Codice completo nel repo: https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback

⚙️ Passo 3 · Opzioni tipizzate

Ogni soglia sta in una classe tipizzata legata ad appsettings.json: niente numeri magici nel codice. Poterli cambiare senza ricompilare è la parte utile, perché le soglie giuste si trovano osservando il sistema, non a tavolino.

ResilienceOptions.cs
namespace LlmResilience.Api.Options;

public sealed class ResilienceOptions
{
    public const string SectionName = "Resilience";

    public int MaxRetryAttempts { get; init; } = 2;
    public TimeSpan RetryBaseDelay { get; init; } = TimeSpan.FromMilliseconds(500);
    public TimeSpan AttemptTimeout { get; init; } = TimeSpan.FromSeconds(30);
    public double BreakerFailureRatio { get; init; } = 0.5;
    public int BreakerMinimumThroughput { get; init; } = 4;
    public TimeSpan BreakerSamplingDuration { get; init; } = TimeSpan.FromSeconds(30);
    public TimeSpan BreakerBreakDuration { get; init; } = TimeSpan.FromSeconds(20);
}

fscamuzzi/llm-resilience-dotnet-polly-fallback · GitHub ↗

Retry, timeout e soglie del circuit breaker. Codice completo nel repo: https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback

🎯 Passo 4 · Quali errori ritentare

È la decisione più importante. Ritentare un errore non transitorio (un prompt non valido, una chiave sbagliata) spreca tempo e, sul cloud, token. Ritento solo ciò che può passare da solo: errori di rete, 5xx, 429, 408 e i timeout.

Separo due domande: vale la pena ritentare sullo stesso client? (IsTransient) e vale la pena passare al client successivo? (ShouldFallBack). La seconda include anche il circuito aperto: se il breaker è aperto non ha senso ritentare, ma ha senso passare oltre.

TransientFailure.cs
using System.Net;
using Polly.Timeout;

namespace LlmResilience.Api.Resilience;

public static class TransientFailure
{
    // Errors worth another attempt on the same provider: network, 5xx, 429, 408, timeouts.
    public static bool IsTransient(Exception exception) => exception switch
    {
        HttpRequestException { StatusCode: null } => true,
        HttpRequestException { StatusCode: HttpStatusCode status } => IsTransientStatus(status),
        TimeoutRejectedException => true,
        TimeoutException => true,
        IOException => true,
        _ => false,
    };

    // Errors that justify moving to the next provider: transient ones plus an open circuit.
    public static bool ShouldFallBack(Exception exception) =>
        IsTransient(exception) || exception is Polly.CircuitBreaker.BrokenCircuitException;

    private static bool IsTransientStatus(HttpStatusCode status) =>
        (int)status >= 500
        || status == HttpStatusCode.TooManyRequests
        || status == HttpStatusCode.RequestTimeout;
}

fscamuzzi/llm-resilience-dotnet-polly-fallback · GitHub ↗

Classificazione degli errori: ritentare o passare oltre. Codice completo nel repo: https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback

🛡️ Passo 5 · ResilientChatClient: la pipeline Polly

Il cuore è un DelegatingChatClient che esegue ogni chiamata dentro una ResiliencePipeline. L'ordine delle strategie conta: il retry sta fuori, il circuit breaker in mezzo, il timeout dentro. Così il timeout vale per tentativo e il breaker vede ogni singolo fallimento, non solo l'esito finale del retry.

Il predicato è lo stesso per retry e breaker (IsTransient). Una BrokenCircuitException non è transitoria, quindi non viene ritentata: esce subito e lascia la decisione al fallback. Il breaker apre quando almeno il 50% delle chiamate nella finestra di 30 secondi fallisce, con un minimo di 4 chiamate.

  • Retry: backoff esponenziale con jitter, per evitare che tanti client ritentino insieme.
  • Circuit breaker: tiene lo stato (Closed, Open, HalfOpen) e lo espone con CircuitBreakerStateProvider.
  • Timeout: 30 secondi per tentativo; produce una TimeoutRejectedException, che è transitoria.
Ordine delle strategie e stati del breaker
Pipeline Polly: il retry avvolge il circuit breaker, che avvolge il timeout, che avvolge la chiamata a Ollama; a destra gli stati Closed, Open e HalfOpen del circuit breaker con le transizioni.

Il timeout vale per tentativo; il breaker vede ogni fallimento.

🧱 ResilientChatClient: il codice

Il costruttore costruisce la pipeline una volta sola. Ogni client ha la sua pipeline e quindi il suo circuit breaker: se il primary è giù, il fallback continua a funzionare.

ResilientChatClient.cs
using LlmResilience.Api.Options;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using Polly;
using Polly.CircuitBreaker;
using Polly.Retry;

namespace LlmResilience.Api.Resilience;

public sealed class ResilientChatClient : DelegatingChatClient
{
    private readonly ResiliencePipeline _pipeline;
    private readonly CircuitBreakerStateProvider _breakerState = new();

    public string Name { get; }

    public CircuitState Circuit => _breakerState.CircuitState;

    public ResilientChatClient(
        string name,
        IChatClient inner,
        ResilienceOptions options,
        ILogger logger) : base(inner)
    {
        Name = name;
        _pipeline = BuildPipeline(name, options, _breakerState, logger);
    }

    public override Task<ChatResponse> GetResponseAsync(
        IEnumerable<ChatMessage> messages,
        ChatOptions? options = null,
        CancellationToken cancellationToken = default) =>
        _pipeline.ExecuteAsync(
            async token => await base.GetResponseAsync(messages, options, token),
            cancellationToken).AsTask();

    public override async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
        IEnumerable<ChatMessage> messages,
        ChatOptions? options = null,
        [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        // Retry and breaker only protect the opening of the stream (up to the first update).
        var opened = await _pipeline.ExecuteAsync(
            async token => await StreamOpening.OpenAsync(
                base.GetStreamingResponseAsync(messages, options, token), token),
            cancellationToken);

        if (opened is null)
            yield break;

        await foreach (var update in StreamOpening.ReplayAsync(opened, cancellationToken))
            yield return update;
    }

    private static ResiliencePipeline BuildPipeline(
        string name,
        ResilienceOptions options,
        CircuitBreakerStateProvider breakerState,
        ILogger logger)
    {
        var handled = new PredicateBuilder().Handle<Exception>(TransientFailure.IsTransient);

        return new ResiliencePipelineBuilder()
            .AddRetry(new RetryStrategyOptions
            {
                ShouldHandle = handled,
                MaxRetryAttempts = options.MaxRetryAttempts,
                Delay = options.RetryBaseDelay,
                BackoffType = DelayBackoffType.Exponential,
                UseJitter = true,
                OnRetry = args =>
                {
                    logger.LogWarning(
                        args.Outcome.Exception,
                        "LLM client {Client}: attempt {Attempt} failed, retrying in {Delay} ms",
                        name, args.AttemptNumber + 1, (int)args.RetryDelay.TotalMilliseconds);
                    return default;
                },
            })
            .AddCircuitBreaker(new CircuitBreakerStrategyOptions
            {
                ShouldHandle = handled,
                FailureRatio = options.BreakerFailureRatio,
                MinimumThroughput = options.BreakerMinimumThroughput,
                SamplingDuration = options.BreakerSamplingDuration,
                BreakDuration = options.BreakerBreakDuration,
                StateProvider = breakerState,
                OnOpened = args =>
                {
                    logger.LogError("LLM client {Client}: circuit OPEN for {Duration} s", name, args.BreakDuration.TotalSeconds);
                    return default;
                },
                OnClosed = _ =>
                {
                    logger.LogInformation("LLM client {Client}: circuit CLOSED", name);
                    return default;
                },
            })
            .AddTimeout(options.AttemptTimeout)
            .Build();
    }
}

fscamuzzi/llm-resilience-dotnet-polly-fallback · GitHub ↗

DelegatingChatClient con retry, breaker e timeout. Codice completo nel repo: https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback

🌊 Passo 6 · Streaming: ritentare solo fino al primo token

Con lo streaming il discorso cambia. Una volta che il primo token è partito verso il client, non posso più ritentare: dovrei ricominciare la risposta da capo e il client ha già visto metà frase. Quindi la protezione agisce solo sull'apertura dello stream, fino al primo aggiornamento.

StreamOpening.OpenAsync chiede il primo elemento dell'enumeratore: se fallisce, l'eccezione passa dalla pipeline (retry, breaker, timeout) e dal fallback. Se riesce, ReplayAsync restituisce quel primo elemento e poi il resto dello stream. Un errore a metà stream, dopo, interrompe lo stream: è un limite del protocollo, non del codice.

StreamOpening.cs
using Microsoft.Extensions.AI;

namespace LlmResilience.Api.Resilience;

// A stream that already produced its first update: from here on a retry is no longer safe.
public sealed record OpenedStream(IAsyncEnumerator<ChatResponseUpdate> Enumerator, ChatResponseUpdate First);

public static class StreamOpening
{
    public static async Task<OpenedStream?> OpenAsync(
        IAsyncEnumerable<ChatResponseUpdate> stream,
        CancellationToken cancellationToken)
    {
        var enumerator = stream.GetAsyncEnumerator(cancellationToken);
        try
        {
            if (!await enumerator.MoveNextAsync())
            {
                await enumerator.DisposeAsync();
                return null;
            }

            return new OpenedStream(enumerator, enumerator.Current);
        }
        catch
        {
            await enumerator.DisposeAsync();
            throw;
        }
    }

    public static async IAsyncEnumerable<ChatResponseUpdate> ReplayAsync(
        OpenedStream opened,
        [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
    {
        await using var enumerator = opened.Enumerator;
        yield return opened.First;

        while (await enumerator.MoveNextAsync())
        {
            cancellationToken.ThrowIfCancellationRequested();
            yield return enumerator.Current;
        }
    }
}

fscamuzzi/llm-resilience-dotnet-polly-fallback · GitHub ↗

Apre lo stream fino al primo aggiornamento, poi lo riproduce. Codice completo nel repo: https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback

🔁 Il flusso dello streaming in un colpo d'occhio

Lo schema riassume dove le difese funzionano e dove no. Nella zona sicura posso ritentare e cambiare modello; dopo il primo token lo stream è impegnato e ogni errore si propaga al client.

Zona sicura e zona impegnata
Schema dello streaming: la zona sicura comprende apertura dello stream e primo MoveNextAsync, dove valgono retry, breaker, timeout e fallback; dopo il primo token i token arrivano al client e un errore interrompe lo stream.

Dopo il primo token non si torna indietro.

🔀 Passo 7 · FallbackChatClient

Il fallback prova i client in ordine. Passa al successivo solo se l'errore lo giustifica (ShouldFallBack); un errore non transitorio, come un prompt non valido, esce subito perché un altro modello non lo risolverebbe. Se falliscono tutti, lancia una LlmUnavailableException con tutti gli errori raccolti.

Segno anche quale client ha risposto in AdditionalProperties della risposta (llm.client): è il dato che poi metto nei log e nelle metriche, perché una risposta del fallback va riconosciuta.

FallbackChatClient.cs
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;

namespace LlmResilience.Api.Resilience;

public sealed class FallbackChatClient(
    IReadOnlyList<ResilientChatClient> clients,
    ILogger<FallbackChatClient> logger) : IChatClient
{
    public const string ClientProperty = "llm.client";

    public IReadOnlyList<ResilientChatClient> Clients { get; } = clients;

    public async Task<ChatResponse> GetResponseAsync(
        IEnumerable<ChatMessage> messages,
        ChatOptions? options = null,
        CancellationToken cancellationToken = default)
    {
        var chat = messages.ToList();
        var failures = new List<Exception>();

        foreach (var client in Clients)
        {
            try
            {
                var response = await client.GetResponseAsync(chat, options, cancellationToken);
                response.AdditionalProperties ??= [];
                response.AdditionalProperties[ClientProperty] = client.Name;
                return response;
            }
            catch (Exception exception) when (TransientFailure.ShouldFallBack(exception))
            {
                logger.LogWarning(exception, "LLM client {Client} failed, trying the next one", client.Name);
                failures.Add(exception);
            }
        }

        throw new LlmUnavailableException(failures);
    }

    public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
        IEnumerable<ChatMessage> messages,
        ChatOptions? options = null,
        [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        var chat = messages.ToList();
        var opened = await OpenFirstAvailableAsync(chat, options, cancellationToken);

        await foreach (var update in StreamOpening.ReplayAsync(opened, cancellationToken))
            yield return update;
    }

    public object? GetService(Type serviceType, object? serviceKey = null) =>
        serviceKey is null && serviceType.IsInstanceOfType(this) ? this : null;

    public void Dispose()
    {
        foreach (var client in Clients)
            client.Dispose();
    }

    private async Task<OpenedStream> OpenFirstAvailableAsync(
        List<ChatMessage> chat,
        ChatOptions? options,
        CancellationToken cancellationToken)
    {
        var failures = new List<Exception>();

        foreach (var client in Clients)
        {
            try
            {
                var opened = await StreamOpening.OpenAsync(
                    client.GetStreamingResponseAsync(chat, options, cancellationToken),
                    cancellationToken);

                if (opened is not null)
                    return opened;

                failures.Add(new InvalidOperationException($"{client.Name} returned an empty stream."));
            }
            catch (Exception exception) when (TransientFailure.ShouldFallBack(exception))
            {
                logger.LogWarning(exception, "LLM client {Client} failed to open the stream, trying the next one", client.Name);
                failures.Add(exception);
            }
        }

        throw new LlmUnavailableException(failures);
    }
}

fscamuzzi/llm-resilience-dotnet-polly-fallback · GitHub ↗

Catena ordinata di client, anche per lo streaming. Codice completo nel repo: https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback

💥 Passo 8 · ChaosChatClient: rompere il primary a comando

Per vedere le policy lavorare mi serve un guasto riproducibile. Il ChaosChatClient avvolge solo il primary e, in base a una modalità impostabile a runtime, lancia un 503 (Fail) oppure resta appeso fino al timeout (Slow). Si attiva con Llm:ChaosEnabled ed è pensato per sviluppo e demo, non per la produzione.

ChaosChatClient.cs
using Microsoft.Extensions.AI;
using System.Net;

namespace LlmResilience.Api.Resilience;

public enum ChaosMode
{
    Off,
    Fail,
    Slow,
}

public sealed class ChaosState
{
    private int _mode;

    public ChaosMode Mode
    {
        get => (ChaosMode)Volatile.Read(ref _mode);
        set => Volatile.Write(ref _mode, (int)value);
    }
}

// Development-only decorator: injects failures so the resilience policies can be observed.
public sealed class ChaosChatClient(IChatClient inner, ChaosState state) : DelegatingChatClient(inner)
{
    private static readonly TimeSpan SlowDelay = TimeSpan.FromMinutes(5);

    public override async Task<ChatResponse> GetResponseAsync(
        IEnumerable<ChatMessage> messages,
        ChatOptions? options = null,
        CancellationToken cancellationToken = default)
    {
        await InjectAsync(cancellationToken);
        return await base.GetResponseAsync(messages, options, cancellationToken);
    }

    public override async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
        IEnumerable<ChatMessage> messages,
        ChatOptions? options = null,
        [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        await InjectAsync(cancellationToken);

        await foreach (var update in base.GetStreamingResponseAsync(messages, options, cancellationToken))
            yield return update;
    }

    private async Task InjectAsync(CancellationToken cancellationToken)
    {
        switch (state.Mode)
        {
            case ChaosMode.Fail:
                throw new HttpRequestException("Chaos: simulated provider outage.", null, HttpStatusCode.ServiceUnavailable);
            case ChaosMode.Slow:
                await Task.Delay(SlowDelay, cancellationToken);
                break;
        }
    }
}

fscamuzzi/llm-resilience-dotnet-polly-fallback · GitHub ↗

Iniezione di guasti per le demo. Codice completo nel repo: https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback

🧩 Passo 9 · Registrazione e endpoint

Un'unica extension method, AddResilientChat, costruisce i due client, li avvolge e registra il FallbackChatClient come IChatClient. Il HttpClient ha il timeout infinito di proposito: la scadenza la decide Polly, per tentativo, non un valore globale nascosto.

ServiceCollectionExtensions.cs
using LlmResilience.Api.Options;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Options;
using OllamaSharp;

namespace LlmResilience.Api.Resilience;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddResilientChat(this IServiceCollection services, IConfiguration configuration)
    {
        services.Configure<LlmOptions>(configuration.GetSection(LlmOptions.SectionName));
        services.Configure<ResilienceOptions>(configuration.GetSection(ResilienceOptions.SectionName));
        services.AddSingleton<ChaosState>();

        services.AddSingleton(provider =>
        {
            var llm = provider.GetRequiredService<IOptions<LlmOptions>>().Value;
            var resilience = provider.GetRequiredService<IOptions<ResilienceOptions>>().Value;
            var chaos = provider.GetRequiredService<ChaosState>();
            var loggers = provider.GetRequiredService<ILoggerFactory>();

            IChatClient primary = CreateOllama(llm.Endpoint, llm.PrimaryModel);
            if (llm.ChaosEnabled)
                primary = new ChaosChatClient(primary, chaos);

            var fallback = CreateOllama(llm.Endpoint, llm.FallbackModel);

            return new FallbackChatClient(
                [
                    new ResilientChatClient("primary", primary, resilience, loggers.CreateLogger("LlmResilience.primary")),
                    new ResilientChatClient("fallback", fallback, resilience, loggers.CreateLogger("LlmResilience.fallback")),
                ],
                loggers.CreateLogger<FallbackChatClient>());
        });

        services.AddSingleton<IChatClient>(provider => provider.GetRequiredService<FallbackChatClient>());
        return services;
    }

    // The HttpClient timeout is disabled on purpose: the Polly timeout owns the deadline.
    private static OllamaApiClient CreateOllama(string endpoint, string model) =>
        new(new HttpClient { BaseAddress = new Uri(endpoint), Timeout = Timeout.InfiniteTimeSpan }, model);
}

fscamuzzi/llm-resilience-dotnet-polly-fallback · GitHub ↗

Composizione dei client e dei decorator. Codice completo nel repo: https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback

🌐 Gli endpoint: 503 pulito invece di un errore generico

Se falliscono tutti i client, l'API risponde 503 Service Unavailable con un ProblemDetails, non un 500. È il segnale corretto per un client che sa ritentare più tardi. Per lo streaming apro il flusso prima di restituire la risposta: così un'interruzione totale diventa un 503 vero e non una risposta 200 interrotta.

ChatEndpoints.cs
using System.Diagnostics;
using System.Net.ServerSentEvents;
using LlmResilience.Api.Contracts;
using LlmResilience.Api.Resilience;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.Extensions.AI;

namespace LlmResilience.Api.Endpoints;

public static class ChatEndpoints
{
    public static IEndpointRouteBuilder MapChatEndpoints(this IEndpointRouteBuilder app)
    {
        app.MapPost("/chat", ChatAsync);
        app.MapPost("/chat/stream", StreamAsync);
        app.MapGet("/llm/status", Status);
        app.MapPut("/chaos", SetChaos);
        return app;
    }

    private static async Task<Results<Ok<ChatReply>, ProblemHttpResult>> ChatAsync(
        ChatRequest request,
        IChatClient client,
        CancellationToken cancellationToken)
    {
        var clock = Stopwatch.StartNew();

        try
        {
            var response = await client.GetResponseAsync(request.Prompt, cancellationToken: cancellationToken);
            var used = response.AdditionalProperties?[FallbackChatClient.ClientProperty]?.ToString() ?? "unknown";
            return TypedResults.Ok(new ChatReply(response.Text, used, clock.ElapsedMilliseconds));
        }
        catch (LlmUnavailableException)
        {
            return Unavailable();
        }
    }

    private static async Task<Results<ServerSentEventsResult<string>, ProblemHttpResult>> StreamAsync(
        ChatRequest request,
        IChatClient client,
        CancellationToken cancellationToken)
    {
        var updates = client.GetStreamingResponseAsync(request.Prompt, cancellationToken: cancellationToken);
        var enumerator = updates.GetAsyncEnumerator(cancellationToken);

        try
        {
            // Opening the stream here lets a total outage become a clean 503 instead of a broken 200.
            if (!await enumerator.MoveNextAsync())
                return TypedResults.ServerSentEvents(Empty(), "token");
        }
        catch (LlmUnavailableException)
        {
            await enumerator.DisposeAsync();
            return Unavailable();
        }

        return TypedResults.ServerSentEvents(Tokens(enumerator), "token");
    }

    private static async IAsyncEnumerable<string> Tokens(IAsyncEnumerator<ChatResponseUpdate> enumerator)
    {
        await using (enumerator)
        {
            do
            {
                if (!string.IsNullOrEmpty(enumerator.Current.Text))
                    yield return enumerator.Current.Text;
            }
            while (await enumerator.MoveNextAsync());
        }
    }

    private static async IAsyncEnumerable<string> Empty()
    {
        await Task.CompletedTask;
        yield break;
    }

    private static Ok<ProviderStatus[]> Status(FallbackChatClient client) =>
        TypedResults.Ok(client.Clients.Select(c => new ProviderStatus(c.Name, c.Circuit.ToString())).ToArray());

    private static NoContent SetChaos(ChaosRequest request, ChaosState state)
    {
        state.Mode = request.Mode;
        return TypedResults.NoContent();
    }

    private static ProblemHttpResult Unavailable() =>
        TypedResults.Problem(
            title: "All LLM clients are unavailable",
            statusCode: StatusCodes.Status503ServiceUnavailable,
            extensions: new Dictionary<string, object?> { ["retryAfterSeconds"] = 20 });
}

fscamuzzi/llm-resilience-dotnet-polly-fallback · GitHub ↗

POST /chat, POST /chat/stream, stato dei circuiti e chaos. Codice completo nel repo: https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback

📄 Program.cs e configurazione

Il composition root resta di poche righe. La configurazione di esempio punta a localhost:11434, la porta pubblicata da Docker Compose.

Program.cs · appsettings.json
using System.Text.Json.Serialization;
using LlmResilience.Api.Endpoints;
using LlmResilience.Api.Resilience;

var builder = WebApplication.CreateBuilder(args);

builder.Services.ConfigureHttpJsonOptions(options =>
    options.SerializerOptions.Converters.Add(new JsonStringEnumConverter()));
builder.Services.AddProblemDetails();
builder.Services.AddResilientChat(builder.Configuration);

var app = builder.Build();

app.MapChatEndpoints();
app.Run();

public partial class Program;

// appsettings.json (estratto)
//   "Llm": {
//     "Endpoint": "http://localhost:11434",
//     "PrimaryModel": "llama3.2:3b",
//     "FallbackModel": "qwen2.5:0.5b",
//     "ChaosEnabled": true
//   },
//   "Resilience": {
//     "MaxRetryAttempts": 2,
//     "RetryBaseDelay": "00:00:00.500",
//     "AttemptTimeout": "00:00:30",
//     "BreakerFailureRatio": 0.5,
//     "BreakerMinimumThroughput": 4,
//     "BreakerSamplingDuration": "00:00:30",
//     "BreakerBreakDuration": "00:00:20"
//   }
// }

fscamuzzi/llm-resilience-dotnet-polly-fallback · GitHub ↗

Avvio dell'app e valori di default. Codice completo nel repo: https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback

▶️ Passo 10 · Provarlo

Avvio Ollama, aspetto che i modelli siano scaricati e lancio l'API. Poi rompo il primary e rifaccio la stessa richiesta: risponde il fallback e nei log vedo i due tentativi con il loro backoff. Dopo qualche fallimento il circuito del primary è Open: le chiamate successive non lo toccano più e il fallback risponde in pochi millisecondi.

Terminale · avvio
docker compose up -d
docker compose logs -f ollama-init     # attendi exit code 0
dotnet run --project src/LlmResilience.Api --urls http://localhost:5050

fscamuzzi/llm-resilience-dotnet-polly-fallback · GitHub ↗

Dipendenze Docker e avvio dell'API. Codice completo nel repo: https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback

🖥️ Cosa vedo nel terminale

Questo è l'output reale di una sessione: il warn del retry con il ritardo, il passaggio al client successivo, la risposta con client: fallback e lo stato dei circuiti. Il valore elapsedMs della prima risposta include l'attesa dei retry; le successive, a circuito aperto, sono quasi istantanee sul lato del primary.

Retry, fallback e circuito aperto
Terminale con la sequenza: PUT /chaos in modalità Fail, richiesta a /chat con due warning di retry e il passaggio al fallback, risposta con client fallback e stato dei circuiti primary Open e fallback Closed.

Dopo i fallimenti il primary è Open e risponde il fallback.

🧪 Test: provare i guasti senza un modello

Un IChatClient finto con uno script di errori mi permette di testare ogni policy senza Ollama e senza rete. Imposto ritardi di un millisecondo, così la suite gira in circa due secondi. Verifico: retry fino al successo, nessun retry sugli errori non transitori, timeout, apertura del circuito, cancellazione del chiamante, fallback e streaming.

ResilienceTests.cs
using LlmResilience.Api.Options;
using LlmResilience.Api.Resilience;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging.Abstractions;
using Polly.CircuitBreaker;
using Polly.Timeout;

namespace LlmResilience.Tests;

public class ResilienceTests
{
    private static readonly ResilienceOptions Fast = new()
    {
        MaxRetryAttempts = 2,
        RetryBaseDelay = TimeSpan.FromMilliseconds(1),
        AttemptTimeout = TimeSpan.FromMilliseconds(200),
        BreakerMinimumThroughput = 4,
        BreakerFailureRatio = 0.5,
        BreakerSamplingDuration = TimeSpan.FromSeconds(30),
        BreakerBreakDuration = TimeSpan.FromSeconds(30),
    };

    private static ResilientChatClient Wrap(string name, IChatClient inner) =>
        new(name, inner, Fast, NullLogger.Instance);

    private static List<ChatMessage> Prompt => [new(ChatRole.User, "ciao")];

    [Fact]
    public async Task Transient_failures_are_retried_until_success()
    {
        var inner = new ScriptedChatClient("ok", ScriptedChatClient.Outage(), ScriptedChatClient.Outage());
        var client = Wrap("primary", inner);

        var response = await client.GetResponseAsync(Prompt);

        Assert.Equal("ok", response.Text);
        Assert.Equal(3, inner.Calls);
    }

    [Fact]
    public async Task Non_transient_failures_are_not_retried()
    {
        var inner = new ScriptedChatClient("ok", new ArgumentException("bad request"));
        var client = Wrap("primary", inner);

        await Assert.ThrowsAsync<ArgumentException>(() => client.GetResponseAsync(Prompt));

        Assert.Equal(1, inner.Calls);
    }

    [Fact]
    public async Task Slow_attempts_hit_the_timeout()
    {
        var inner = new ScriptedChatClient("ok") { Delay = TimeSpan.FromSeconds(5) };
        var client = Wrap("primary", inner);

        await Assert.ThrowsAsync<TimeoutRejectedException>(() => client.GetResponseAsync(Prompt));

        Assert.Equal(3, inner.Calls);
    }

    [Fact]
    public async Task Circuit_opens_after_repeated_failures_and_stops_calling_the_provider()
    {
        var inner = new ScriptedChatClient("ok", Enumerable.Repeat<Exception?>(ScriptedChatClient.Outage(), 20).ToArray());
        var client = Wrap("primary", inner);

        await Assert.ThrowsAsync<HttpRequestException>(() => client.GetResponseAsync(Prompt));
        await Assert.ThrowsAsync<BrokenCircuitException>(() => client.GetResponseAsync(Prompt));
        var callsWhenOpen = inner.Calls;

        await Assert.ThrowsAsync<BrokenCircuitException>(() => client.GetResponseAsync(Prompt));

        Assert.Equal(CircuitState.Open, client.Circuit);
        Assert.Equal(callsWhenOpen, inner.Calls);
    }

    [Fact]
    public async Task Caller_cancellation_is_not_retried()
    {
        var inner = new ScriptedChatClient("ok") { Delay = TimeSpan.FromSeconds(5) };
        var client = new ResilientChatClient("primary", inner, Fast, NullLogger.Instance);
        using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(50));

        await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.GetResponseAsync(Prompt, null, cts.Token));

        Assert.Equal(1, inner.Calls);
    }

    [Fact]
    public async Task Fallback_answers_when_the_primary_is_down()
    {
        var primary = new ScriptedChatClient("from primary", Enumerable.Repeat<Exception?>(ScriptedChatClient.Outage(), 20).ToArray());
        var secondary = new ScriptedChatClient("from fallback");
        var client = new FallbackChatClient([Wrap("primary", primary), Wrap("fallback", secondary)], NullLogger<FallbackChatClient>.Instance);

        var response = await client.GetResponseAsync(Prompt);

        Assert.Equal("from fallback", response.Text);
        Assert.Equal("fallback", response.AdditionalProperties![FallbackChatClient.ClientProperty]);
    }

    [Fact]
    public async Task Fallback_is_skipped_when_the_primary_works()
    {
        var primary = new ScriptedChatClient("from primary");
        var secondary = new ScriptedChatClient("from fallback");
        var client = new FallbackChatClient([Wrap("primary", primary), Wrap("fallback", secondary)], NullLogger<FallbackChatClient>.Instance);

        var response = await client.GetResponseAsync(Prompt);

        Assert.Equal("primary", response.AdditionalProperties![FallbackChatClient.ClientProperty]);
        Assert.Equal(0, secondary.Calls);
    }

    [Fact]
    public async Task Fallback_throws_when_every_client_fails()
    {
        var down = Enumerable.Repeat<Exception?>(ScriptedChatClient.Outage(), 20).ToArray();
        var client = new FallbackChatClient(
            [Wrap("primary", new ScriptedChatClient("a", down)), Wrap("fallback", new ScriptedChatClient("b", down))],
            NullLogger<FallbackChatClient>.Instance);

        var failure = await Assert.ThrowsAsync<LlmUnavailableException>(() => client.GetResponseAsync(Prompt));

        Assert.Equal(2, failure.Failures.Count);
    }

    [Fact]
    public async Task Streaming_is_retried_before_the_first_update()
    {
        var inner = new ScriptedChatClient("uno due tre", ScriptedChatClient.Outage());
        var client = Wrap("primary", inner);

        var text = string.Concat(await Collect(client.GetStreamingResponseAsync(Prompt)));

        Assert.Equal("unoduetre", text);
        Assert.Equal(2, inner.Calls);
    }

    [Fact]
    public async Task Streaming_falls_back_when_the_primary_cannot_open()
    {
        var primary = new ScriptedChatClient("a b", Enumerable.Repeat<Exception?>(ScriptedChatClient.Outage(), 20).ToArray());
        var secondary = new ScriptedChatClient("x y");
        var client = new FallbackChatClient([Wrap("primary", primary), Wrap("fallback", secondary)], NullLogger<FallbackChatClient>.Instance);

        var text = string.Concat(await Collect(client.GetStreamingResponseAsync(Prompt)));

        Assert.Equal("xy", text);
    }

    private static async Task<List<string>> Collect(IAsyncEnumerable<ChatResponseUpdate> updates)
    {
        var parts = new List<string>();
        await foreach (var update in updates)
            parts.Add(update.Text);
        return parts;
    }
}

fscamuzzi/llm-resilience-dotnet-polly-fallback · GitHub ↗

Retry, circuit breaker e fallback verificati con un client scriptato. Codice completo nel repo: https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback

⚠️ Errori da evitare

Sono gli errori che vedo più spesso quando si aggiungono retry e fallback a un'integrazione LLM.

  • Ritentare tutto: un 400 o un prompt non valido non migliora al secondo tentativo.
  • Retry senza jitter: tanti client che ritentano insieme formano un'onda che schiaccia il provider.
  • Un solo timeout globale: un timeout per tentativo evita che tre retry da 100 secondi diventino cinque minuti di attesa.
  • Un breaker condiviso: ogni provider ha il suo, altrimenti un guasto del primary spegne anche il fallback.
  • Fallback silenzioso: un modello più piccolo risponde diversamente; registro sempre quale client ha risposto.
  • Ritentare lo streaming a metà: dopo il primo token si duplicherebbe l'inizio della risposta.
  • Chaos in produzione: Llm:ChaosEnabled va a false fuori da sviluppo.

📦 GitHub repo

Il progetto completo — API, decorator, client di test scriptato, docker-compose.yml con Ollama e download dei modelli, file .http e suite xUnit — è pubblico su GitHub. Il README riporta gli stessi comandi Docker Compose, dotnet test e dotnet run di questo articolo.

Codice completo su GitHub: https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback

Terminale · clona ed esegui
git clone https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback.git
cd llm-resilience-dotnet-polly-fallback
docker compose up -d
dotnet test
dotnet run --project src/LlmResilience.Api --urls http://localhost:5050

fscamuzzi/llm-resilience-dotnet-polly-fallback · GitHub ↗

Repository companion pubblico con codice completo, test e Docker Compose. Codice completo nel repo: https://github.com/fscamuzzi/llm-resilience-dotnet-polly-fallback

🏁 Conclusioni

Retry, timeout, breaker e fallback non sono quattro varianti della stessa idea: rispondono a quattro guasti diversi e vanno composti nell'ordine giusto. Con IChatClient e Polly restano confinati in due decorator e l'app non se ne accorge.

Il passo successivo naturale è misurarli: contare i retry, i circuiti aperti e le risposte del fallback con le metriche di OpenTelemetry, come nell'articolo sull'osservabilità degli LLM.

Domande frequenti su resilienza LLM .NET

Perché non ritentare tutti gli errori di un LLM?

Solo gli errori transitori (rete, 5xx, 429, 408, timeout) possono passare da soli. Un prompt non valido o una chiave sbagliata fallirebbe di nuovo e costerebbe tempo e, sul cloud, token.

Qual è l'ordine giusto di retry, circuit breaker e timeout in Polly?

Retry all'esterno, circuit breaker in mezzo, timeout all'interno. Il timeout vale per tentativo e il breaker conta ogni singolo fallimento.

Microsoft.Extensions.AI ha un fallback tra modelli?

Non ne conosco uno incluso: IChatClient è un'interfaccia comoda da decorare, quindi scrivo io un FallbackChatClient. Sono poche decine di righe e restano indipendenti dal provider.

Posso ritentare uno stream a metà?

No. Dopo il primo token il client ha già ricevuto parte della risposta e un retry la duplicherebbe. Proteggo solo l'apertura dello stream, fino al primo aggiornamento.

Serve un circuit breaker per ogni modello?

Sì. Con un breaker condiviso, i guasti del primary aprirebbero il circuito anche per il fallback, che invece funziona. Ogni ResilientChatClient ha la sua pipeline.

Posso usare OpenAI o Azure invece di Ollama?

Sì. I decorator dipendono solo da IChatClient: cambio le due registrazioni in AddResilientChat e la pipeline resta uguale. Cambiano solo le eccezioni che il provider lancia, quindi riverifico IsTransient.

Parliamone

Se questo tema ti riguarda, scrivimi: confrontarsi su codice e AI è sempre tempo speso bene.