Class: Nexaas::QueueTime::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/nexaas/queue_time/middleware.rb

Overview

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

Constant Summary collapse

METRIC_NAME =
'request.queue_time'
HEADER_FORMAT_PATTERN =
/
  ^   # Beginning of line
  t=  #
  \d+ # At least 1 digit
  \.? # Optionally a dot may be used for fractional timestamps
  \d* # Optionally more digits after the dot
  $   # End of line
/x

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware

Returns a new instance of Middleware.



28
29
30
# File 'lib/nexaas/queue_time/middleware.rb', line 28

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# 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