Showing posts with label Performance optimization. Show all posts
Showing posts with label Performance optimization. Show all posts

Tuesday, November 7, 2023

Raspberry Pi - Fixing NAS (via SMB) slowness

This is a continuation of the Home NAS series, especially on how to increase the speed. The NAS is set up on a Raspberry Pi 4 B model. One of the older posts was debugging of NAS slowness and it concluded that the WiFi-5 is the bottleneck. Either Raspberry needs to be connected via cable or needs to use WiFi-6. Since the WiFi-6 is not natively supported by the RasPi the only option left was to connect via wire but it requires cabling through walls which is really a high effort. The cable-based internet connection is on the main level and the data center is upstairs. The data center here refers to a small rack where RasPi,2 external hard disks, and another laptop are sitting and running without GUI.

Move to 5G home internet

Fortunately or unfortunately the coaxial cable-based internet provider Xfinity increased their pricing which triggered the search for better options. Very quickly it landed on 5G home internet providers. Cheaper in price, ultra-fast connection in my area, is portable, has a WiFi-6 router built-in, etc...

Why T-Mobile?

There is no affection towards them also please note that I am not affiliated with T-Mobile in any way also this post is not sponsored by them. It is cheaper and one of my friends has it and has given good feedback. Also, it has 2 ethernet ports which seems normal in any modem-router combo.

Speed tests

As usual, I checked the speed using the same iperf3 tool before installing the 5G gateway. This is important as our previous test results may not be true now.

Yes, it is still slow. This will give a max of 10 MB/s only when copying files from NAS.

New setup

The RasPi also the client machine connected via wire and the readings are below.

Wow definitely higher than expected. It is time to copy a file and check the speed.
Yes, it is faster. This concluded that the SMB or anything in the RasPi or OS was not the problem. The network was the problem.

The Wi-Fi 6 test

Lastly, the Wi-Fi 6 test was also performed.

It is given great performance but not to the expected level. Anyway, the Wi-Fi was kind of free. It is wise to invest in a Wi-Fi 7 router when it arrives at an affordable cost after standards are finalized.

The table below is for reference.

RasPi NetworkDestination Networkiperf3 reading
Wi-Fi 5Wi-Fi580 Mbits/sec
WiredWired771 Mbits/sec
WiredWi-Fi6394 Mbits/sec

Bonus screenshot below that shows the internet speed test.

Wednesday, September 13, 2023

.Net Framework v/s .Net - One more performance comparison

Some of us might have heard why I should upgrade to .Net from legacy .Net Framework as it works and I want to run the application only on Windows servers. We as developers reply to them that .Net is modern and getting a lot of new features etc. Along with we emphasize that .Net is faster than .Net Framework. Should we use Linux to get that performance boost or will it be faster in Windows? There are a lot of comparisons¹ available on the net regarding the same. Here is one more comparison.

Application use case

This post is not to create a log of use cases and compare performance between the 2 frameworks. Rather this is comparing the encryption performance.
The application encrypts and decrypts data using X509Certificate. The use case tested may not be applicable in many projects but this is a solution to send data securely between the producers and one consumer. All the producers have the public key to encrypt and the consumer has the private key to decrypt.


This has projects that consume the shared code with minimal conditional compilations. Those are console apps and are ready to run with the required frameworks installed.

Please create an issue or give a PR if anyone finds problems in the test code.

Test environment

Model - HP EliteBook 840 G3
OS - Win 10 21H2 (OS Buid 19044.2194)
CPU - Intel i7-6600U @ 2.60Hz
RAM - 16GB
.Net Framework Version - 4.8(Runtime v4.0.30319)
.Net Version - .Net 6 (6.0.16)

Results

The .Net performs twice the speed of the .Net Framework. The picture is worth 1,000 words

The results were taken from an average of 3 attempts.

References


Tuesday, January 17, 2023

Azure @ Enterprise - Connection pooling behavior when JWT is used to authenticate into Azure SQL Server

Connection pooling in .Net is a hidden feature. We as consumer developers, cannot directly feel how the pooling happens behind the scenes. .Net is allowing us to clear the connection pool. We create a new SqlConnection and Close it after use. When we create a connection it uses an internal pooling mechanism and a connection object is associated with the object that we create and the closed connections go back to the pool.

This post is not to educate about simple connection pooling instead it talks about an issue encountered in production.

Issue

There is a .Net 6 Web API hosted in Azure App Service. It mainly accesses an Azure SQL database and storage blobs. When the load slightly increased, it started showing the below error.

System.Data.SqlClient.SqlException (0x80131904): Resource ID : 2. The session limit for the database is 600 and has been reached. See 'https://docs.microsoft.com/azure/azure-sql/database/resource-limits-logical-server' for assistance.

