SlideShare une entreprise Scribd logo
1  sur  32
10 Performance and Scalability secrets of ASP.NET websites Lessons learnt from scaling a Web 2.0 app to millions of users Omar AL Zabir Chief Architect, SaaS Platform, BT omaralzabir.com omaralzabir@gmail.com Twitter.com/omaralzabir Book “Building Web 2.0 portal using ASP.NET 3.5” from O’Reilly
How to blow up a website Get 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 attack Application 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 attacks Protect 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 Optimization ASP.NET ProcessModel Defaults maxWorkerThreads = 20 maxIOThreads = 20 memoryLimit = 60 Nowadays, 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 Optimization Default 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 Optimization Remove 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 content Each 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 content Setup 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 optimization If 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 suboptimal Bottleneck Max 2 concurrent calls
ASP.NET Profile Provider Anonymous 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 Provider The slow SP that gets fired when you access custom Profile properties: CREATE PROCEDURE [dbo].[aspnet_Profile_GetProperties]     @ApplicationNamenvarchar(256), AS BEGIN     DECLARE @ApplicationIduniqueidentifier     SELECT @ApplicationId = NULL     SELECT @ApplicationId = ApplicationId                 FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName … … …     IF (@@ROWCOUNT > 0)     BEGIN UPDATE dbo.aspnet_Users         SET    LastActivityDate=@CurrentTimeUtc         WHERE UserId = @UserId     END END
ASP.NET Profile Provider The slow SP’s execution plan
ASP.NET Profile Provider Don’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 Membership ASP.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),@CurrentTimeUtcdatetimeASBEGIN SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
ASP.NET Membership Query Common 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 Queries Let's look at the indexes:  Table: aspnet_users Clustered Index = ApplicationID, LoweredUserName NonClustered Index = ApplicationID, LastActivityDate Primary Key = UserID Table: aspnet_membership Clustered Index = ApplicationID, LoweredEmail NonClustered = UserID Table: aspnet_Profile Clustered Index = UserID DO 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 applications Linq 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 SQL Convert all queries to Compiled Queries. tinyurl.com/omarLINQ
Linq to SQL transaction deadlocks Large 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 deadlocks Connection 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 Network 0.7 sec Washington, DC 2.2 sec Australia
How CDN works static.yoursite.com www.yoursite.com Home User
Two types of CDN Static – you upload the files to CDN and they give you an URL. E.g. yoursite.cachefly.net/logo.gif Dynamic – Host your dynamic application behind the CDN. For ex, Edgecast and Panther Express. Very cheap - $0.2/GB
How Dynamic CDN works www.yoursite.com Static content cached, Compressed automatically
13 disasters for production websites Faulty 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
Conclusion ASP.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.

Contenu connexe

Tendances

Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application
Madhuri Kavade
 
Asp Net Advance Topics
Asp Net Advance TopicsAsp Net Advance Topics
Asp Net Advance Topics
Ali Taki
 

Tendances (19)

Building Web APIs that Scale
Building Web APIs that ScaleBuilding Web APIs that Scale
Building Web APIs that Scale
 
Advanced Asp.Net Concepts And Constructs
Advanced Asp.Net Concepts And ConstructsAdvanced Asp.Net Concepts And Constructs
Advanced Asp.Net Concepts And Constructs
 
Building An Application For Windows Azure And Sql Azure
Building An Application For Windows Azure And Sql AzureBuilding An Application For Windows Azure And Sql Azure
Building An Application For Windows Azure And Sql Azure
 
2310 b 15
2310 b 152310 b 15
2310 b 15
 
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide showThe complete ASP.NET (IIS) Tutorial with code example in power point slide show
The complete ASP.NET (IIS) Tutorial with code example in power point slide show
 
Architetture Serverless con SQL Server e Azure Functions
Architetture Serverless con SQL Server e Azure FunctionsArchitetture Serverless con SQL Server e Azure Functions
Architetture Serverless con SQL Server e Azure Functions
 
Drupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp NorthDrupal Performance : DrupalCamp North
Drupal Performance : DrupalCamp North
 
ASP.NET Core 1.0
ASP.NET Core 1.0ASP.NET Core 1.0
ASP.NET Core 1.0
 
(WEB307) Scalable Site Management Using AWS OpsWorks | AWS re:Invent 2014
(WEB307) Scalable Site Management Using AWS OpsWorks | AWS re:Invent 2014(WEB307) Scalable Site Management Using AWS OpsWorks | AWS re:Invent 2014
(WEB307) Scalable Site Management Using AWS OpsWorks | AWS re:Invent 2014
 
Play + scala + reactive mongo
Play + scala + reactive mongoPlay + scala + reactive mongo
Play + scala + reactive mongo
 
Locking and Race Conditions in Web Applications
Locking and Race Conditions in Web ApplicationsLocking and Race Conditions in Web Applications
Locking and Race Conditions in Web Applications
 
Web Servers(IIS, NGINX, APACHE)
Web Servers(IIS, NGINX, APACHE)Web Servers(IIS, NGINX, APACHE)
Web Servers(IIS, NGINX, APACHE)
 
Web303
Web303Web303
Web303
 
Gruntwork Executive Summary
Gruntwork Executive SummaryGruntwork Executive Summary
Gruntwork Executive Summary
 
Ch 04 asp.net application
Ch 04 asp.net application Ch 04 asp.net application
Ch 04 asp.net application
 
Asp Net Advance Topics
Asp Net Advance TopicsAsp Net Advance Topics
Asp Net Advance Topics
 
Web Servers (ppt)
Web Servers (ppt)Web Servers (ppt)
Web Servers (ppt)
 
Owin from spec to application
Owin from spec to applicationOwin from spec to application
Owin from spec to application
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 

En vedette

Web Design Trends - the Do's and Don'ts of using HTML5
Web Design Trends - the Do's and Don'ts of using HTML5Web Design Trends - the Do's and Don'ts of using HTML5
Web Design Trends - the Do's and Don'ts of using HTML5
Kevin Bruce
 
jChaart - Web Dashboard Framework
jChaart - Web Dashboard FrameworkjChaart - Web Dashboard Framework
jChaart - Web Dashboard Framework
oazabir
 
Developing multi tenant applications for the cloud 3rd edition
Developing multi tenant applications for the cloud 3rd editionDeveloping multi tenant applications for the cloud 3rd edition
Developing multi tenant applications for the cloud 3rd edition
Steve Xu
 

En vedette (17)

WebSockets with Spring 4
WebSockets with Spring 4WebSockets with Spring 4
WebSockets with Spring 4
 
Web Design Trends - the Do's and Don'ts of using HTML5
Web Design Trends - the Do's and Don'ts of using HTML5Web Design Trends - the Do's and Don'ts of using HTML5
Web Design Trends - the Do's and Don'ts of using HTML5
 
pengertian distribusi
pengertian distribusipengertian distribusi
pengertian distribusi
 
Scalability In PHP
Scalability In PHPScalability In PHP
Scalability In PHP
 
Consuming ASP.NET Web API with WebSockets
Consuming ASP.NET Web API with WebSocketsConsuming ASP.NET Web API with WebSockets
Consuming ASP.NET Web API with WebSockets
 
jChaart - Web Dashboard Framework
jChaart - Web Dashboard FrameworkjChaart - Web Dashboard Framework
jChaart - Web Dashboard Framework
 
Building modern web sites with ASP .Net Web API, WebSockets and RSignal
Building modern web sites with ASP .Net Web API, WebSockets and RSignalBuilding modern web sites with ASP .Net Web API, WebSockets and RSignal
Building modern web sites with ASP .Net Web API, WebSockets and RSignal
 
Test-Driven Infrastructure with CloudFormation and Cucumber.
Test-Driven Infrastructure with CloudFormation and Cucumber. Test-Driven Infrastructure with CloudFormation and Cucumber.
Test-Driven Infrastructure with CloudFormation and Cucumber.
 
