SlideShare a Scribd company logo
10 Performance and Scalability secrets of ASP.NET websitesLessons learnt from scaling a Web 2.0 app to millions of usersOmar AL ZabirChief Architect, SaaS Platform, BTomaralzabir.comomaralzabir@gmail.comTwitter.com/omaralzabirBook “Building Web 2.0 portal using ASP.NET 3.5” from O’Reilly
How to blow up a websiteGet some super fast fiber broadband connection.Run this on couple of quad core desktops:for (int j = 0; j < 100; j ++){  for (inti = 0; i < 100; i ++)  {var client = new WebClient();client.DownloadStringAsync(         new Uri("http://www.microsoft.com/MISReport.aspx");  }Thread.Sleep(500);}
Prevent App Level DOS attackApplication Level DOS attacks are attempts to hit your expensive pages too frequently so that you have 100% CPU and your site goes down. For ex, hitting some expensive Report page continuously.You can run out of ASP.NET Threads and stop responding completely to any request.I’m not talking about Network level DOS attacks like TCP SYN flood or DDOS attacks that hardware firewalls can prevent.Firewalls don’t block legitimate requests.
Prevent App level DOS attacksProtect only expensive pages. Pages that are unlikely to get hit too many times within a short duration.Build a HttpModuleand hook on OnInitevent.Store which IP is making how many number of hits in last 10 minutes. Store the table in some in-memory cache.If the threshold has exceeded, stop responding to that IP. Call Response.End()Solution is here:http://tinyurl.com/omarDOS
ASP.NET ProcessModel OptimizationASP.NET ProcessModel DefaultsmaxWorkerThreads = 20maxIOThreads = 20memoryLimit = 60Nowadays, servers are way too powerful. You don’t need to be conservative.Change default process model setting in machine.config to make best use of CPU power.
ASP.NET Pipeline OptimizationDefault ASP.NET Pipeline has several components that intercept each and every request. Thus they add extra processing overhead on every request.Multiply the overhead by hundreds of requests per second – you get a significant overhead.
ASP.NET Pipeline OptimizationRemove what you don’t need.If you are using Forms Authentication, SQL Server storage, no web.config based role based permission then you can remove most of them:
Prevent large ASP.NET cookies on static contentEach and every request, even static files, get the ASP.NET cookies sent.517 bytes of worthless data per request.Avg pages have 40 resources. 40 x 517 = 20 KB.1M page view = 20 GB of data upload to server.Cookie:.DBANON=w3kYczsH8Wvzs6MgryS4JYEF0N-8ZR6aLRSTU9KwVaGaydD6WwUHD7X9tN8vBgjgzKf3r3SJHusTYFjU85yYfnunyCeuExcZs895JK9Fk1HS68ksGwm3QpxnRZvpDBAfJKEUKee2OTlND0gi43qwwtIPLeY1; ASP.NET_SessionId=bmnbp155wilotk45gjhitoqg; .DBAUTH12=2A848A8C200CB0E8E05C6EBA8059A0DBA228FC5F6EDD29401C249D237812344C15B3C5C57D6B776037FAA8F14017880E57BDC14A7963C58B0A0B30229AF0123A6DF56601D814E75525E7DCA9AD4A0EF200832B39A1F35A5111092F0805B0A8CD3D2FD5E3AB6176893D86AFBEB68F7EA42BE61E89537DEAA3279F3B576D0C44BA00B9FA1D9DD3EE985F37B0A5A134ADC0EA9C548D
Prevent ASP.NET cookies on static contentSetup a new website in IIS, map to the same code folder.Map static.yoursite.com host header to that website.Prefix all css, js, image links with http://static.yoursite.com/Add a Global.asax’sEndResponseevent on the new website.HttpContext context = HttpContext.Current;List<string> cookiesToClear = new List<string>();foreach(string cookieName in context.Request.Cookies){HttpCookiecookie = context.Request.Cookies[cookieName];cookiesToClear.Add(cookie.Name);}foreach(string name in cookiesToClear){HttpCookiecookie = new HttpCookie(name, string.Empty);cookie.Expires= DateTime.Today.AddYears(-1);context.Response.Cookies.Set(cookie);}
System.net optimizationIf you are using HttpWebRequest or WebClient or any other TCP/IP operation, increase the max connection limit.Default is 2 per IP.WCF service calls are limited by this setting.Unless you suspect rogue clients, set some reasonably high number on webservers, but moderate number on desktop clients.
System.net default setting is suboptimalBottleneckMax 2 concurrent calls
ASP.NET Profile ProviderAnonymous Provider creates one anonymous user in database on every first hit to Profile object’s Custom properties:The SP aspnet_Profile_GetProperties gets called when you access Profile object for first time in a request. And this SP is slooooooooow!
ASP.NET Profile ProviderThe slow SP that gets fired when you access custom Profile properties:CREATE PROCEDURE [dbo].[aspnet_Profile_GetProperties]    @ApplicationNamenvarchar(256),ASBEGIN    DECLARE @ApplicationIduniqueidentifier    SELECT @ApplicationId = NULL    SELECT @ApplicationId = ApplicationId                FROM dbo.aspnet_ApplicationsWHERE LOWER(@ApplicationName) = LoweredApplicationName………    IF (@@ROWCOUNT > 0)    BEGINUPDATE dbo.aspnet_Users        SET    LastActivityDate=@CurrentTimeUtc        WHERE UserId = @UserId    ENDEND
ASP.NET Profile ProviderThe slow SP’s execution plan
ASP.NET Profile ProviderDon’t update LastActivityDate when Profile object is loaded. Do it only when Profile object is updated.Update once every hour or so. If LastActivityDate < DateTime.Now.AddHours(-1) then update. No need to do per request or too frequently.Hard code the Application ID to avoid one lookup inside the SP.tinyurl.com/omarGetProp
ASP.NET MembershipASP.NET Membership Provider Stored Procs use default transaction isolation level, which is Serializable.Transaction (Process ID ##) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.Timeout Expired. The Timeout Period Elapsed Prior To Completion Of The Operation Or The Server Is Not Responding.ALTER PROCEDURE [dbo].[aspnet_Profile_GetProperties]@ApplicationNamenvarchar(256),@UserNamenvarchar(256),@CurrentTimeUtcdatetimeASBEGINSET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
ASP.NET Membership QueryCommon queries that brings down hell:Select * from aspnet_users where UserName = ‘blabla’Select * from aspnet_membership where Email = “someone@somewhere.com”What’s wrong with these queries?
ASP.NET Membership QueriesLet's look at the indexes: Table: aspnet_usersClustered Index = ApplicationID, LoweredUserNameNonClustered Index = ApplicationID, LastActivityDatePrimary Key = UserIDTable: aspnet_membershipClustered Index = ApplicationID, LoweredEmailNonClustered = UserIDTable: aspnet_ProfileClustered Index = UserIDDO NOT use Email or UserName fields in WHERE clause. They are not part of the index instead LoweredUserName and LoweredEmail fields are in conjunction with ApplicationID field. All queries must have ApplicationID in the WHERE clause.
A love story.NET 3.0 was released, woohoo!WCF!Lambda Expressions!!Linq to SQL!!!Upgraded to .NET 3.0, top to bottom.Major deployment over the weekend.Monday 9 AM, peak traffic.No response from site.
~100% on all web servers
Linq to SQL is not suitable for high volume web applicationsLinq to SQL is not optimized for web application.No disconnected entity support.Entities are not serializable.Linq to sql expressions consume high CPU when compiled to SQL.var query = from widget in dc.Widgetswhere widget.ID == id && widget.PageID == pageIdselect widget;var widget = query.SingleOrDefault();
How bad Linq to SQL is?Source: JD Conley’s blog
Fixing Linq to SQLConvert all queries to Compiled Queries.tinyurl.com/omarLINQ
Linq to SQL transaction deadlocksLarge table, high read and medium write, causes query timeouts, high locks, transaction deadlock because of SERIALIZATION isolation level.Transaction (Process ID ##) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.Timeout Expired. The Timeout Period Elapsed Prior To Completion Of The Operation Or The Server Is Not Responding.using (vardb= new YourDataContext2()) {    db.Connection.Open(); db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;"); varuser = db.aspnet_Users.First(); varpages = user.Pages.ToList(); }
Linq to SQL transaction deadlocksConnection does not close!Bug in Data Context code.Solution is to override the Dispose.class YourDataContext2 : YourDataContext, IDisposable{public new void Dispose() { if (base.Connection!= null) if (base.Connection.State!= System.Data.ConnectionState.Closed) { base.Connection.Close(); base.Connection.Dispose(); } base.Dispose(); } }
Content Delivery Network (CDN)CDN cache and deliver content from their servers that are closest to users’ computers. The closer servers are to end user, the shorter roundtrip time for every request. For ex, Akamai has servers almost every city in the world.Content from CDN nodes get served faster with lower latency than coming from your servers.CDN Nodes have better caching and compression algorithms.CDN nodes can offload your server and network from delivering static files. Thus better throughput for dynamic content.
Content Delivery Network0.7 secWashington, DC2.2 secAustralia
How CDN worksstatic.yoursite.comwww.yoursite.comHome User
Two types of CDNStatic – you upload the files to CDN and they give you an URL. E.g. yoursite.cachefly.net/logo.gifDynamic – Host your dynamic application behind the CDN. For ex, Edgecast and Panther Express.Very cheap - $0.2/GB
How Dynamic CDN workswww.yoursite.comStatic content cached,Compressed automatically
13 disasters for production websitesFaulty hard drive supplied by supplier, data corruption within weeks. Controller malfunctions and corrupts all disks in the same controller.RAID malfunction.CPU overheated and burned out.Firewall went down.Remote Desktop stopped working after a patch installation.Remote Desktop max connection exceeded. Cannot login anymore to servers.Database got corrupted while we were moving the production database from one server to another over the network.One developer deleted the production database accidentally while doing routine work.Support crew at hosting service formatted our running production server instead of a corrupted server that we asked to format.Windows got corrupted and was not working until we reinstalled.DNS goes down. Don’t get domain from GoDaddy.Internet backbone goes down in different part of the world.http://tinyurl.com/omar13
ConclusionASP.NET out of the box, does not scale for millions of hits.Must make the hacks at code, database and configuration level to get it to scale.That’s reality for any technology, not ASP.NET specific.

More Related Content

What's hot (18)

PDF
Building Web APIs that Scale
Salesforce Developers
 
PDF
Advanced Asp.Net Concepts And Constructs
Manny Siddiqui MCS, MBA, PMP
 
PPT
Building An Application For Windows Azure And Sql Azure
Eric Nelson
 
PPT
2310 b 15
Krazy Koder
 
PPT
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
Subhas Malik
 
PDF
Architetture Serverless con SQL Server e Azure Functions
Massimo Bonanni
 
PDF
Drupal Performance : DrupalCamp North
Philip Norton
 
PPTX
ASP.NET Core 1.0
Ido Flatow
 
PPTX
Play + scala + reactive mongo
Max Kremer
 
PPTX
Locking and Race Conditions in Web Applications
Andrew Kandels
 
PPTX
Web Servers(IIS, NGINX, APACHE)
Reza Jebeli
 
PPTX
Gruntwork Executive Summary
Yevgeniy Brikman
 
PPTX
Ch 04 asp.net application
Madhuri Kavade
 
PPTX
Asp Net Advance Topics
Ali Taki
 
PPT
Web Servers (ppt)
webhostingguy
 
PPTX
Owin from spec to application
damian-h
 
PPTX
Ajax ppt - 32 slides
Smithss25
 
Building Web APIs that Scale
Salesforce Developers
 
Advanced Asp.Net Concepts And Constructs
Manny Siddiqui MCS, MBA, PMP
 
Building An Application For Windows Azure And Sql Azure
Eric Nelson
 
2310 b 15
Krazy Koder
 
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
Subhas Malik
 
Architetture Serverless con SQL Server e Azure Functions
Massimo Bonanni
 
Drupal Performance : DrupalCamp North
Philip Norton
 
ASP.NET Core 1.0
Ido Flatow
 
Play + scala + reactive mongo
Max Kremer
 
Locking and Race Conditions in Web Applications
Andrew Kandels
 
Web Servers(IIS, NGINX, APACHE)
Reza Jebeli
 
Gruntwork Executive Summary
Yevgeniy Brikman
 
Ch 04 asp.net application
Madhuri Kavade
 
Asp Net Advance Topics
Ali Taki
 
Web Servers (ppt)
webhostingguy
 
Owin from spec to application
damian-h
 
Ajax ppt - 32 slides
Smithss25
 

Viewers also liked (17)

PDF
WebSockets with Spring 4
Sergi Almar i Graupera
 
KEY
Web Design Trends - the Do's and Don'ts of using HTML5
Kevin Bruce
 
PPTX
pengertian distribusi
dyanningsih
 
PPT
Scalability In PHP
Ian Selby
 
PDF
Consuming ASP.NET Web API with WebSockets
Maayan Glikser
 
PPTX
jChaart - Web Dashboard Framework
oazabir
 
PPTX
Building modern web sites with ASP .Net Web API, WebSockets and RSignal
Alessandro Pilotti
 
PDF
Test-Driven Infrastructure with CloudFormation and Cucumber.
Stelligent
 
PPTX
Performance is a feature! - London .NET User Group
Matt Warren
 
PDF
OpenROV: Node.js takes a dive into the ocean
Simone Chiaretta
 
PPTX
State management
teach4uin
 
PPTX
End to End Security with MVC and Web API
Michele Leroux Bustamante
 
PPTX
Design Practices for a Secure Azure Solution
Michele Leroux Bustamante
 
PPTX
Deploying web apis on core clr to docker
Glenn Block
 
PDF
Developing multi tenant applications for the cloud 3rd edition
Steve Xu
 
PPTX
Running Docker in Development & Production (#ndcoslo 2015)
Ben Hall
 
PPTX
The Velvet Revolution: Modernizing Traditional ASP.NET Apps with Docker
Elton Stoneman
 
WebSockets with Spring 4
Sergi Almar i Graupera
 
Web Design Trends - the Do's and Don'ts of using HTML5
Kevin Bruce
 
pengertian distribusi
dyanningsih
 
Scalability In PHP
Ian Selby
 
Consuming ASP.NET Web API with WebSockets
Maayan Glikser
 
jChaart - Web Dashboard Framework
oazabir
 
Building modern web sites with ASP .Net Web API, WebSockets and RSignal
Alessandro Pilotti
 
Test-Driven Infrastructure with CloudFormation and Cucumber.
Stelligent
 
Performance is a feature! - London .NET User Group
Matt Warren
 
OpenROV: Node.js takes a dive into the ocean
Simone Chiaretta
 
State management
teach4uin
 
End to End Security with MVC and Web API
Michele Leroux Bustamante
 
Design Practices for a Secure Azure Solution
Michele Leroux Bustamante
 
Deploying web apis on core clr to docker
Glenn Block
 
Developing multi tenant applications for the cloud 3rd edition
Steve Xu
 
Running Docker in Development & Production (#ndcoslo 2015)
Ben Hall
 
The Velvet Revolution: Modernizing Traditional ASP.NET Apps with Docker
Elton Stoneman
 
Ad

Similar to 10 performance and scalability secrets of ASP.NET websites (20)

PPT
IEEE KUET SPAC presentation
ahsanmm
 
PPTX
Asp.net performance
Abhishek Sur
 
PPTX
10 tips to make your ASP.NET Apps Faster
Brij Mishra
 
PDF
ASP.NET Scalability - NxtGen Oxford
Phil Pursglove
 
PDF
How to optimize asp dot-net application
sonia merchant
 
PDF
ASP.NET Scalability - DDD7
Phil Pursglove
 
PDF
ASP.NET Scalability - VBUG London
Phil Pursglove
 
PPTX
Tuga it 2016 improving your application performance
Nuno Caneco
 
DOCX
High performance coding practices code project
Pruthvi B Patil
 
PDF
ASP.NET Scalability - WebDD
Phil Pursglove
 
PPTX
Extended edition: How to speed up .NET and SQL Server web apps (2 x 45 mins w...
Bart Read
 
PPTX
ASP.NET MVC Zero to Hero
Md. Mahedee Hasan
 
PPTX
ASP.NET Quick Wins - 20 Tips and Tricks To Shift Your Application into High Gear
Kevin Griffin
 
PPTX
ASP.NET Best Practices - Useful Tips from the Trenches
Habeeb Rushdan
 
DOCX
Why use .net by naveen kumar veligeti
Naveen Kumar Veligeti
 
PPSX
06 asp.net session08
Vivek Singh Chandel
 
PDF
Asp.Net Tips
Susan Begonja
 
PDF
Fullstack LX - Improving your application performance
Nuno Caneco
 
PPT
Migrating To Visual Studio 2008 & .Net Framework 3.5
Jeff Blankenburg
 
PPTX
ConFoo 2017: Introduction to performance optimization of .NET web apps
Pierre-Luc Maheu
 
IEEE KUET SPAC presentation
ahsanmm
 
Asp.net performance
Abhishek Sur
 
10 tips to make your ASP.NET Apps Faster
Brij Mishra
 
ASP.NET Scalability - NxtGen Oxford
Phil Pursglove
 
How to optimize asp dot-net application
sonia merchant
 
ASP.NET Scalability - DDD7
Phil Pursglove
 
ASP.NET Scalability - VBUG London
Phil Pursglove
 
Tuga it 2016 improving your application performance
Nuno Caneco
 
High performance coding practices code project
Pruthvi B Patil
 
ASP.NET Scalability - WebDD
Phil Pursglove
 
Extended edition: How to speed up .NET and SQL Server web apps (2 x 45 mins w...
Bart Read
 
ASP.NET MVC Zero to Hero
Md. Mahedee Hasan
 
ASP.NET Quick Wins - 20 Tips and Tricks To Shift Your Application into High Gear
Kevin Griffin
 
ASP.NET Best Practices - Useful Tips from the Trenches
Habeeb Rushdan
 
Why use .net by naveen kumar veligeti
Naveen Kumar Veligeti
 
06 asp.net session08
Vivek Singh Chandel
 
Asp.Net Tips
Susan Begonja
 
Fullstack LX - Improving your application performance
Nuno Caneco
 
Migrating To Visual Studio 2008 & .Net Framework 3.5
Jeff Blankenburg
 
ConFoo 2017: Introduction to performance optimization of .NET web apps
Pierre-Luc Maheu
 
Ad

Recently uploaded (20)

PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 

10 performance and scalability secrets of ASP.NET websites

  • 1. 10 Performance and Scalability secrets of ASP.NET websitesLessons learnt from scaling a Web 2.0 app to millions of usersOmar AL ZabirChief Architect, SaaS Platform, [email protected]/omaralzabirBook “Building Web 2.0 portal using ASP.NET 3.5” from O’Reilly
  • 2. How to blow up a websiteGet some super fast fiber broadband connection.Run this on couple of quad core desktops:for (int j = 0; j < 100; j ++){ for (inti = 0; i < 100; i ++) {var client = new WebClient();client.DownloadStringAsync( new Uri("http://www.microsoft.com/MISReport.aspx"); }Thread.Sleep(500);}
  • 3. Prevent App Level DOS attackApplication Level DOS attacks are attempts to hit your expensive pages too frequently so that you have 100% CPU and your site goes down. For ex, hitting some expensive Report page continuously.You can run out of ASP.NET Threads and stop responding completely to any request.I’m not talking about Network level DOS attacks like TCP SYN flood or DDOS attacks that hardware firewalls can prevent.Firewalls don’t block legitimate requests.
  • 4. Prevent App level DOS attacksProtect only expensive pages. Pages that are unlikely to get hit too many times within a short duration.Build a HttpModuleand hook on OnInitevent.Store which IP is making how many number of hits in last 10 minutes. Store the table in some in-memory cache.If the threshold has exceeded, stop responding to that IP. Call Response.End()Solution is here:http://tinyurl.com/omarDOS
  • 5. ASP.NET ProcessModel OptimizationASP.NET ProcessModel DefaultsmaxWorkerThreads = 20maxIOThreads = 20memoryLimit = 60Nowadays, servers are way too powerful. You don’t need to be conservative.Change default process model setting in machine.config to make best use of CPU power.
  • 6. ASP.NET Pipeline OptimizationDefault ASP.NET Pipeline has several components that intercept each and every request. Thus they add extra processing overhead on every request.Multiply the overhead by hundreds of requests per second – you get a significant overhead.
  • 7. ASP.NET Pipeline OptimizationRemove what you don’t need.If you are using Forms Authentication, SQL Server storage, no web.config based role based permission then you can remove most of them:
  • 8. Prevent large ASP.NET cookies on static contentEach and every request, even static files, get the ASP.NET cookies sent.517 bytes of worthless data per request.Avg pages have 40 resources. 40 x 517 = 20 KB.1M page view = 20 GB of data upload to server.Cookie:.DBANON=w3kYczsH8Wvzs6MgryS4JYEF0N-8ZR6aLRSTU9KwVaGaydD6WwUHD7X9tN8vBgjgzKf3r3SJHusTYFjU85yYfnunyCeuExcZs895JK9Fk1HS68ksGwm3QpxnRZvpDBAfJKEUKee2OTlND0gi43qwwtIPLeY1; ASP.NET_SessionId=bmnbp155wilotk45gjhitoqg; .DBAUTH12=2A848A8C200CB0E8E05C6EBA8059A0DBA228FC5F6EDD29401C249D237812344C15B3C5C57D6B776037FAA8F14017880E57BDC14A7963C58B0A0B30229AF0123A6DF56601D814E75525E7DCA9AD4A0EF200832B39A1F35A5111092F0805B0A8CD3D2FD5E3AB6176893D86AFBEB68F7EA42BE61E89537DEAA3279F3B576D0C44BA00B9FA1D9DD3EE985F37B0A5A134ADC0EA9C548D
  • 9. Prevent ASP.NET cookies on static contentSetup a new website in IIS, map to the same code folder.Map static.yoursite.com host header to that website.Prefix all css, js, image links with http://static.yoursite.com/Add a Global.asax’sEndResponseevent on the new website.HttpContext context = HttpContext.Current;List<string> cookiesToClear = new List<string>();foreach(string cookieName in context.Request.Cookies){HttpCookiecookie = context.Request.Cookies[cookieName];cookiesToClear.Add(cookie.Name);}foreach(string name in cookiesToClear){HttpCookiecookie = new HttpCookie(name, string.Empty);cookie.Expires= DateTime.Today.AddYears(-1);context.Response.Cookies.Set(cookie);}
  • 10. System.net optimizationIf you are using HttpWebRequest or WebClient or any other TCP/IP operation, increase the max connection limit.Default is 2 per IP.WCF service calls are limited by this setting.Unless you suspect rogue clients, set some reasonably high number on webservers, but moderate number on desktop clients.
  • 11. System.net default setting is suboptimalBottleneckMax 2 concurrent calls
  • 12. ASP.NET Profile ProviderAnonymous Provider creates one anonymous user in database on every first hit to Profile object’s Custom properties:The SP aspnet_Profile_GetProperties gets called when you access Profile object for first time in a request. And this SP is slooooooooow!
  • 13. ASP.NET Profile ProviderThe slow SP that gets fired when you access custom Profile properties:CREATE PROCEDURE [dbo].[aspnet_Profile_GetProperties] @ApplicationNamenvarchar(256),ASBEGIN DECLARE @ApplicationIduniqueidentifier SELECT @ApplicationId = NULL SELECT @ApplicationId = ApplicationId FROM dbo.aspnet_ApplicationsWHERE LOWER(@ApplicationName) = LoweredApplicationName……… IF (@@ROWCOUNT > 0) BEGINUPDATE dbo.aspnet_Users SET LastActivityDate=@CurrentTimeUtc WHERE UserId = @UserId ENDEND
  • 14. ASP.NET Profile ProviderThe slow SP’s execution plan
  • 15. ASP.NET Profile ProviderDon’t update LastActivityDate when Profile object is loaded. Do it only when Profile object is updated.Update once every hour or so. If LastActivityDate < DateTime.Now.AddHours(-1) then update. No need to do per request or too frequently.Hard code the Application ID to avoid one lookup inside the SP.tinyurl.com/omarGetProp
  • 16. ASP.NET MembershipASP.NET Membership Provider Stored Procs use default transaction isolation level, which is Serializable.Transaction (Process ID ##) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.Timeout Expired. The Timeout Period Elapsed Prior To Completion Of The Operation Or The Server Is Not Responding.ALTER PROCEDURE [dbo].[aspnet_Profile_GetProperties]@ApplicationNamenvarchar(256),@UserNamenvarchar(256),@CurrentTimeUtcdatetimeASBEGINSET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  • 17. ASP.NET Membership QueryCommon queries that brings down hell:Select * from aspnet_users where UserName = ‘blabla’Select * from aspnet_membership where Email = “[email protected]”What’s wrong with these queries?
  • 18. ASP.NET Membership QueriesLet's look at the indexes: Table: aspnet_usersClustered Index = ApplicationID, LoweredUserNameNonClustered Index = ApplicationID, LastActivityDatePrimary Key = UserIDTable: aspnet_membershipClustered Index = ApplicationID, LoweredEmailNonClustered = UserIDTable: aspnet_ProfileClustered Index = UserIDDO NOT use Email or UserName fields in WHERE clause. They are not part of the index instead LoweredUserName and LoweredEmail fields are in conjunction with ApplicationID field. All queries must have ApplicationID in the WHERE clause.
  • 19. A love story.NET 3.0 was released, woohoo!WCF!Lambda Expressions!!Linq to SQL!!!Upgraded to .NET 3.0, top to bottom.Major deployment over the weekend.Monday 9 AM, peak traffic.No response from site.
  • 20. ~100% on all web servers
  • 21. Linq to SQL is not suitable for high volume web applicationsLinq to SQL is not optimized for web application.No disconnected entity support.Entities are not serializable.Linq to sql expressions consume high CPU when compiled to SQL.var query = from widget in dc.Widgetswhere widget.ID == id && widget.PageID == pageIdselect widget;var widget = query.SingleOrDefault();
  • 22. How bad Linq to SQL is?Source: JD Conley’s blog
  • 23. Fixing Linq to SQLConvert all queries to Compiled Queries.tinyurl.com/omarLINQ
  • 24. Linq to SQL transaction deadlocksLarge table, high read and medium write, causes query timeouts, high locks, transaction deadlock because of SERIALIZATION isolation level.Transaction (Process ID ##) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.Timeout Expired. The Timeout Period Elapsed Prior To Completion Of The Operation Or The Server Is Not Responding.using (vardb= new YourDataContext2()) { db.Connection.Open(); db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;"); varuser = db.aspnet_Users.First(); varpages = user.Pages.ToList(); }
  • 25. Linq to SQL transaction deadlocksConnection does not close!Bug in Data Context code.Solution is to override the Dispose.class YourDataContext2 : YourDataContext, IDisposable{public new void Dispose() { if (base.Connection!= null) if (base.Connection.State!= System.Data.ConnectionState.Closed) { base.Connection.Close(); base.Connection.Dispose(); } base.Dispose(); } }
  • 26. Content Delivery Network (CDN)CDN cache and deliver content from their servers that are closest to users’ computers. The closer servers are to end user, the shorter roundtrip time for every request. For ex, Akamai has servers almost every city in the world.Content from CDN nodes get served faster with lower latency than coming from your servers.CDN Nodes have better caching and compression algorithms.CDN nodes can offload your server and network from delivering static files. Thus better throughput for dynamic content.
  • 27. Content Delivery Network0.7 secWashington, DC2.2 secAustralia
  • 29. Two types of CDNStatic – you upload the files to CDN and they give you an URL. E.g. yoursite.cachefly.net/logo.gifDynamic – Host your dynamic application behind the CDN. For ex, Edgecast and Panther Express.Very cheap - $0.2/GB
  • 30. How Dynamic CDN workswww.yoursite.comStatic content cached,Compressed automatically
  • 31. 13 disasters for production websitesFaulty hard drive supplied by supplier, data corruption within weeks. Controller malfunctions and corrupts all disks in the same controller.RAID malfunction.CPU overheated and burned out.Firewall went down.Remote Desktop stopped working after a patch installation.Remote Desktop max connection exceeded. Cannot login anymore to servers.Database got corrupted while we were moving the production database from one server to another over the network.One developer deleted the production database accidentally while doing routine work.Support crew at hosting service formatted our running production server instead of a corrupted server that we asked to format.Windows got corrupted and was not working until we reinstalled.DNS goes down. Don’t get domain from GoDaddy.Internet backbone goes down in different part of the world.http://tinyurl.com/omar13
  • 32. ConclusionASP.NET out of the box, does not scale for millions of hits.Must make the hacks at code, database and configuration level to get it to scale.That’s reality for any technology, not ASP.NET specific.