at System.Data.ProviderBase.DbConnectionPool.CheckPoolBlockingPeriod(Exception e)
 at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
  at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
  at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()

Troubleshooting

Let us start the production war to bring it back.

Q&A about connection pooling

Before starting specific troubleshooting let's refresh the main points about connection pooling. Experts may skip this section

Are there many connection pools?

Yes, there are chances of having many connection pools. For each connection string, it creates and maintains a separate connection pool.

How many connections are in a pool?

By default 100 per pool. It is configurable through the connection string or via code

When all the connections are in use and a connection is requested from the pool what will happen?

It will throw an exception after the connection timeout. Looks like 

"Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. 
This may have occurred because all pooled connections were in use and max pool size was reached."

Does the SQL Server know the consumers are keeping connections in the pool?

Yes. To simply verify just run exec sp_who2 in the SQL server to check the connections from the client machine. Most of the connections will be in the Sleeping state.

How to check the pooling status of our application?

Take a memory dump of the application and analyze the crude way using WinDbg or use the DebugDiag tool.
Otherwise, monitor the Performance counters related to ADO.Net.

Specific steps to troubleshoot the issue

Let us look at some specifics about this issue

What are the Azure SQL specs?

Standalone database, tier - S0

What is exec sp_who returns from the database?

A lot of connections in the sleeping state.

Are there 600+ requests coming to the App Service per second?

No. There are only 10 requests per second.

Is there auto-scaling of app service instances?

No. There is only 1 app service instance. Questions such as "who in the world runs App Service with only one instance in production" are banned.

Any other application is making connections to the same database?

Yes. But that Azure Function is now disabled. 

Is the connection string or code have any customization of connection pool size?

No customization. Just working with the default 100

What is the authentication mechanism for Azure SQL?

It is the service principal / Azure app registration. Uses certificate to obtain JWT.

How many connection pools are there?

Only god knows until we take a memory dump and analyze it.

Will there be one connection pool per JWT considering JWT is part of the connection string?

Oh yeah...There are chances if the JWT is not cached. If each SqlConnection is created with a separate JWT, it will create many pools with one connection. If that happens, we will not get the timeout error from the connection pool, but the Azure SQL will run out of connections. Resulting in the same exception as mentioned above.

Is there any Microsoft official documentation for the above answer?

Not really. But a GitHub Issue answering the question.

For further clarification look at the source code of SqlConnectionPoolKey.CalculateHashCode()

Disclaimer

The actual root cause cannot be disclosed on social media such as this blog due to security, confidentiality, etc...

Tuesday, July 5, 2022

Azure @ Enterprise - Serverless problems - Functions scales but Azure SQL and .Net Connection Pooling fails

Ideally this could have been a Twitter tweet.

Never make a intermediate component Serverless that auto scale

Serverless¹ is relatively new buzzword in the industry. We normally jump into serverless offerings as they are really attractive to manage and operate. The main feature that comes with Serverless is the auto scale. The Serverless compute that host out code is expected to scale out as the traffic increase.

Problem

If everything is that easy what is the problem? Let us consider the below architecture.


In case the architecture is not understandable, leave a comment. At first as a developer, we may not see any problem. But let us see this from the operations perspective.

  • It runs most of the day time
  • Intermittent failure starts in the evening
  • In the night it works fine again

Root cause

Debugging this problem would not be a herculean task as far as there is proper logging.
The S3 Azure SQL tier has limits ² on how many connections. During the day there are only users the load they generate can be handled by S3 tier. Evening there is overlap. Demon apps starts and there are still users. Then it fails. Again in the night users are logged out and it serves all daemon apps.

The catch here is the Azure Functions will auto scale but the SQL cannot hence fails.

References

Tuesday, March 9, 2021

Mind map on SQL Server Performance

Below is the mind map. The mind map is not complete. These are some ideas I got while working closely in performance.
These are just pointers to quickly refer what are the things to check when someone reports SQL Server performance issues. Need to google for the details on how to really optimize the performance.

Feel free to click on it and explore. Below is the link to GitHub. Feel free to issue pull requests if there are important things missing.


Tuesday, June 2, 2020

Azure @ Enterprise - Experiments with the smallest possible VM B1ls- Part 1 - Installing UI and Remote desktop

Experiments with the smallest possible VM Bl1s series
  1. Installing UI and Remote Desktop
  2. Installing web server
  3. Installing proxy

Introduction

