Performance is a buzzword for APIs. One of the most important and measurable parameters of the API performance is the response time. In this article, we will understand how to add code to measure the response time of an API and then return the response time data to the end client.

What is the need for this?
So, let's take a moment to think why we would ever need such a feature to measure the Response time of an API. Following are some of the points that have been the inspiration for writing code to Capture response time.
You need to define the SLA (Service Level Agreements) for your API with your clients. The clients need to understand how much time the API takes to respond back. The response time data over time can help us decide on an SLA for our API.
Management is interested in reports as to how fast or slow the application is. You need to have data to corroborate your claims. It is worth it to have reports on the performance of the application and to share it with Stakeholders.
The client needs to have the information of the Response time of the API so that they can track how much time is spent on the client and the Server.
You might also have encountered similar requests in your project and it is worthwhile looking at an approach to capture the response time for the API.
Where to add the code?Let's explore a couple of approaches to capture the response time of our API focusing mostly on capturing the time spent in our API. Our objective is to calculate the time elapsed in milliseconds from the time the request is received by the Asp.net core runtime to the time the response is processed and sent back from the Server.
What factors are we ignoring?It's important to understand that this discussion doesn't include the time spent in N/W, Time spent in IIS and Application Pool Startup. If the Application Pool wasn't up and running, then the first request can affect the overall response time of the API. There is an Application Initialization Module which we can make use of but that is out of scope for this article.
First AttemptOne very naive approach to capturing the response time of an API would be to add code to every API method at the start and end and then measure the delta to calculate the response time as shown below.
- // GET api/values/5
- [HttpGet]
- public IActionResult Get() {
- // Start the watch
- var watch = new Stopwatch();
- watch.Start();
- // Your actual Business logic
- // End the watch
- watch.Stop();
- var responseTimeForCompleteRequest = watch.ElapsedMilliseconds;
- }
This code should be able to calculate the time spent in an operation. But this doesn't seem to be the right approach for the following reasons.
- If an API has a lot of operations, then we need to add this code to multiple places which are not good for maintainability.
- This code measures the time spent in the method only, it doesn't measure the time spent on other activities like middleware, filters, Controller selection, action method selection, Model binding etc.
Let's try to improve the above code by centralizing the code in one place so that it is easier to maintain. We need to execute the response time calculation code before and after a method is getting executed. If you have worked with earlier versions of Asp.net Web API, you would be familiar with concepts of Filter. Filters allow you to run code before or after specific stages in the request processing pipeline.
We will implement a filter for calculating the Response time as shown below. We will create a Filter and use the OnActionExecuting to start the timer and then stop the timer in method OnActionExecuted, thus calculating the response time of the API.
- public class ResponseTimeActionFilter: IActionFilter {
- private const string ResponseTimeKey = "ResponseTimeKey";
- public void OnActionExecuting(ActionExecutingContext context) {
- // Start the timer
- context.HttpContext.Items[ResponseTimeKey] = Stopwatch.StartNew();
- }
- public void OnActionExecuted(ActionExecutedContext context) {
- Stopwatch stopwatch = (Stopwatch) context.HttpContext.Items[ResponseTimeKey];
- // Calculate the time elapsed
- var timeElapsed = stopwatch.Elapsed;
- }
- }



EUPROTEIN INCPosted Mar 6, 2020, 11:23 AM
Any updates as to how to use this ResponseTimeMiddleware class and how to integrate? Thanks
Deependra KushwahPosted Jan 31, 2020, 4:15 AM
This is what I have used to get the request time in web API.
Deependra KushwahPosted Jan 31, 2020, 4:15 AM
AppBuilder.Use(async (context, next) => { var watch = new Stopwatch(); watch.Start(); await next(); watch.Stop(); context.Response.Headers.Set("ResponseTime", watch.Elapsed.Seconds.ToString()); );
Jesse SmithPosted Jun 28, 2019, 2:48 PM
Looks interesting, I would like to see an implementation of this as well
Serkan CamurPosted Jun 20, 2019, 1:00 AM
Good article but explain please how to use ResponseTimeMiddleware class and where on?