Tips And Tricks To Improve WEB API Performance

Web API is a technology from Microsoft as a part of .NET framework, that enables users to communicate with heterogeneous platforms including website, mobiles, and desktop applications etc. While writing the Web API, we should focus on its performance and response time. Here, I have listed a few points to be considered while working for increasing the performance of Web API.

Use Parallel Programming in Web API 

Web API logic mainly deals with 2 important functions - Post data to the server for inserting or updating, and Fetch data from the server. When we have thousands of records to fetch from server, the response time is very very high. This is because sometimes we will have to loop through the data-source, make several changes, and then send the data to the client. And, a simple foreach loop is a single threaded loop which processesthe data sequentially, one by one, to give the result set.

So, in this case, it is recommended to use parallel foreach loop while getting the data from the server. As the parallel foreach loop works in multi-threaded environment, the execution will be faster than foreach loop.

Execution Process of Parallel Foreach loop,
  1. List<Employee> li = new List<Employee>();  
  2.            li.Add(new Employee { Id = 1001, Name = "Sambid", Company = "DELL", Location = "Bangalore" });  
  3.            li.Add(new Employee { Id = 1002, Name = "Sumit", Company = "DELL", Location = "Bangalore" });  
  4.            li.Add(new Employee { Id = 1003, Name = "Koushal", Company = "Infosys", Location = "New Delhi" });  
  5.            li.Add(new Employee { Id = 1004, Name = "Kumar", Company = "TCS", Location = "Bangalore" });  
  6.            li.Add(new Employee { Id = 1005, Name = "Mohan", Company = "Microsoft", Location = "Hyderabad" });  
  7.            li.Add(new Employee { Id = 1006, Name = "Tushar", Company = "Samsung", Location = "Hyderabad" });  
  8.            li.Add(new Employee { Id = 1007, Name = "Jia", Company = "TCS", Location = "Pune" });  
  9.            li.Add(new Employee { Id = 1008, Name = "KIRAN", Company = "CTS", Location = "Bangalore" });  
  10.            li.Add(new Employee { Id = 1009, Name = "Rinku", Company = "CGI", Location = "Bangalore" });  
And, here is the Employee class.
  1. public class Employee  
  2.    {  
  3.        public int Id { get; set; }  
  4.        public string Name { get; set; }  
  5.        public string Company { get; set; }  
  6.        public string Designation { get; set; }  
  7.        public string Location { get; set; }  
  9.    }  
This is how we can use Parallel Foreach loop.
The loop will execute at once and give the result. In case of Foreach Loop, it gives results one by one. Suppose we have 1000 records in the result set, the loop will execute one by one 1000 times to give the result.

Note- Please don't use the Parallel foreach loop while you have very little amount of records to fetch.

Use Asynchronous Programming to handle the concurrent HTTP requests

What happens in synchronous programming is that whenever a request comes for executing a Web API, a thread from Thread Pool is assigned to the request to execute. This thread is blocked until the process is executed and returns the result.
Here, the T2 thread remains blocked until it processes the request and returns the result, and if it encounters a long loop for execution, it takes a lot of time and waits till the end.

Suppose we have only 3 threads and all the threads have been assigned to three requests that have been waiting in the queue. In that situation, if 4th request comes as we have implemented it synchronously, it will give error because now it doesn't have any thread to handle the request.

So, to handle more numbers of concurrent HTTP requests, we have to use Async Programming.

Asynchronous request handlers operate somewhat differently. When a request comes to the Web API Controller it takes one of its thread pool threads and assigns it to that request.

While the process will start executing, the thread will be returned to the thread pool. After finishing the execution, one more thread is allocated for the request to bringing the request.So, in this way, the thread will not wait until the completion of process execution and come back to the thread pool for handling another Request.