Though cloud providers come up with abstracted PaaS solutions, the IaaS will be there for a while. The main problem with virtual machines is their cost. If we want to host a web site, it is very cheap to use PaaS option. Even in Azure, there is a free tier for Azure App Service also a freemium option in Azure Functions. AWS had a very low-cost VM from the earlier. But Azure added a similar one named B1ls last year only in the burstable B series. 
This is a series of posts on experimenting with that machine. It has only1 vCPU and 512MiB RAM. There are some other attempts with B1ls series on the internet which are interesting ones even to deploy docker swarm cluster.

Azure v/s AWS low-cost VMs

Below is a simple comparison of Azure v/s AWS in this low-cost burstable VMs scenario.

 Criteria Azure B1ls AWS T3.nano and T3a.nano  Comments
 Cost$.0052/h $.0047/h for T3a.nano
 CPU1 vCPU2 vCPU (up to 2.5 GHz) Hz of Azure to be filled
 Memory512 MiB .5 GiB 
Storage 4 GiB SSD  TBD 

Remote desktop

This experiment is to follow the Azure documentation to install a desktop environment into B1ls and try whether we can remote into. SSH works great.

The article followed is here. It uses xfce4 desktop environment which seems the lightweight option possible. Then xrdp to expose the remote desktop service.

After struggles, finally, I was able to get something thought not the full remote desktop. The screenshot is below.

Issued faced

Issue 1 - Not able to get lock to install

Error message
testadmin@PrimaryVM:~$ sudo apt-get -y install xfce4
E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is another process using it?
testadmin@PrimaryVM:~$ sudo apt-get -y install xfce4
E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), is an other process using it?


Troubleshooting
Followed all most all the techniques mentioned in this tutorial. Fortunately I was able to get it installed.

Issue 2 - Slowness

The installation was very slow. Finally, I had to take a workaround in the experiment by scaling up for the installation and scaling down to B1ls to do remote desktop.

Tuesday, November 12, 2019

Power BI Desktop Dashboard for IIS Log Analysis - Improved performance of PowerShell data prep script

This is the third post in the "Power BI Desktop Dashboard for IIS Log Analysis" series.

Power BI Desktop Dashboard for IIS Log Analysis
Power BI Desktop Dashboard for IIS Log Analysis - C# for IIS log parsing instead of PowerShell
Power BI Desktop Dashboard for IIS Log Analysis - Improved performance of PowerShell data prep script

Here we will be discussing how the data preparation process is enhanced by just using the LogParser command. In the initial versions, the time to prepare CSV from the .log file was high if the cs-byes and sc-bytes columns were missing. That is because the approach taken was to load the CSV file into PowerShell and add additional columns with a default value.

This time the approach changed a little bit and completely avoided the need to load CSV files into PowerShell. Logic is as follows

  1. Try to convert the input log files as-is on the assumption that the log contains all the required fields including cs-bytes and sc-bytes. This uses LogParser.exe
  2. In case of error, use the same LogParser.exe file with a slightly different query which selects '0 as cs-bytes, 0 as sc-bytes'. 
Click here to see the code changes in GitHub repo.

The fix is not rocket science. It is an obvious thing everybody knows but unfortunately missed in the earlier phase. Thanks, Wade Mascia for pointing out.


Happy Analyzing...

Tuesday, October 29, 2019

NewtonSoft Json Test pad

Nearly for the last 10 months half the time in my day job, I am working with Microsoft on optimizing the performance of our flagship application. Not really my current company's application but for the client which is one of the big 4 auditing firms. Sorry, as per NDA, I am not allowed to reveal the client name:)

It is a legacy application someone started in what we now call classic VB when I was in high school. It then converted to .Net then to WPF, then made SOA finally in AngularJS 1.X. I don't think its really converted but people started calling it in different technology. Nothing in WPF blocks you writing code in the WinForms way. It's really a legacy giant with 100s of .vbproj & .csproj files.

One of the problems we discovered was the JSON serialization. Though developers wanted to use NewtonSoft.JSON, they were using JavaScript serializer as that is the built-in JSON serializer in .Net. For using built in things, they don't need additional permissions. At some point, Microsoft figured out from the performance tuning data (perfview.exe) that the JavaScriptSerializer is slow than the NewtonSoft.JSON serializer. Though we all knew the fact, we never expected Microsoft telling that it is the bottleneck in the system and needs to be fixed.

It is declared that the NewtonSoft.JSON serializer would be the defacto serializer going forward. Developers started changing JavaScriptSerializer to NewsonSoft. 

One of the tools which came to demand is a test pad for NewtonSoft.JSON. Given a JSON string, how to easily develop the query to find something in JSON via NewtonSoft.JSON. We can easily use Linq but some are easy with the SelectToken(). We started searching for an online NewtonSoft test pad something similar to JSFiddle. Or some desktop tools similar to LINQPad.

