United Kingdom: +44 (0)208 088 8978

Using IServerTiming with F#

Isaac shows us how to make use of the Server Timing browser API in ASP .NET.

We're hiring Software Developers

Click here to find out more

The official Server Timing API defines itself as a specification that allows "a server to communicate performance metrics about the request-response cycle to the user agent". In other words, for our purposes, it enables ASP .NET applications to provide server timing metrics to the web browser (and other clients) through standard HTTP response headers. There are many places where this is useful, including (but not only) for rapid diagnostics during development.

Getting started

The unofficial Lib.AspNetCore.ServerTiming package provides a handy piece of middleware that we can easily use within our Saturn applications:

let app = application {
    use_router myRoutes
    service_config (fun svc -> svc.AddServerTiming())
    app_config (fun app -> app.UseServerTiming())
}

Once you've added the middleware, you can start to use it by resolving the IServerTiming service:

let endpoint next (ctx: HttpContext) =
    let serverTiming = ctx.GetService<IServerTiming>()
    serverTiming.Metrics.Add(ServerTimingMetric("cache", 300, "Cache"))
    serverTiming.Metrics.Add(ServerTimingMetric("sql", 900, "Sql Server"))
    serverTiming.Metrics.Add(ServerTimingMetric("fs", 600, "FileSystem"))
    serverTiming.Metrics.Add(ServerTimingMetric("cpu", 1230, "Total CPU"))
    text "Hello world" next ctx

The SDK also comes with some handy methods for treating timings as IDisposables:

let! sqlResult = task {
    use timer = serverTiming.TimeAction "sql" // when "timer" goes out of scope, the lifetime of that disposable will be recorded
    do! Task.Delay 500
    return "ALFKI"
}

as well as Tasks:

let! readFromFile = task {
    let readingTask = Task.Delay 1500
    do! serverTiming.TimeTask (readingTask, "getStuffFromFileSystem") // the lifetime of the readingTask execution will be used for the timing 
    return "File contents"
}

Once complete, you can see the results of the timings directly in your browser:

Conclusion

Server Timing is a timing feature natively supported in most modern browsers. ASP .NET can participate in this through standard HTTP Headers; the use of the ServerTiming NuGet package makes this even easier to do. You can see the full source code for this sample here. Have fun!