How to detect slow responses in Umbraco API

Unearth slow responses in Umbraco v8 API using ActionFilters. Dive into a step-by-step guide to set up performance tracking and enhance your site's speed.

Introduction

In today's digital landscape, performance is paramount.

When working with Umbraco API, detecting slow responses can provide insights to boost the speed and efficiency of your site.

This guide unveils a straightforward method using ActionFilters, assisting developers in pinpointing performance bottlenecks and streamlining integration.

Why Address Slow Responses?

  • Spot delays: Quickly identify and rectify slow responses from the Umbraco API.
  • Efficient benchmarking: Apply a fuss-free micro-benchmark technique for instant results.
  • Pinpoint bottlenecks: Zone in on areas in Umbraco CMS that can benefit from performance optimization.
  • Solve integration glitches: Ensure smoother integration by fixing potential issues.

Understanding the Concept

At the heart of this technique is a custom class that extends the ActionFilterAttribute, named UmbracoApiPerformanceTrackingAttribute.

The idea is to intercept the action's events - both when it begins and when it ends - and measure the elapsed time.

If this time exceeds our set benchmark, it indicates a slow response, which we log for in-depth analysis.

public sealed class UmbracoApiPerformanceTrackingAttribute : ActionFilterAttribute
{
   public override void OnActionExecuting(HttpActionContext actionContext)
   {
      //We start measuring the request

      base.OnActionExecuting(actionContext);
   }

   public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
   {
      //We finish the measurement and log the information when the request is slow

      return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
   }
}

Implementing the API Filter

For our filter to function effectively, we'll integrate specific components:

  • Stopwatch: Enables precise time measurement between the start and end of actions.
  • HttpContext.Current.Items: Useful for temporarily storing the Stopwatch.
  • Logger: Essential for recording details of slow requests.
  • Configurable parameters: ProfilingModeEnabled and SlowResponseMinTimeInMilliseconds.

Here, ProfilingModeEnabled is a switch for our profiler, while SlowResponseMinTimeInMilliseconds establishes our threshold for a 'slow' request.

public sealed class UmbracoApiPerformanceTrackingAttribute : ActionFilterAttribute
{
   private const string StopWatchCacheKey = "UmbracoPerformanceTracking_Stopwatch";

   public override void OnActionExecuting(HttpActionContext actionContext)
   {
      if (AppConfigProvider.ProfilingModeEnabled)
      {
         var stopwatch = Stopwatch.StartNew();

         HttpContext.Current.Items[StopWatchCacheKey] = stopwatch;
      }

      base.OnActionExecuting(actionContext);
   }

   public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
   {
      if (AppConfigProvider.ProfilingModeEnabled)
      {
         Stopwatch stopwatch = (Stopwatch)HttpContext.Current.Items[StopWatchCacheKey];

         stopwatch.Stop();

         if (stopwatch.ElapsedMilliseconds >= AppConfigProvider.SlowResponseMinTimeInMilliseconds)
         {   
            Current.Logger.Warn(typeof(UmbracoCustomLoggingAttribute), $"SLOW RESPONSE (took more than {AppConfigProvider.SlowResponseMinTimeInMilliseconds}): {stopwatch.ElapsedMilliseconds} [ms] - {actionExecutedContext.Request.Method} {actionExecutedContext.Request.RequestUri}");
         }
      }

      return base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
   }
}

Applying the Filter

After crafting the attribute, it's time to implement it.

Decorate your UmbracoApiController with the new filter to monitor its performance.

The beauty of this filter lies in its adaptability.

You can either apply it to the entire controller or specific methods, allowing you the freedom to track performance as broadly or as narrowly as you wish.

[UmbracoApiPerformanceTracking]
public class SlowUmbracoApiController : UmbracoApiController
{
   public IHttpActionResult SlowEndpointA(string id)
   {
      return Json("Hello from Endpoint A");
   }

   public IHttpActionResult SlowEndpointB(string id)
   {
      return Json("Hello from Endpoint B");
   }
}

Optimizing Logging for Production

A word of advice for those deploying in a production environment: optimize your logging settings.

Setting an appropriate logging level not only aids in performance but also ensures the logs are clutter-free.

With Umbraco 8, you can effortlessly configure logs using the Serilog library.

To set the logging level to “Warning” and above with Serilog you need to:

  • Go to config directory
  • Find serilog.config file and open the configuration file
  • Go to <appSettings> section
  • Set “serilog:minimum-level” value as “Warning” (serilog supports many log levels such as Verbose, Debug, Information, Warning, Error, Fatal)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <!-- VALID Values: Verbose, Debug, Information, Warning, Error, Fatal -->
        <add key="serilog:minimum-level" value="Warning" />
    </appSettings>
</configuration>

Conclusion

The journey to performance optimization is more than delving deep into technicalities.

It's about amplifying user satisfaction, ensuring cost-effective operations💰, and considering the impact on our wallets.

We hope this guide provides the tools to track and improve your site's performance effectively.

Need personalized assistance or have questions about optimizing Umbraco API? Reach out to our expert team.

We're here to help you maximize your website's potential!

Further Reading

For those looking to delve deeper into timing requests, I highly recommend the article that inspired this guide - HttpModule For Timing Requests published on the "You've Been Haacked" blog by Phil Haack.

His insights provide a comprehensive understanding of ASP .NET requests timing and configuration, serving as an excellent companion piece to this guide.

And for more insights, tips, and best practices related to Umbraco, don't miss out on the other articles on our blog!

↑ Top ↑