After a good amount of googling ended up using https://dotnetfiddle.net. That has support to add nuget packages. Even we didn't have to start from scratch. Fork the below snippet to start with. 

https://dotnetfiddle.net/QQbpk5

Happy coding...

Tuesday, September 17, 2019

Power BI Desktop Dashboard for IIS Log Analysis

Introduction

As developers, we all might have encountered situations of analyzing IIS web server logs. During the development time, the file is small and easy to analyze in Notepad or Excel. But when it grows to GBs in production servers we use other tools. One such popular tool to query IIS logs is LogParser. It is a free command-line tool from Microsoft. There are graphical applications around it to generate even charts. One such free tool is the Log Parser Studio. It is also from Microsoft.

Once we move up in career and had to deal with managers, product stakeholders or even to CXO to show what the IIS logs say, we need more visuals or a dashboard reflecting the IIS logs. Though we can create visual using Log Parser Studio, it is tedious creating reports and charts one by one. 

One easier solution is to get in Azure and use Azure AppInsights which has built-in dashboards. We can do customizations easily. There are other services like Application Insight also such as Dynatrace, Retrace, etc...But the problem is that not all of us gets the luxury to buy the software and services we want. Sometimes our organization or clients may not be willing to buy. So let's look for other free solutions.

Enter Power BI

Power BI Desktop is a free visualization tool from Microsoft. It can easily produce great-looking visuals with data insights.
Fortunately, this is not the first post on PowerBI for IIS W3C log analysis. There is already one out. We are using it as a base and adding some more features.

https://blogs.msdn.microsoft.com/kennethteo/2018/04/27/analyzing-w3ciis-log-with-powerbi/

Prerequisites

Tools 

  • LogParser
  • Power BI Desktop - Free version is enough
Experience
  • Basics of PowerShell
  • LogParser queries.

Data preparation

The post by Kenneth uses .bat commands to trigger LogParser to convert .log files from IIS to csv. Those queries have hardcoded column names. The problem with that is we cannot just add more columns from IIS logs. Example cs-bytes and sc-bytes are the columns which are not enabled in IIS by default. Ideally, the solution is to use 'select * ' in the LogParser query. But the problem is that Power BI doesn't support (or more research needed) a flexible number of columns in CSV mapped properly to fixed columns. 
Hence using PowerShell to invoke LogParser which first try to convert .log to .csv including cs-bytes and sc-bytes. If those columns are not available, it tries without those columns which are the default setting in IIS. If those columns are not available, 0 / default value will be used.

PowerShell can be downloaded from the below location.

How to run PowerShell

  • Use the IIS to CSV.ps1 
  • Change the $inputPath to the folder where .log files are located
  • Run the ps1 file
  • The output .csv files will be generated in the same folder location.
Power BI template provided by Kenneth in his post has to be updated to reflect this change. Let's see those changes

Separation of concerns in Power BI dashboards

The Power BI template used by Kenneth has fewer reports and visuals. Obviously, that seems towards proving a concept. Let's add more visuals such as a dedicated page for errors, errors by server-ip to identify faulty servers.

Sample

Step by step instructions to add more visuals is not necessary as the PBI template itself can be shared and anyone can load their own data to it. Sample Power BI having more visuals has been uploaded to below location.

https://github.com/joymon/software-performance/tree/master/web/iis/log-analysis/Power%20BI/PBI-Template

Just prepare the CSV from .log files and update data source in PBI to reflect the changes in visuals.

Feel free to download and try it out. Any suggestions are welcome in Github as enhancements.

References

https://ideas.powerbi.com/forums/265200-power-bi-ideas/suggestions/6752494-web-servers-on-premise-for-iis-log-data
https://community.powerbi.com/t5/Desktop/IIS-log-files-convert-queries-to-PowerBI/td-p/166160
https://ittechnews.net/microsoft/official-microsoft-news/analyzing-w3c-iis-log-with-powerbi/

Tuesday, July 30, 2019

Angular + ASP.Net WebAPI Application Performance Optimization - Index and Mind map

This is an index of things which needs to be checked, for performance optimization of a simple ASP.Net + Angular application. The simple application refers to application which read and write to SQL Server. If the application uses some other data store, still the points about other aspects are valid.

The details of each item would be either a link to posts in this blog or link to other resources. If someone is struggling to find where to start or struck on an optimization exercise,hope these questions will light a bulb in their brain. Sorry to say that it is very difficult to find an algorithm which applies every performance optimizations.

