PerfByDesign Aspnet
PerfByDesign Aspnet
Performance
Mark Friedman
Architect
Developer Division
Microsoft Corporation
Web Application Performance
Agenda:
ASP.NET architecture for building dynamic
web applications
Building scalable web applications
Persisting Session state
Caching application data
n-Tiered application scaling
Building responsive web applications
Page Load Time and Round trips
AJAX
Tips for Silverlight and WPF-based applications
3
ASP.NET Application Performance
6
ASP.NET Application Performance
Client-side scripting
Rich Internet Applications (RIA)
AJAX
Browser Document Object Model (DOM)
Javascript
Asynchronous server Postbacks (to web services)
7
ASP.NET Application Performance
Measurement considerations
On the client
Performance counters
Network Monitor traces
ETW traces (IE, etc.)
Direct measurements inside Javascript code
On the server
IIS logs (especially Time-Taken fields)
Performance counters
web app response time data is not available
ETW traces (IIS, ASP.NET, CLR, etc.)
volume considerations
Direct measurement inside .NET code
e.g., Stopwatch
8
ASP.NET Application Performance
Measurement considerations
End-to-End
Multiple tiers
9
Web Application Performance
Client-side
script Network
Client-side Latency
script Network
Network Latency
Latency
Server-side Server-side Server-side
.aspx .aspx .aspx
e.g., VS TeamTest 10
Web Application Performance
12
Web Application Performance
13
demo
Visual Roundtrip
Analyzer
Web Application Performance
15
Web Application Performance
Elements of Page Load Time
Html
CSS
Javascript (serializes)
XAML
Images
Audio
Video
Banner ads (often from 3rd parties)
etc.
Page Load parallelism
IE7 limited to two parallel sessions
IE8 and Chrome support six parallel sessions
16
Web Application Performance
See “
Caching Architecture Guide for .NET Framework Applications”
19
ASP.NET Application Architecture
w3wp.exe
w3wp.exe
mscoree.dll
MyApp.dll mscorsvr.dll
20
ASP.NET programming model
Form:
<asp:DropDownList id="FileDropDownList" style="Z-INDEX: 111;
LEFT: 192px; POSITION: absolute; TOP: 240px“ runat="server"
Width="552px" Height="40px“
AutoPostBack="True"></asp:DropDownList>
Code behind:
Private Sub FileDropDownList_SelectedIndexChanged _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles FileDropDownList.SelectedIndexChanged
Session("FileSelected") = FileDropDownList.SelectedValue
End Sub
21
IIS Architecture
Application Pool Application Pool
IIS
Administration
net.tcp net.tcp
Metabase
http http
Cache
Windows
Authentication WAS Default.aspx Default.aspx
FTP
<code-behind>.dll <code-behind>.dll
SSL SMTP
W3SVC Mscoree.dll Mscoree.dll
NNTP
W3wp W3wp
LSSAS Inetinfo SVCHOST W3wp W3wp
User
Kernel
HTTP
27
Monitoring IIS worker processes
28
IIS 7.0 Integrated Pipeline
29
IIS 7.0 Integrated Mode
30
IIS 7.0 Integrated Mode
33
Configure IIS Tracing using Logman
34
Configure IIS Tracing using Logman
35
ETW Trace reporting tools
logparser
xperf
36
ETW Trace reporting tools
37
ETW Trace reporting tools
38
Configure IIS Tracing using Logman
39
ASP.NET programming model
40
ASP.NET programming model
Event Usage
PreInit Create dynamic controls, set the Theme; master page, etc.
Init Read or initialize control properties
InitComplete Raised by the Page object.
PreLoad Perform any processing on your page or control before the Load event.
Load The Page calls the OnLoad event method on the Page, then recursively for each
child control and its children
Control events Button Clicks and other Control events are processed after Page_Load
LoadComplete Fires after all controls on the page are loaded.
PreRender Data binding for controls occurs now.
SaveStateComplete Fires when the ViewState for all controls is complete and saved.
Render Method that writes out the html markup associated with the control.
Unload Do final cleanup, such as closing files or database connections
42
ASP.NET scalability strategies
Session State management
ASP.NET Cache
n-Tiered applications
e.g.,
Presentation Layer
Business Logic Layer
Data Layer
43
ASP.NET State Management
What is State?
Any information about the user,
his/her history and association with
the application that informs the
application’s processing.
e.g.,
how to associate a (potential)
customer with his/her shopping cart?
44
ASP.NET State Management
45
ASP.NET State Management
State by Scope:
Application state (HttpApplicationState)
Page
Static variables
potentially use Page.Cache for dynamic data
Session
Client-side options
Query strings
Cookies
Hidden fields
View state
Control state
Server-side options
Session state 46
ASP.NET Application Performance
Persisting state
on the client
on the server
State Management
ViewState Stored in _VIEWSTATE hidden field
HiddenField control
Cookies Add cookie data to the Cookies collection in the HttpResponse object
Query strings
Application State HttpApplicationState
Session State
Profiles SqlProfileProvider
47
ASP.NET Application Performance
ViewState
Passed to the client in _ViewState hidden field in the
Response message
Returned to the Server on a postback Request
Inspect using
%@ Page Trace="true“
View html Source on the client
3rd party tools like Fiddler
Be careful of
Data bound controls (GridView, etc.)
50
Large TreeViews, DropDownLists, etc.
ASP.NET Application Performance
51
ASP.NET Application State
52
ASP.NET Session state
HttpContext.Session
Data associated with a logical sequence of Requests
that need to be persisted across interactions
Unique session IDs are passed along automatically
with each Request as either cookies or embedded in
the URL
Session data is stored in a Dictionary collection,
allowing individual session state variables to be
accessed directly by Key name
Three external storage options
InProc
StateServer
SQL Server
Timeout management 53
ASP.NET Session
HttpContext.Session
InProc option provides fastest service, but does
not permit access to Session data from a
different process in a Web garden application
or a different Web server in a cluster
Using alternatives to InProc session storage has
significant performance implications
StateServer
SQL Server
Custom provider
55
Session State configuration
options
56
Session State options
For example,
<configuration>
<system.web>
<sessionState mode="SQLServer"
sqlConnectionString=" Integrated
Security=SSPI;datasource=dataserver;"
cookieless="false"
timeout="20"/>
</sessionState>
</system.web> 57
</configuration>
Caching strategies
Optimize:
Max(Cache Hit %)
Min(Space x Time)
58
ASP.NET Cache
Optimize to:
maximize Cache Hit %
minimize Cache
memory size
Cache Size
Analyze web logs for
patterns of re-use
Usually, there are
diminishing returns
from increasing cache
size to be large enough 0 25 50 75 100
to hold infrequently
referenced objects Cache Hit %
59
Caching strategies
Multiple facilities:
e.g.,
IIS kernel mode Cache
ASP.NET Application cache
ASP.NET Page cache
etc.
Application cache
HttpContext.Cache
Page.Cache
Page output caching
Full page
@ OutputCache Directive
Use VaryByParam with Query Strings to cache multiple versions of a Page
Partial page
Control Caching
<PartialCaching> Attribute
Post-cache substitution: dynamically updating portions of a cached page
Substitution.MethodName
HttpResponse.WriteSubstitution Method
What to cache:
Frequently used data that is relatively static and expensive to
re-create
Additional considerations based on object size
64
ASP.NET Application & Page Cache
65
ASP.NET Application & Page Cache
Cache Methods
Add (key, value, dependencies, expiration, sliding
expiration, priority, onRemoveCallback);
e.g., Cache.Add("Key1", "Value 1", null,
DateTime.Now.AddSeconds(60),
Cache.NoSlidingExpiration, CacheItemPriority.High,
onRemove);
Dependencies (permits bulk removal)
Notification upon removal
68
ASP.NET Application & Page Cache
70
ASP.NET Application & Page Cache
Response.Cache.SetCacheability(HttpCacheability.Pu
blic);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(
300));
Response.Cache.SetMaxAge(TimeSpan.FromSeconds(300)
);
Response.Cache.SetValidUntilExpires(true);
Response.Cache.SetLastModified(DateTime.Now);
Response.Cache.SetOmitVaryStar(true);
73
ASP.NET Page Output Cache
Server
ServerAndNoCache
PublicAndPrivate
74
ASP.NET Page Output Cache
75
ASP.NET Partial Page Output Cache
76
ASP.NET & AJAX
Web pages built with ASP.NET Web server
controls perform postbacks initiated by clicking
a button, etc.
In Response, the server renders a new page.
Frequently this re-renders controls and text that did
not change between postbacks.
AJAX refers to set of patterns and practices that
perform partial rendering of the page at the
client using Javascript and asynchronous HTTP
requests
Microsoft pioneered the use of AJAX prior to
ASP.NET
AJAX support for ASP.NET was not provided 77
until.NET Framework 3.0
ASP.NET & AJAX
Asynchronous XMLHttpRequest
Note: implementation of XMLHttpRequest is
browser-dependent
xmlhttp.open('GET', url, true);
xmlhttp.onreadystatechange = AsyncUpdateEvent;
xmlhttp.send(null);
79
ASP.NET and AJAX
UpdatePanel Control
Define regions of the page that can be updated independently using an
XMLHttpRequest
converts PostBacks into Asynchronous XML and HTTP Requests
Somewhat larger Request messages vs. significantly smaller server Response
messages
Flicker-free update
Re-sends all Viewstate data, however, for controls within the UpdatePanel
Triggers Property
ChildrenAsTriggers Property for controls inside the UpdatePanel
Client Server
HTTP Get Request
Response message
Sys.Application.Init
All scripts loaded
ScriptManager control
UpdatePanel
Sys.Application.Load
81
AJAX Page Processing Events
Client Server
PageRequestManager
initializeRequest
beginRequest
Asynchronous postback
request to the server
Response message
pageLoading event
pageLoaded event
Application load event
endRequest event
82
ASP.NET + AJAX
84
ASP.NET + AJAX + WCF
WCF code is protocol-independent
WCF endpoints:
Addresses
Bindings (e.g., WebHttpBinding)
Contracts
configure declaratively
85
WCF Performance Caution: your
mileage will vary.
Service Binding alternatives:
Binding Response Time (msecs) Throughput
Throughput
8000
Source: Resnik, Crane, & Bowen,
6000
Essential Windows
4000
Communication Foundation,
Addison Wesley, 2008. Chapter 4. 2000
See also, “ i ng i ng i ng i ng
nd nd nd nd
A Performance Comparison of Windows Co p Bi p Bi pB
i
e Bi
tt tt Tc ip
mmunication Foundation (WCF) with Existing sH icH et P
w s n ed
Distributed Communication Technologies ba m
” e tNa 86
n
WCF Scalability
Instancing
per-Call servicing is the default mode
per-Session servicing (the default)
[ServiceContract(Session = true)]
interface IMyContract {...}
[ServiceBehavior(InstanceContextMode =
InstanceContextMode.PerSession)]
class MyService : IMyContract {...}
<netTcpBinding>
<binding name="TCPSession">
<reliableSession enabled="true"
inactivityTimeout="00:25:00"/>
</binding>
</netTcpBinding>
WCF Sessions
Explicitly initiated and terminated by the calling
application.
Messages are processed in the order in which
they are received.
Sessions explicitly group messages into a
conversation.
Note: WCF does not create a specific session-
oriented data store
Singleton service
one instance of the service is configured
the instance lasts until the Host shuts down
the instance can have multiple concurrent threads…
[ServiceBehavior(
InstanceContextMode=InstanceContextMode.Single,
ConcurrencyMode = ConcurrencyMode.Multiple )]
class MySingleton : IMyContract, IDisposable
WCF Scalability
Threading
ConcurrencyMode.Multiple
requires locking and synchronization of shared state
data
ConcurrencyMode.Reentrant
can be used with per-Session callers to limit the
number of concurrent instances
<system.serviceModel>
But
<diagnostics
performanceCounters=“ServiceOnly"></diagnostics>
93
WCF Diagnostics
94
WCF Diagnostics
95
WCF Diagnostics
96
ASP.NET + AJAX + WCF
WCF makes it easy to develop web services
Uri baseAddress = new Uri("http://localhost:8000/HelloService");
string address = "http://localhost:8000/HelloService/MyService";
using (ServiceHost serviceHost = new ServiceHost(typeof(HelloService),
baseAddress))
{
serviceHost.AddServiceEndpoint(typeof(IHello), new WebHttpBinding(),
address);
serviceHost.Open();
Console.WriteLine("Press <enter> to terminate service");
Console.ReadLine();
serviceHost.Close();
}
99
ASP.NET Application Performance
HTTP performance is constrained by the TCP Protocol
TCP ensures in order delivery of all packets
All packets must be Acknowledged
Note: full duplex protocol
TCP Session handshaking
SYN, SYN-ACK, ACK sequence
Negotiates the TCP Window Size
Calculates 1st Round Trip Time used by Fast Retransmit logic
TCP Window
Upper limit on the amount of data that can be sent to a
Receiver without receiving an Acknowledgement
Congestion control (pacing) mechanism
Slow Start
Full Window used as a congestion signal
Round Trip Time, or RTT, determines Timeout interval for
retransmitting unacknowledged, i.e., dropped packets
100
demo
Visual Roundtrip
Analyzer
102
Web Application Performance
103
Web Application Performance
104
Web Application Performance
105
Web Application Performance
107
VRTA (Visual Round Trip Analyzer) File
details
108
ASP.NET Application Performance
110