asp.net performance optimization
TRANSCRIPT
Da consulenze/sviluppo di soluzioni reali Spesso si sviluppa non pensando alle
prestazioni "Tempo è denaro"
Spesso è il cliente/utente che fa notare la lentezza dell'applicazione
Dalla sessione "Architettura di Stackoverflow" di Marco Cecconi Alcune note:
Metodo YAGNI No Dependency Injection, no Providers, no… Custom ORM (no Entity Framework, no NHibernate) Soluzione composta da (soli) 8 progetti
Perché questa sessione?
KISS http://it.wikipedia.org/wiki/KISS_(informatica)
KISS è un acronimo usato nell'informatica, che sta per Keep It Simple, Stupid, ossia "rimani sul semplice, stupido
YAGNI http://
en.wikipedia.org/wiki/You_aren't_gonna_need_it
"You aren't gonna need it" (acronym: YAGNI) is a principle of extreme programming (XP) that states a programmer should not add functionality until deemed necessary
Da tenere sempre a mente
Navigazione da browser Test di carico Performance counter Profiler / Tracert / Logging SQL Profiler
Come capire dove intervenire?
Esistono Performance Counter specifici per ASP.NET (e suoi componenti)
Permettono di monitorare lo stato dell'applicazione, e l'uso che viene fatto delle risorse (cache, session, …) Possono venir messi a confronto con i
performance counter di sistema per capire la causa di rallentamenti/blocchi
NOTE: attenzione che ogni counter ha una propria scala/range di valori
Performance Counter
Requests Failed The total number of failed requests. Any status codes greater
than or equal to 400 will increment this counter.
Requests/Sec The number of requests executed per second.
Requests Queued The number of requests waiting for service from the queue.
Request Wait Time The number of milliseconds that the most recent request
waited in the queue for processing.
Pipeline Instance Count The number of active request pipeline instances for the
specified ASP.NET application. Since only one execution thread can run within a pipeline instance, this number gives the maximum number of concurrent requests that are being processed for a given application.
Performance Counter ASP.NET
Errors During Execution The total number of errors that occur
during the execution of an HTTP request, excluding parser and compilation errors.
Errors Unhandled During Execution The total number of unhandled errors that
occur during the execution of HTTP requests.
Performance Counter ASP.NET
Sessions Active The number of sessions currently active. This
counter is supported only with in-memory session state.
Sessions Total The total number of sessions. This counter is
supported only with in-memory session state.
Session SQL Server Connections Total The total number of session-state connections
made to the computer on which out-of-process session-state data is stored.
State Server Sessions Active The number of currently active user sessions. This
counter is available only on the computer where the state server service (aspnet_state) is running.
Performance Counter ASP.NET
Cache Total Entries The total number of entries in the cache. This
counter includes both use of the cache by the ASP.NET page framework and use of the application cache through cache APIs.
Cache Total Turnover Rate The number of additions and removals to the
cache per second, which is useful in helping to determine how effectively the cache is being used. If the turnover rate is high, the cache is not being used efficiently.
Per monitorare solo la Cache API: Cache API Entries Cache API Turnover Rate
Performance Counter ASP.NET
Potete creare dei vostri Performance Counter Utili per poter monitorare valori/dati che vi
sono utili a capire l'utilizzo della vostra applicazione
Link: https://www.simple-talk.com/dotnet/performance/building-performance-metrics-into-asp.net-mvc-applications/
Potete salvare i dati recuperati dai counter: Utile per analizzarli in un secono momento http://technet.microsoft.com/en-us/library/cc722148.aspx
Performance counter
Permettono di portare alla luce eventuali errori che compaiono "solamente" quando l'applicazione è sotto stress Problemi di memory leak Problemi di concorrenza/thread safety Problemi dovuti ad un server sottodimensionato
CPU al 100% Memoria RAM occupata
Problemi di connettività/banda
I Web Load & Performance Testing sono presenti sono nella versione Ultimate di Visual Studio
Test di carico
Non eseguire i test di carico dalla stessa macchina che ospita l'applicazione
Utilizzare più Test Agents (distribuiti) per eseguire i test
Possibilità di sfruttare Microsoft Azure per automatizzare il tutto Oppure sfruttare le Virtual
Machine/WorkerRole per scalare i Test Agents http://msdn.microsoft.com/en-us/library/
ms182594.aspx
Test di carico
Permette di monitorare l'uso che viene fatto del database Di conseguenza anche il codice di accesso
ai dati
Utile per scoprire chiamate non necessarie
Utile per scoprire chiamate duplicate
SQL Profiler
Libreria che permette di profilare la chiamate verso il database, e gli eventi di ASP.NET MVC, WCF Entity Framework, Raven DB, Mongo DB, DbConnection, DbCommand, … …
Sviluppato dal team di StackOverflow e rilasciato come OpenSource http://miniprofiler.com/ Nuget: Install-Package MiniProfiler
Possibilità di profilare codice custom
MiniProfiler
Non esiste solo HttpContext.Cache HttpContext.Items
Per eseguire cache di dati per la richiesta corrente
HttpContext.Application Per dati che non cambiano durante il ciclo di vita
dell'applicazione Non thread-safe
System.Runtime.Caching Non ha dipendenze da System.Web http://msdn.microsoft.com/en-us/library/system.ru
ntime.caching(v=vs.110).aspx
Deriva dall'Enterprise Library Caching Application Block
Presente da .NET Framework 4.0
Cache
La cache di ASP.NET diventa un limite
Ci si deve appoggiare ad una cache/servizio esterno alle applicazioni
Alcune soluzioni: AppFabric Redis Memcached
In alcune realtà ci sono server dedicati a gestire solo la cache
Ma se più app accedono agli stessi dati?
Estende Windows Server in modo da poter genstire e monitorare una cache applicativa centralizzata
Servizio scalabile Possibilità di gestire anche le
Sessioni ASP.NET Possibilità di taggare gli oggetti in
cache
NOTE: non installabile in Windows Server Web Edition
Windows Server AppFabric
http://redis.io/ In-memory Key-Value store Scalabile (è possibile attivare la persistenza)
Microsoft ha eseguito il porting per Windows https://github.com/MSOpenTech/redis
Librerie clients disponibili per molti linguaggi
Altamente performante
Redis
http://memcached.org/ Key-Value store In-memory Scalabile
Memcached Users LiveJournal, Wikipedia, Flickr Bebo, Twitter, Typepad Yellowbot, Youtube, WordPress.com, ...
Clients disponibili su NuGet: Esempio: Install-Package
EnyimMemcached
Memcached
Attenzione che gli oggetti che inserite in cache devono essere Serializzabili
Non inserite in cache oggetti compilati dinamicamente
Attenzione che gli oggetti non siano dei proxy (es con Lazy Loading)
NOTE:
https://efcache.codeplex.com/ Implementazione del
CachingProvider di Entity Framework
Permette di mantenere in cache il risultato delle query
Viene gestita anche l'invalidazione dei dati in cache
Second Level Cache for Entity Framework
Permette di ritornare il rendering di una pagina/view/userControl/partialView senza doverla ricompilare ed eseguire
Possibilità di specificare quali chiavi/metodo utilizzare come chiavi per il riuso
Riduce notevolmente il carico di lavoro del server
Non utilizzarla in pagine con dati che variano di frequente
Output-cache
Utilizzare CDN o un secondo dominio per tutti i file statici
I browser hanno un limite per il numero di connessioni/richieste contemporanee verso lo stesso dominio Includere immagini/file in un secondo dominio
permette di aumentare il numero di download contemporanei del browser
Utilizzare librerie su CDN pubbliche aumenta la possibilità che queste siano già presenti nella cache del browser
Enabling CDN for Azure Websites http
://azure.microsoft.com/blog/2014/09/18/enabling-cdn-for-azure-websites/
CDN – Content Delivery Network
Tramite il web.config è possibile specificare dei parametri per forzare la cache (lato client) di file statici Immagini CSS JavaScript …
Cache static content
<system.webServer><staticContent>
<clientCache cacheControlMaxAge="7.00:00:00" cacheControlMode="UseMaxAge" /></staticContent>
</system.webServer>
ASP.NET App Suspend
Possibilità di sospendere un'applicazione (invece che terminarla) dopo un tempo di inattività
Da IIS8, Windows Server 2012 R2, Framework 4.5.1
Riduzione dei tempi di avvio Parametro dell'ApplicationPool
Performance Counters for ASP.NET http://msdn.microsoft.com/en-us/library/vstudio/fxk122b4(v=vs.100).aspx
Building Performance Metrics into ASP.NET MVC Applications https://www.simple-talk.com/dotnet/performance/building-performance-metrics-into-asp.net-mvc-a
pplications/
Introduzione a Windows Server AppFabric http://msdn.microsoft.com/en-us/library/hh351318.aspx
Redis on Windows https://github.com/MSOpenTech/redis
StackExchange.Redis https://github.com/StackExchange/StackExchange.Redis
Conditional GET http://optimizeasp.net/conditional-get
Enabling CDN for Azure Websites http://azure.microsoft.com/blog/2014/09/18/enabling-cdn-for-azure-websites/
Plugin per Fiddler – Stress Stimulus http://www.stresstimulus.com/
Architettura di Stackoverflow Video: https://www.youtube.com/watch?v=t6kM2EM6so4
Slide: http://www.slideshare.net/howtoweb/marco-cecconi-stack-overflow-architecture
Links
feedback
10
• Materiale: – http://
blog.dottor.net/files/xedotnet/20140919_Dottor.AspNetPerformance_code.zip
– http://blog.dottor.net/files/xedotnet/20140919_Dottor.AspNetPerformance_slide.zip
Email: [email protected]: http://www.dottor.net Blog: http://blog.dottor.netTwitter: http://twitter.com/dottor
Contatti