Share
Embed
Robust and resilient apps with Polly and Refit
In this session we will see how we can make apps robust, resilient and reliable using Polly framework paired with Refit that simplify a lot the management of REST api calls. With a few lines of code we are able to write complex retry policies, both synchronous and asynchronous, to face transient faults but also refresh auth tokens, manage timeouts... and other useful things. Start making your app stronger today!
Andrea Ceroni
December 05, 2019
Transcript
25 slides
-
Robust and resilient apps with Polly and Refit Andrea Ceroni
Senior R&D Developer @Elfo www.wpc2019.it 2 Thanks to App-vNext https://github.com/App-vNext/Polly-Samples#slide-decks -
Refit Transient Errors Resilience strategies (Reactive, Proactive)
Integrazione con HttpClientFactory Polly policies (Retry, Circuit Breaker, Fallback, Timeout, Bulkhed, Cache ) Wrap e PolicyRegistry Simmy Circuit Breaker distribuito www.wpc2019.it 3 Agenda -
www.wpc2019.it 5 Refit The automatic type-safe REST library for .NET
Core, Xamarin and .NET public interface IAzureDevOpsApi { [Get(“/v1/projects/{id}”)] Task<Project> GetProject(int id) [Get(“/v1/projects”)] Task<List<Projec>> GetProjects() } RestService genera un’ implementazione di IAzureDevOpsApi che usa HttpClient var adoClient = RestService.For<IAzureDevOpsApi>(”https://azuredevops...”) var project = await adoClient.GetProject(66); Code generation a compile time, nulla di magico -
www.wpc2019.it 6 Errori transitori e non solo... Problemi di
rete Interrezioni di servizio Attacchi DoS IO locks Problemi hardware Sicuramente i problemi ci saranno e non possiamo evitarli però possiamo limitare i danni e magari tentare di prevenirli Fallire in maniera controllata è meglio di fallire senza controllo J -
www.wpc2019.it 7 Reattive Proattive Timeout Bulkhead Isolation Cache Retry Circuit
Breaker Fallack Wait and Retry -
www.wpc2019.it 8 Polly Esprimere policy per la gestione di eccezioni
transitorie in modo semplice e conciso tramite fluent interface: (Retry, Circuit Breaker, Fallback, Timeout, Bulkhead Isolation, Cache) .NET 4.5+ / .NET Standard 1.1 / .NET Std 2.0+ / .NET Core 2.1+ 1) Definisco la policy var retryPolicy = Policy .Handle<Exception>() .RetryAsync(2); 2 ) Eseguo il metodo all’interno della policy var result = await retryPolicy .ExecuteAsync(() => DoSomething()); -
www.wpc2019.it 9 HttpClientFactory .NET Core >= 2.1 Integrata con HttpClientFactory
è possibile configurare diversi client e diverse strategie durante lo Startup services.AddHttpClient(“AzureDevOps”, client => { client.BaseAddress = new Uri(“...”) }) .AddTransientHttpErrorPolicy(p => p.WaitAndRetryAsync(3)); Tutte le chiamate che usano questo client saranno protette da retry e il client può essere "injettato" ovunque tramite DI services.AddRefitClient<IAzureDevOpsAPi>() -
www.wpc2019.it 12 Retry e WaitAndRetry Retry immediato in caso di
fallimento. Si specifica il numero di tentativi. Wait and Retry con attesa prima di ogni retry. E’ possibile configurare il timeout tra i retry exponential back-off, jitter... Retry Forever continua a provare fino a quando (eventualmente) ha successo. Retry addresses ... ‘It’s probably a blip. Give it another go - it might succeed.’ -
www.wpc2019.it 13 Fallback Fallback permette di specificare un valore sostitutivo
(default) o un’ azione da eseguire (escalate...) quando un’ operazione continua a fallire Fallback addresses … ‘Failures will occur … prepare how you will respond when that happens’ -
www.wpc2019.it 14 Circuit Breaker Circuit Breaker apre il circuito per
un periodo di tempo configurabile se accadono troppi errori. Blocca le chiamate mentre il circuito è aperto. Protegge i sistemi a valle che possono riprendersi. Fail fast pattern così da evitare effetti a catena. Circuit Breaker addresses … ‘Whoa, that system is struggling / down. Give it a break. And don’t hang around waiting for an answer that’s unlikely right now!’ -
www.wpc2019.it 15 Timeout Timeout permette di evitare di aspettare quando
si pensa che una risposta non arriverà. Optimistic mode Timeout cooperativo tramite CancellationToken. Pessimistic mode Forza il timeout (ritornando al chiamante) anche quando il metodo chiamato non supporta timeout/cancellazione. Timeout ensures … callers can ‘walk away’ from a faulting downstream system, release blocked threads/connections etc. -
www.wpc2019.it 16 Bulkhead Isolation Bulkhead evita che un’ operazione consumi
tutte le risorse. Se un flusso di chiamate inizia a fallire tutti i thread del chiamante potrebbero finire in attesa su quel servizio...fino a quando anche il chiamante collassa. Bulkhead lo impedisce limitando le risorse che un determinato flusso di chiamate può consumare. Può essere un valido trigger per lo scaling orizzontale. Bulkhead … ‘One fault shouldn’t sink the whole ship!’ -
www.wpc2019.it 17 Cache Cache evita di rifare le stesse operazioni,
il risultato delle chiamate viene salvato in memoria e la volta successiva ritorna direttamente quello senza chiamate ulteriori. Riduce la latenza. Permette di agganciarci il cache provider che preferiamo. (MemoryCache, Redis, etc...) Ha una scadenza. Cache addresses … ‘You’ve asked that one before!’ -
www.wpc2019.it 18 Wrap PolicyWrap permette di combinare a piacimento le
policy precedenti così da supportare diversi scenari e creare una strategia di resilienza ad-hoc PolicyWrap superResilience = Policy.Wrap(fallback, retry, breaker, timeout); superResilience.Execute(() => DoSomething()); -
www.wpc2019.it 19 Caratteristiche Definiscono come gestire gli errori transitori
Sintassi fluente e concisa Thread-safe (ma attenzione che i delegati non lo sono!) Utilizzabili ovunque (non solo per chiamate http) Sincrone o asincrone E’ possibile concatenare più policy e definire quindi una strategia Si applicano a qualsiasi Action o Func (chimate a servizi, db, richieste web, processi schedulati...) -
www.wpc2019.it 20 Chaos Engineering con Polly per testare la resilienza.
var faultPolicy = Policy.InjectFault<SocketException>( fualtRate: 0.1, enabled: () => EnableFault()); var latencyPolicy = Policy.InjectLatency( latency: TimeSpan.FromSeconds(2), faultRate: 0.2, enabled: () => EnableLatency()); var failurePolicy = Policy.InjectResult<HttpResponseMessage>( new HttpResponseMessage(HttpStatusCode.Unauthorized)); Permettono di creare chaos all’interno dell’app e sperimentare nei diversi environment. Zero overhead quando disabilitate. Molto utili anche negli unit test. -
www.wpc2019.it 21 Distributed Circuit Breaker Circuit breaker distribuito e stateful
(persistenza su Azure Storage) implementato con Azure Durable Entity. Può essere chiamato direttamente da un' Azure Function (semplice o durable orchestrator) attraverso IDurableCircuitBreakerClient. Oppure consumabile ovunque attraverso una chiamata http, Durable Entity è API first by-design. Stateful e consistente tra diversi chiamanti e diverse function app. -
www.wpc2019.it 22 Links https://github.com/andrekiba/WPC19 https://github.com/reactiveui/refit https://github.com/App-vNext/Polly https://docs.microsoft.com/it- it/dotnet/architecture/microservices/implement- resilient-applications/use-httpclientfactory-to- implement-resilient-http-requests
https://github.com/App-vNext/Polly-Samples https://github.com/Polly-Contrib/Simmy https://github.com/Polly- Contrib/Polly.Contrib.AzureFunctions.CircuitBreaker -
Q & A www.wpc2019.it 24 var escape = Policy .RetryAsync(1,
:onRetrySync (...) => { IRunAwayFromTheRoom(); }); var q&a = Policy .Handle<DontKnowException>() .FallbackAsync(42 J) .WrapAsync(escape); var answer = await q&a .ExecuteAsync(() => Question()); -
Contatti OverNet Education [email protected] www.OverNetEducation.it Rozzano (MI)
+39 02 365738 Bologna +39 051 269911 www.wpc-overneteducation.it #wpc19it www.wpc2019.it 25