Calculate an approximation of a server response time with Rails and Apache

This post was born from the need of calculating some kind of server response time during a page request. Although this is not perfect, because doesn’t account for the time that the response takes to reach the user, it’s pretty accurate on the server side.

In order to have the request start time I added this header in the Apache configuration server:

RequestHeader append Request-Started "%t"

I didn’t use a simple before_filter because it would have not considered the time spent in rack middlewares, for example.

Now in my action I can count on a request header like this:

Request-Started: t=1460473552166899

Note that this timestamp is in microseconds.

Now in the page view template I can get the total request time doing some simple math:


server_response_time = current_time - time_from_header

def current_time
  Time.now.utc
end

def time_from_header
  Time.at(request.headers['Request-Started'].split("=").last.to_i / 1_000_000).utc
end

Leave a Reply

wpDiscuz