WHAT'S NEW?
Loading...
Showing posts with label performance. Show all posts
Showing posts with label performance. Show all posts

Index

  • Intro
  • Hidden exceptions
  • Serialiation
  • SSL Overhead
  • Garbage collection
  • SQL performance
  • References

Intro

Here you will find some useful tips to improve the performance in your web applications based on Matt Watson webinar from Stackify. This is not the typical stuff about how to build your queries or caching calls to your backend. This is more the next things you should be taking care of.

Besides, today I want to introduce you to Prefix. A free tool that runs on the developers machine (not in servers) which helps you understanding where your apps spend most of its time.

Hidden exception

In our apps, exceptions happen even when nothing is notified to us. Take a look at the "Output view" in Visual Studio when you spin up your new MVC project. You will see some exceptions poping up there. This "hidden" exceptions required a handling process we should get rid of.

Add break on first time exceptions in your project configuration and you will start getting this like: first time you access the memory cache provider will trigger an exception because there's not a performance counter assigned to it.


Automatically log First time exceptions and Unhandled Exceptions with the following snippet:



Now I'm getting the whole stack trace from the exceptions triggered behind the scenes. Another best practice is the usage of TryParse functions when working with transformations.


Exceptions best practices:
  1. Avoid them at all costs
  2. Find hidden exceptions with Prefix
  3. Track all first chance exceptions to hunt them down
  4. Aggregate all exceptions in production

Serialization

Making calls to web services or databases and waiting for the answer takes a lot of time. My recommendation it's always check the database query or the process that happens on the backend. But when that bit can't be improved more (theoretically), then it's the time to talk about how the information travels from one place to another.

Web requests typically have the following steps:
  1. Serialize request
  2. Send request
  3. Receive response headers
  4. Download response
  5. Deserialize response.
You can get a really good insight of the time for each of those steps by using a tool like Prefix. Just install and it will start monitoring the traffic on your local dev box. Take a look at the following picture where a data binding happens and spends 119 ms. just on that.


A good approach on web services is always the use of asynchronous operations so the interface will respond the user commands. Check these two code methods where I'm passing an input parameter on the first one and I'm waiting for the interface to send an asynchronous string on the second one.




I found this table very useful to help you understand how long it takes the serialization process in different frameworks. Keep an eye on MVC serialization process when using objects as it's the slowest one.

Serialization best practices:
  1. Understand payload size
  2. Customize JSON serializers
  3. Consider manually reading incoming data

SSL Overhead

Broadly used across many applications, the security handler runs on your machines and takes care of the user validation and message encryption.



SSL best practices:
  1. Offload SSL to load balancer or hardware if possible (Netscaler, F5, etc.)
  2. User Azure Application Gateway for SSL offloading
  3. AWS use ELB with SSL

Garbage collection

One key metric to monitor is called "CLR Memory % Time in GC" which comes out of the box with Stackify.

GC best practices:
  1. Avoid the large object heap
    1. Use streams where you can (example above)
    2. Avoid large strings
  2. Microsoft new feature: Server vs workstation GC mode
  3. Monitor GC performance counters

SQL Performance

In the following example I validate the execution time for a SQL query which takes a few ms. to be executed. Notice on the bottom right corner it takes 6 seconds to download. This is very important to understand as your current performance analysis reports might be wrong.


This is why we need to understand not only how long it takes to run a query, we need the download time for the user to get the query on its computer (serialization).

SQL best practices:

  1. SQL server performance is not exactly the same as real world performance
  2. Your SQL performance reports are probably wrong
  3. Use your logging or Prefix to understand real world performance.

References

Index


  • Introduction
  • Logging and tracing
  • Profiling
  • Performance counters
  • References

Introduction

This post is part of a series of post to help you prepare the MCSD certification, particularly the certification exam 70-483, based on the book:


You will find all the code available in the following GitHub repository. Lets talk a little bit about threads and how they work using a .Net development environment.

Logging and tracing

  • Tracing refers to monitor the execution of your applications. Typically, you enable it when you want to investigate something. 
  • Logging is always enabled and tracks events occurring within your application, can be an error or just some useful information. In case of something critical occurred you can rise an email to someone.

.Net helps you to trace and log your app with the Debug class within the System.Diagnostics namespace. As its name suggests is only available in debug mode (the ConditionalAttribute with a value of DEBUG is applied to this class). By default, it writes to the Output window, see the following example where if the Debug.Assert fails a message box asks you to retry, abort or ignore.


The TraceSource class can be used in a similar way as before but it gives us more functionality by using its three parameters:
  1. severity of the event happened with the TraceEventType enum:
    1. Critical: most severe
    2. Error: problem handled.
    3. Warning: something unusual
    4. Information: relevant data
    5. Verbose: the loosest
    6. Stop/Start/Suspend/Resume/Transfer: related to the flow of the app
  2. id to group our calls with the event ID number. Our own groups 
    1. 1.000-1.999 Db calls
    2. 10.000-19.000 WS calls
  3. Message displayed.
Example of the TraceSource usage:


By default all is written to the Output window. TraceListeners can help you to change this behavior. Types of TraceListeners:
  • ConsoleTraceListener
  • DelimitedListTraceListener
  • EventLogTraceListener
  • TextWriteTraceListener
  • XmlWriteTraceListener
Example of how to change the default output of a TraceSource using a TraceListener programmaticly:


You can define these listeners within your application configuration file (app.config / web.config) which makes more easier to change it in live environments instead of having to change your code and doing a new deployment.

You can also write your logs directly to the Windows Event Log by using the EventLog class within the System.Diagnostics namespace (remember to run Visual Studio as administrator). The following example will create a new entry in the Windows event log and in the second execution will add an event to that entry. You can open the "Event Viewer" in Windows and look for "MyNewLog" within the "Applications and Service logs".


To read the event log you can do it programmatically by getting an EventLogEntry object and reading its properties. Besides, you can subscribe to changes with the EntryWritten event and be notified when a new entry is added. See examples here:


Profiling

Profiling refers to the amount of memory your apps use, which methods are called, for how long... The Stopwatch class within the System.Diagnostics namespace will help you found bottlenecks in your code by telling you the time spent in certain areas by calling: Start, Stop and Reset methods.

Visual Studio also has a wizard tool to check performance in your apps within the Analyze menu. You will find four options there:

  1. CPU sampling: it's an initial search for performance problems.
  2. Instrumentation: timing information for each function called.
  3. .Net memory allocation
  4. Resource content data: multithreaded application, it helps you find out why methods have to wait until certain resource is released.

Performance counters

The most typical are: CPU usage, memory usage or length of a query, and all can be viewed with the app perfmon.exe provided by Windows. You can read them by code:



Bear in mind you need to be administrator or member of the "Performance Monitor Users" group. As you can see in the example the PerformanceCounter class implements the IDisposable interface because we can use the using statement. The following types can be useful when you plan to create your own performance counters:

  • NumberOfItems32 / NumberOfItems64: number of operations
  • RateOfCountsPerSecond32 / RateOfCountsPerSecond64: calculate the amount per second of an item or operation
  • AverageTimer32
This is all for today and with this post we've finished chapter number 3. I hope you learnt something today and I hope to see you in the next post.