Browser side

  • Do we need to support desktop and mobile browsers?
  • Any possibility to avoid Internet Explorer and support only modern browsers:)
  • Do we have separate mobile site with URL or same site is controlled via bootstrap or similar display technique
  • Static assets
    • Are those cached? If not can we cache?
    • If those are cached what is the cache expiry?
    • If those are cached how its done? cache-control or Expires header? Is the cache really working?
    • Is the server properly returning http 304?
    • Are they minified and bundled?
    • Are the images optimized to have small foot print? 
    • Are they served from CDN?
  • Angular best practices applied?
  • If it is AngularJS, what is the feasibility to upgrade to Angular

The network

DNS and routing

  • Hows the DNS resolved to IP?
  • Is the application available public or accessed only via enterprise intranet?
  • What is the network connection band width between clients and server? also between web servers and database server(s)

Network devices

  • CDN
    • Any option for warming up cache?
  • Security / Application Gateways which open packets and scan for attacks.
    • What is the time needed for security inspections? Is it fast, if we bye pass gateway for testing?
  • Network load-balancer
    • Do we have load balancer? Are we reached the height of optimization and need scale out or scale up? In Azure, the best practice is to use LB as the machines gets patches and restarts periodically. Also follow the best practices to group machines so that all of those will not be restarted same time.
    • What is the algorithm used for load balancing?
    • Do we have sticky session need?
  • Common
    • Do we have logs available from these devices?
    • Are the logs enough to confirm that the backing web server is taking time to respond?

Web Server machine

  • Does the requirement of project is practical to the server? eg: One quad core, 8GB VM may never support 100,000 concurrent users even if its a simple company static web site
  • Is the machine / hosting infrastructure in Azure or any cloud? If so do all the best practices followed and coded by considering cloud principles such as retry pattern?
  • What is the status of CPU, Memory, Network etc.. during load test or busy hour?

IIS

  • Logging
    • Does the logging (time-taken field) says requests are taking high time? Please note that that time includes server processing + data transfer
    • Are we logging any custom field which are big in size?
    • Are the extra logging such as failed request tracking enabled?
    • During a load test of busy session
      • If we go to IIS worker process screen are we able to see many requests pending?
      • What is the http queue length performance counter shows ?
      • Are we able to identify one or sub set of requests taking high chunk of processing time other than rest of requests? This can be done by analyzing IIS logs.
  • Static assets - Kind of repetition from previous section. 
    • Are they cached properly?
    • Are we using ASP.Net Bundling or compile time bundled? Are they served in minimized form
    • Can we increase cache expiry?
  • Protocols
    • Any possibility to leverage http/2, if not done?
    • Is it using web sockets?
  • Authentication
    • Is it using windows authentication? If so NTML or Kerberos? Kerberos is recommended for better performance
  • AppPool Recycling 
    • What is the AppPool recycling settings? 
    • Is the recycling causing delay?
    • Any ways to run mock requests so that the cache is populated before real user hit application?
  • Throttling / Limiting
    • What is the MaxConnection Setting and other IIS level throttling?
    • Are there any performance counter showing connections getting queued and rejected?
  • Timeouts
    • Is there any manual test and load test attempted by reducing the timeouts to lowest possible settings? Some times high timeouts cause some requests to occupy entire system resources
  • Payload
    • Does the http compression enabled

ASP.Net Application

ASP.Net pipeline till our code

  • What are the throttling settings at different level?
  • Are there any custom HttpModules which may reduce performance? Any unwanted modules?

Our code

  • Are there anything which can be cached instead of going every time to database? eg: any reference tables which change only by deployment.
  • Are there any retries happening and succeeding after lot of attempts? Try reducing retry count to 3.
  • Are there static variable usage and any potential for lock contention and memory leaks?
  • Are the locks applied to lowest possible code section?
  • JSON optimization
    • Can the property names be shortened?
    • Are the default values serialized into JSON?
  • Are we doing any HTML rendering at server and returning as JSON property? Any possibility to make application as pure client rendered SPA?
  • Do we have high amount of reflection?

.Net General

  • Are there high amount of GC collections? This can be found from analyzing performance counters?
  • What is the fragmentation level in LOH?
  • Can we do NGEN?
  • Any memory leaks in the application? eg: open connections, unwanted static things which may hold objects?

Database

  • Does the applications logs showing that the queries are taking time?
  • Does the SQL setup with possible best practices? eg: temp db, flags, connection limiting etc...
  • Are there any subset of SPs always slow?

Mind map

Finally, there is a mind map created using PlantUML for easy reference. Since this is kept textual in GitHub and rendered on demand, this would be living document than the post.

Details on how to get PlantUML working is available in different post including a YouTube video tutorial.

Other similar links

Tuesday, July 9, 2019

IIS Web server log parsing - URLs which takes highest percentage of time and payload