Performance is a feature! - London .NET User Group
Performance is a feature! - London .NET User GroupPerformance is a feature! - London .NET User Group
Performance is a feature! - London .NET User Group
 
OpenROV: Node.js takes a dive into the ocean
OpenROV: Node.js takes a dive into the oceanOpenROV: Node.js takes a dive into the ocean
OpenROV: Node.js takes a dive into the ocean
 
State management
State managementState management
State management
 
End to End Security with MVC and Web API
End to End Security with MVC and Web APIEnd to End Security with MVC and Web API
End to End Security with MVC and Web API
 
Design Practices for a Secure Azure Solution
Design Practices for a Secure Azure SolutionDesign Practices for a Secure Azure Solution
Design Practices for a Secure Azure Solution
 
Deploying web apis on core clr to docker
Deploying web apis on core clr to dockerDeploying web apis on core clr to docker
Deploying web apis on core clr to docker
 
Developing multi tenant applications for the cloud 3rd edition
Developing multi tenant applications for the cloud 3rd editionDeveloping multi tenant applications for the cloud 3rd edition
Developing multi tenant applications for the cloud 3rd edition
 
Running Docker in Development & Production (#ndcoslo 2015)
Running Docker in Development & Production (#ndcoslo 2015)Running Docker in Development & Production (#ndcoslo 2015)
Running Docker in Development & Production (#ndcoslo 2015)
 
The Velvet Revolution: Modernizing Traditional ASP.NET Apps with Docker
The Velvet Revolution: Modernizing Traditional ASP.NET Apps with DockerThe Velvet Revolution: Modernizing Traditional ASP.NET Apps with Docker
The Velvet Revolution: Modernizing Traditional ASP.NET Apps with Docker
 

Similaire à 10 performance and scalability secrets of ASP.NET websites

Asp.net performance
Asp.net performanceAsp.net performance
Asp.net performance
Abhishek Sur
 
Wss Object Model
Wss Object ModelWss Object Model
Wss Object Model
maddinapudi
 
C# and ASP.NET Code and Data-Access Security
C# and ASP.NET Code and Data-Access SecurityC# and ASP.NET Code and Data-Access Security
C# and ASP.NET Code and Data-Access Security
Darren Sim
 

Similaire à 10 performance and scalability secrets of ASP.NET websites (20)

PPT
PPTPPT
PPT
 
Why use .net by naveen kumar veligeti
Why use .net by naveen kumar veligetiWhy use .net by naveen kumar veligeti
Why use .net by naveen kumar veligeti
 
Tuning and optimizing webcenter spaces application white paper
Tuning and optimizing webcenter spaces application white paperTuning and optimizing webcenter spaces application white paper
Tuning and optimizing webcenter spaces application white paper
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
 
NET_Training.pptx
NET_Training.pptxNET_Training.pptx
NET_Training.pptx
 
More Asp
More AspMore Asp
More Asp
 
IIS 7: The Administrator’s Guide
IIS 7: The Administrator’s GuideIIS 7: The Administrator’s Guide
IIS 7: The Administrator’s Guide
 
Walther Ajax4
Walther Ajax4Walther Ajax4
Walther Ajax4
 
Windows Azure and a little SQL Data Services
Windows Azure and a little SQL Data ServicesWindows Azure and a little SQL Data Services
Windows Azure and a little SQL Data Services
 
Migration from ASP to ASP.NET
Migration from ASP to ASP.NETMigration from ASP to ASP.NET
Migration from ASP to ASP.NET
 
ASP.NET Core 2.1: The Future of Web Apps
ASP.NET Core 2.1: The Future of Web AppsASP.NET Core 2.1: The Future of Web Apps
ASP.NET Core 2.1: The Future of Web Apps
 
Asp.net performance
Asp.net performanceAsp.net performance
Asp.net performance
 
IBM Connect 2016 - Break out of the Box
IBM Connect 2016 - Break out of the BoxIBM Connect 2016 - Break out of the Box
IBM Connect 2016 - Break out of the Box
 
Wss Object Model
Wss Object ModelWss Object Model
Wss Object Model
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
 
NodeJS @ ACS
NodeJS @ ACSNodeJS @ ACS
NodeJS @ ACS
 
ASP.NET Core 2.1: The Future of Web Apps
ASP.NET Core 2.1: The Future of Web AppsASP.NET Core 2.1: The Future of Web Apps
ASP.NET Core 2.1: The Future of Web Apps
 
C# and ASP.NET Code and Data-Access Security
C# and ASP.NET Code and Data-Access SecurityC# and ASP.NET Code and Data-Access Security
C# and ASP.NET Code and Data-Access Security
 
Asp.net tips
Asp.net tipsAsp.net tips
Asp.net tips
 
IIS 6.0 and asp.net
IIS 6.0 and asp.netIIS 6.0 and asp.net
IIS 6.0 and asp.net
 

Dernier

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

10 performance and scalability secrets of ASP.NET websites

  • 1. 10 Performance and Scalability secrets of ASP.NET websites Lessons learnt from scaling a Web 2.0 app to millions of users Omar AL Zabir Chief Architect, SaaS Platform, BT omaralzabir.com omaralzabir@gmail.com Twitter.com/omaralzabir Book “Building Web 2.0 portal using ASP.NET 3.5” from O’Reilly
  • 2. How to blow up a website Get 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 attack Application 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 attacks Protect 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 Optimization ASP.NET ProcessModel Defaults maxWorkerThreads = 20 maxIOThreads = 20 memoryLimit = 60 Nowadays, 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 Optimization Default 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 Optimization Remove 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 content Each 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 content Setup 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 optimization If 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 suboptimal Bottleneck Max 2 concurrent calls
  • 12. ASP.NET Profile Provider Anonymous 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 Provider The slow SP that gets fired when you access custom Profile properties: CREATE PROCEDURE [dbo].[aspnet_Profile_GetProperties] @ApplicationNamenvarchar(256), AS BEGIN DECLARE @ApplicationIduniqueidentifier SELECT @ApplicationId = NULL SELECT @ApplicationId = ApplicationId FROM dbo.aspnet_Applications WHERE LOWER(@ApplicationName) = LoweredApplicationName … … … IF (@@ROWCOUNT > 0) BEGIN UPDATE dbo.aspnet_Users SET LastActivityDate=@CurrentTimeUtc WHERE UserId = @UserId END END
  • 14. ASP.NET Profile Provider The slow SP’s execution plan
  • 15. ASP.NET Profile Provider Don’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 Membership ASP.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),@CurrentTimeUtcdatetimeASBEGIN SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
  • 17. ASP.NET Membership Query Common 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?
  • 18. ASP.NET Membership Queries Let's look at the indexes: Table: aspnet_users Clustered Index = ApplicationID, LoweredUserName NonClustered Index = ApplicationID, LastActivityDate Primary Key = UserID Table: aspnet_membership Clustered Index = ApplicationID, LoweredEmail NonClustered = UserID Table: aspnet_Profile Clustered Index = UserID DO 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 applications Linq 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 SQL Convert all queries to Compiled Queries. tinyurl.com/omarLINQ
  • 24. Linq to SQL transaction deadlocks Large 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 deadlocks Connection 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 Network 0.7 sec Washington, DC 2.2 sec Australia
  • 28. How CDN works static.yoursite.com www.yoursite.com Home User
  • 29. Two types of CDN Static – you upload the files to CDN and they give you an URL. E.g. yoursite.cachefly.net/logo.gif Dynamic – Host your dynamic application behind the CDN. For ex, Edgecast and Panther Express. Very cheap - $0.2/GB
  • 30. How Dynamic CDN works www.yoursite.com Static content cached, Compressed automatically
  • 31. 13 disasters for production websites Faulty 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. Conclusion ASP.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.