Server-Timing header in Phoenix/Plug development

Today I have found about Server-Timing header support in browsers. Its purpose is to allow browser developer tools to display some server metrics next to network durations, example:

(Screenshot from Safari, the long blue bar at the bottom)

(Screenshot from Chrome, again, the long blue bar at the bottom)

For now I have created simple plug that exports them:

defmodule Plugs.ServerTimings do
  @behaviour Plug

  import Plug.Conn

  @impl true
  def init(opts) do
    opts
  end

  @impl true
  def call(conn, _) do
    start_time = System.monotonic_time()
    millis = System.convert_time_unit(1, :millisecond, :native)

    register_before_send(conn, fn conn ->
      mono_duration = IO.inspect(System.monotonic_time() - start_time)
      duration = mono_duration / millis

      conn
      |> put_resp_header("server-timing", "plug;dur=#{duration}")
    end)
  end
end

But this is very simple and basic. I tried to use Telemetry together with this, but it worked out rather poorly. Having Telemetry with such would be pretty useful, as it would allow to display other metrics in one timeline:

  • Template rendering time
  • DB queries
  • External services requests
  • Etc.

(Right now the feature set in Server-Timing is rather sparse, as it do not allow for example to state “start” time, which would allow more detailed, tracing-like, information within such view)

What do you think, and what are the possibilities for rendering such informations or even to integrate it into Phoenix/Plug itself.

4 Likes

I have just published library that provides above plug as a independent library

1 Like