Identifying where to start fixing performance issues to increase throughput is a tricky question, if we are new to the web application. One way to find out what to fix is to find the costly URL operations in the application. If the IIS logs are available we can check what are the URLs taking highest % time in a given duration they are costly in the system 

Sometimes each URL may be taking 1 second but there are millions of instances and some other times there are less instances but each instance might be taking 10s of seconds. So finding the % of time a particular URL or pattern taking from the total request time if a good start than taking a long running but less in number URL request.

This helps if we need to increase the throughput of existing system or want to reduce the hardware maintaining the same throughput.

Below are the queries to find out the candidate URL. The fix has to be done by analyzing the URL and what and how it does internally.

Percentage of time spent time-taken

/*This script finds out what are the requests taking highest % of time in the entire duration of IIS logs
Better place the URLs to remove ids, GUIDs to find unique URLs*/

SELECT TOP 500  cs-uri-stem,
  COUNT(cs-uri-stem) AS TotalRequests,
  SUM(time-taken) AS SumTime,
  MUL(PROPSUM(time-taken), 100.0) AS PercentTime,
  MAX(time-taken) AS MaxTime,
  MIN(time-taken) AS MinTime,
  AVG(time-taken) AS AvgTime
FROM '[LOGFILEPATH]'
// WHERE condition for proper filtering
GROUP BY cs-uri-stem
ORDER BY PercentTime DESC

Percentage of % payload size 

SELECT TOP 500  cs-uri-stem,

  COUNT(cs-uri-stem) AS TotalRequests,
  SUM(sc-bytes) AS SumSCBytes,
  MUL(PROPSUM(sc-bytes), 100.0) AS PercentSize,
  MAX(sc-bytes) AS MaxSCBytes,
  MIN(sc-bytes) AS MinSCBytes,
  AVG(sc-bytes) AS AvgSCBytes

FROM '[LOGFILEPATH]'
// WHERE condition for proper filtering
GROUP BY cs-uri-stem

ORDER BY PercentSize DESC

Tuesday, June 11, 2019

.Net Server Performance - Important performance counters

The list of performance counters doesn't really a good fit to be inside a blog post. This is because it should be a living document. As and when we feel there is one more counter to be looked at we should add to the list. So its well suited as a gist which is easy to update than blog. Also someone interested can give pull request as well.

The main purpose of this list is to help collecting high level view about the performance of system. It may not tell which function or stored procedure is taking more time, but gives a view about where to start with. At least helps to determine whether to start from web server or database server.

This can be feed into an monitoring system such as Azure Application Insights for tracking the previous state. 

Tuesday, March 13, 2018

Uploading large files from browser to ASP.Net web server - WebSockets

Problem

Most of the applications are now web applications. When we are in browser we are in restricted area. We cannot code freely to leverage machine's full capabilities. One of the area where the limitation applies is on uploading large files which is a normal use case. Small files we can easily upload using file input control. But when the file size grows we get into trouble. 
There are so many solutions out there including third party controls. But what if we need to write one from scratch? What are the options?

Alternatives

We can use ActiveX controls which helps to unleash the potential of the machine. With the arrival of HTML5 FileAPI we have more control in the HTML itself. There are so many third parties who are making use of the same. If there is a way to use ActiveX or third party controls, the problem is solved. Else or you think the existing solutions are not enough, continue reading.

Solutions

There are many ways to upload files. Below are the principles taken on the solution approach

Principles

  • Never use ActiveX
  • Read the file without breaking the browser memory (chunking)
  • Should support up to 25GB file minimum.
  • Support scaling
There are reasons behind the principles but are not relevant at this point. Below is the first solution and that is going to be discussed in this post.

WebSockets

One of the modern way is the WebSockets. Below goes a repo which demos how the file can be read async and sync methods and send via WebSockets.

https://github.com/joymon/large-file-upload-from-browser

Feels free to surf the repo and comment. Will be adding more development notes soon.

Results

  • Using a Web Worker and FileReaderSync API seems faster than async FileReader API.

Limitations

Below goes some limits
  1. The connection has to be open. Affects scaling.
  2. Socket connection management is tedious
  3. The server is slower in reading and writing the files. Client reports it send all the data.

References

Tuesday, October 7, 2014

SQL Server internals - How to see where my data record stored

As I mentioned in many of my previous posts, its very difficult for me to learn something without seeing how its done internally. For example you can see how I explored .Net GC working in one my previous post. This time I am trying to learn how SQL Server stores that data internally.

Where SQL Server stores our tables & records?

As everybody knows, its in the disk only. But which file? Where its located. There are at least 2 files required for each database and we can see the file paths in the properties tab of SQL Server Database or query the details.

How the data records, tables are organized