So, here I have given a small example of registration and how should we use Async programming in Web API.
  1. [AllowAnonymous]  
  2.       [Route("Register")]  
  4.       public async Task<IHttpActionResult> Register(RegisterBindingModel model)  
  5.       {  
  6.           Dictionary<object, object> dict = new Dictionary<object, object>();  
  7.           if (!ModelState.IsValid)  
  8.           {  
  9.               return BadRequest(ModelState);  
  10.           }  
  12.           var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };  
  14.           IdentityResult result = await UserManager.CreateAsync(user, model.Password);  
  16.           if (result.Succeeded)  
  17.           {  
  18.               tbl_Users obj = new tbl_Users();  
  19.               obj.Active = false;  
  20.               obj.FirstName = model.FirstName;  
  21.               obj.LastName = model.LastName;  
  22.               obj.Email = model.Email;  
  23.               obj.UserId = user.Id;  
  26.               DefEntity.tbl_Users.Add(obj);  
  27.              if(DefEntity.SaveChanges()==1)  
  28.               {  
  29.                   dict.Add("Success""Data Saved Successfully.");  
  31.                   return Ok(dict);  
  32.               }  
  33.              else  
  34.               {  
  37.                   return Content(HttpStatusCode.BadRequest, "User Details not Saved.");  
  38.               }  
  41.           }  
  42.           else  
  43.           {  
  44.               return GetErrorResult(result);  
  46.           }  
  49.       }  
Compress the Result of Web API

Web API compression is very important to improve ASP.NET Web API performance. In the Web, the data transfers through the network in packages (data packets), increasing the size of the data package, which will increase the size as well as increase the response time of the Web API. Thus, reducing the data packet size improves the load performance of Web API.

By compressing the API Response, we have the following two advantages.
  • Data size will be reduced
  • Response time will increase (increasing the speed of the communication between the Client and Server.)

    We can compress web API through coading and through some setting in IIS.I have described the compression of Web API using coading in the following  Links.
  • Similarly, we can enable IIS compression by checking Dynamic Content Compression module.
    So in this way we can compress the web API Response for achieving performance.
Using Caching to Improve Performance

Caching is a technique of storing frequently used data or information in a local memory, for a certain time period. So, next time, when the client requests the same information, instead of retrieving the information from the database, it will give the information from the local memory. The main advantage of caching is that it improves the performance by reducing the processing burden. We have several ways to implement Caching in web api .Here in the below link i have described one way to implement Caching.
Using High speed JSON Serializer

We frequently use JSON instead of XML for exchanging data between the service provider and the service clients. Primarily, we use this because JSON is light-weight.

In .NET, there are lots of serializers. The most popular is Json.NET which was chosen by Microsoft to be the default JSON serializer for Web API. Json.NET is great because it is fast, robust, and configurable.

There are several serializers which are faster than  Json.Net .Some of them are mentioned below.
We can see that the Protobuf-Net and JIL are very fast serializers, so if we can implement these in place of then it will obviously  improve the performance. Protocol Buffers, or Protobuf , is Google’s official serializer. To use JIL serializer in .Net i have written an article you can check this in the below link.
Create Proper DataBase Structure

To improve any application performance  we should give focus on database structure. I can say that the database structure plays an important role in improving performance.These are few notes we should check while working on database.
  • Try to make Normalized tables structure.
  • Provide proper Indexing to all table so that searching result will be easy from the table.
  • Relate all the interrelated table with Foreign Key and Primary Key.

    I think we must follow at least these 3  rules while creating database Structure for improving performance.
Try TO Validate Certain Properties From Client Side

It is very good to validate certain model properties from Client Side rather then Server side. Once we put invalidated data without client side validation then it will go to the server and check if it is valid data or not. If it is not valid data then it will give error from server. So here we can check the round trip using client side validation. So it will be good if we can do the validation with what ever possible from client side like (Mobile devices,Web sites etc).

Mobile Client

So, I think if we focus on the above discussed points, we can somehow increase Web API performance .If you have any points regarding the performance, please comment below so that I can update that in this article.