class Nexaas::QueueTime::Middleware

This middleware calculates the time a request has been waiting in the queue before being served by the application server.

It requires the header `X_REQUEST_START`. This header contains the timestamp of when the request first apperead in the stack. This header is usually set by a LoadBalancer, Reverse Proxy or Router.

The format of the header must match: `t=TIMESTAMP`, where TIMESTAMP is the unix timestamp. This format is supported by APMs such as New Relic and Scout

Constants

HEADER_FORMAT_PATTERN
METRIC_NAME

Public Class Methods

new(app) click to toggle source
# File lib/nexaas/queue_time/middleware.rb, line 28
def initialize(app)
  @app = app
end

Public Instance Methods

call(env) click to toggle source
# File lib/nexaas/queue_time/middleware.rb, line 32
def call(env)
  request_start_header = env['HTTP_X_REQUEST_START']
  if request_start_header && request_start_header =~ HEADER_FORMAT_PATTERN
    left_queue_at = Time.now.to_f
    metric = calculate_queue_time_in_ms(left_queue_at, request_start_header)
    DogStatsd.timing(METRIC_NAME, metric.to_i, sample_rate: 1)
  end

  @app.call(env)
end

Private Instance Methods

calculate_queue_time_in_ms(left_queue_at, request_start_header) click to toggle source
# File lib/nexaas/queue_time/middleware.rb, line 45
def calculate_queue_time_in_ms(left_queue_at, request_start_header)
  entered_queue_at = extract_timestamp(request_start_header)
  (left_queue_at - entered_queue_at.to_f) * 1000
end
extract_timestamp(entered_queue) click to toggle source
# File lib/nexaas/queue_time/middleware.rb, line 50
def extract_timestamp(entered_queue)
  entered_queue.delete('t=')
end