We could see that the data is stored in normal files with extension .mdf,.ldf and .ndf. Does that mean we can open that in notepad and see it? Is the SQL Server just open the file and writing into it just like how we did in C/C++ labs in college?

Absolutely no. As SQL Server is a production ready software so it cannot do like academic code. It has more levels which optimize the storage techniques for maximum performance. One level is the file groups where we can specify more than one file for a group and associate with partition. Another level is the page. SQL Server considers a page as the atomic unit of storage. The page size is 8KB. It  does the IO operations such as reads / caches at page level only. Even if we need one record from a page, it reads the entire page.

Lets get into how the records are stored. As we know the physical storage order of records in SQL Server database is based on the clustered index and normally the primary key will be clustered index. We cannot have more than one physical storage order for data records. That's is why there is only one clustered index allowed.

How to inspect SQL Server pages

But there is something called non-clustered indexes. If the records cannot be physically stored in more than one order how they help us? Those are different data structures which tells the order of rows in a different way. Before going to "how the non-clustered indexes works" lets get full understanding about how the clustered index works and how to see the data inside page.

I am glad to say that people before me already thought in the same way and done enough hard work to explain the storage with good pictures. So why I need to do the task again? I just read their blogs and see understood how it works. So sharing the same via my blog.

Below is the blog post where I could see the storage is explained with undocumented SQL Server functions called DBCC IND & DBCC PAGE
http://www.mssqltips.com/sqlservertip/1578/using-dbcc-page-to-examine-sql-server-table-and-index-data/

References

http://www.practicalsqldba.com/2012/04/sql-server-index-fragmentation.html
https://www.simple-talk.com/sql/database-administration/sql-server-storage-internals-101/

My interest was about index fragmentation. So I did some more research on it and preparing my own post where we can see how fragmentation can be created and solved.

Tuesday, September 23, 2014

Leveraging PerfMon to monitor application / server health

Here I would like to discuss about a business scenario and solution we provided. Sorry to say that this post contains less code. 

I am not saying that this is the ultimate solution. Anybody can criticize so that I can improve the solution. 

Background

We have a generic queuing system in our project to off load long running process. The web layer which includes web site and web services just put the request in the queue so that it can return the response in 2 seconds by allowing the processing machines to process at a later time. The processing is done in a pull fashion instead of push fashion. Each processing machine (Windows 2008 virtual machines) knows what is its processing capacity and how many queue messages are currently running on it. Based on the current available processing capacity it de-queue requests / messages from the queue and process it. There is a proprietary algorithm which we developed for de-queuing messages based on other factors too such as priority of individual message or message type etc...

There is a web portal to monitor this environment. It tells how many messages waiting in the queue, what are the messages in progress, how many failed etc...

I would say its a cloud setup where we can add more processing servers to scale out based on the processing power requirement. But I don't know why nobody else in our project call it cloud :( . May be those poor guys don't know what is cloud? Or they didn't get any chance to experiment with commercial cloud and see how it scales :)

The problem here is to give a solution to visualize this queuing system in correlation with system performance. In other terms, the admins of this environment needs to see what is the processor utilization in a each processing machine when that is processing it's maximum number of messages. Based on that they can decide whether currently configured "maximum number of messages which can be processing concurrently" is really utilizing full system resources. If the concurrent requests configured is high than it's capacity ie over utilized, we can expect more failures (due to timeouts or memory problems ) in the processing servers. Else the system will be in underutilized state.

The solution

Approach 1

As I mentioned earlier, there is a web portal which displays details about queue system. Initial suggestions were to have a capturing mechanism to capture processor and memory snapshots of all the processing servers and display in the web portal using third party graph libraries.

Pros

  • Full control over data collection and display

Cons

  • Need license for third party. We could use open source but the client don't allow that
  • More development effort
Is this the best solution?

Approach 2

If we think about alternatives, we can end up in 3-4 alternatives. The one which got major support is "Using perfmon to show the queue details".

The solution is simple. Microsoft already invested enough in creating beautiful graph based UI for monitoring system performance and its called Perfmon, bundled along with Windows operating system. We can create our own performance counters and get it displayed there as well. We have such a nice tool, then why can't we leverage that to show queue details there and correlate with the system performance such as the processor utilization, memory etc...

Pros

  • No need of third party for visualization.
  • Simple to implement

Cons

  • Tomorrow if Microsoft discontinue perfmon, need to find alternative
  • Needs special permission if we are creating new perfmon category.

Code snippet

Without code, its very difficult for me to stop the post. So just sharing the links towards working with PerformanceCounters using .Net.


Registry permission for creating perfmon
http://bytes.com/topic/net/answers/501945-requested-registry-access-not-allowed-performance-counte

Monday, November 11, 2013

Understanding Windows Task Manager readings

Windows Task Tanager is a well known and frequently used software in windows. At least by the programmers. Developers mainly use Task Manager to close their ever running, not responding or slow programs. But actually what those reading tells us? 

It tells us about the Applications which are running, the Processes details, Windows Services information, network usage,Users who are all logged into the system along with overall system performance.

Recently I was interviewing so many developers for filling a position in "Performance & Memory team". Initially we were looking for people who have experience in performance profiling and memory optimizations. But no luck. Then we thought that we can give training to the people but he needs to be well aware of .Net internals. Again there was no luck. Finally we are trying for somebody who knows how the computer is functioning. I think if the developer, who don't know how his program is executed by the operating system, is not a good fit for performance team where he need to analyse other's code and improve its performance. One question I used to ask the candidates is about Task manager. Most of them, says "Sorry, to get my program working, I don't need to know about the readings in Task manager and it's interpretations and I survived 5-7 years in the field". I believe that by domination of managed execution environments such as Java & .Net, people forget about the machine which is actually doing their tasks. Sometimes I felt that understanding the system reading was not there in any of the programming books. 

This is just a simple initiative to aggregate the tutorials which will explain how to interpret the Task manager readings to a developer.

http://brandonlive.com/2010/02/21/measuring-memory-usage-in-windows-7/
http://windows.microsoft.com/en-in/windows-vista/what-do-the-task-manager-memory-columns-mean
http://blogs.technet.com/b/supportingwindows/archive/2013/05/03/finally-a-windows-task-manager-performance-tab-blog.aspx

Monday, July 1, 2013

What,Why & How to resolve OutOfMemoryException in .Net

This is a normal exception happens in most of the .net applications. When ever developers see this they start thinking about the RAM of the system and divert their thoughts towards physical memory. But before going to that area there are some other things to be noted. 

What is OutOfMemoryException

  • An Exception in .Net which will be fired when the .net runtime is not able to allocate memory for object
  • The MSIL instructions such as newobj,newarr and box may throw this exception

Why OutOfMemoryException is occuring

  • Its not actually because there is not enough memory in the machine.(Memory shown in Task manager) 
  • Its because there is not enough continuous free memory in the process's address space to do memory allocation for objects

How to resolve

  • Facts before you try to solve this issue.
  • Steps for quick fix.
    • Convert the application to 64bit. This will remove the 2GB memory limit on process and largely increase the process address space so that there will be lesser fragmentation which provides more continuous free memory space.
  • Steps for actual fix
    • Use tools such WinDbg, .Net memory profiler etc... to find out the size of objects in the process memory. In most cases this will be very less than the memory shown in task manager.You may also use performance monitor counters to do the same.
    • If the size of objects and task manager reading has less difference ,it means you actually uses so many objects or the object you created are not deallocated properly. Check for memory leaks and fix it.
    • Check for LOH (Large Object Heap) fragmentation and fix it.
    • If you really want to work with huge objects use MemoryFailPoint class
Reference
http://blogs.msdn.com/b/tess/archive/tags/memory+issues/
http://msdn.microsoft.com/en-us/magazine/cc163528.aspx
http://stackoverflow.com/questions/4767651/what-is-the-cause-of-outofmemoryexception-in-net-on-the-windows-service-under-a

Monday, February 25, 2013

SQL Server - FileStream content length using len and datalength

Basically there are some differences between len and datalength functions which almost all SQL developers may know. len() returns the no of characters by trimming the right side and datalength() returns the no of bytes used to store the data structure in the table.
I would like to add one more scenario to this comparison which is nothing but finding length of FileStream content. If you are new to SQL FileStream please refer this article. The scenario we were encountering was so simple. We had to list out all the files which are empty. To be more on business side, need to delete all the zero byte files in file stream storage table.
Below is the table def
CREATE TABLE [DocumentContent](
    [DocumentContentID] [uniqueidentifier] ROWGUIDCOL  NOT NULL,
    [FileStreamContent] [varbinary](max) FILESTREAM  NULL,
 CONSTRAINT [PK_DocumentContent] PRIMARY KEY NONCLUSTERED 
(
    [DocumentContentID] ASC
))
The initial query used to determine the list of blank files is
select DocumentContentID 
from DocumentContent 
where len(FileStreamContent) <=1
This works without errors but the time taken to execute is really huge and directly proportional to the no of documents in the table also the size of the documents. Sometimes exceeds 30 seconds and started getting timeouts and eventually deadlocks. So modified as follows.
select DocumentContentID 
from DocumentContent 
where datalength(FileStreamContent) <=1
It rocks. Now the query takes normal time even if the table has many rows.