Performance Zone is brought to you in partnership with:

Leigh has been in the technology industry for over 15 years, writing marketing and technical documentation for Sun Microsystems, Wells Fargo, and more. She currently works at New Relic as a Marketing Manager. Leigh is a DZone MVB and is not an employee of DZone and has posted 106 posts at DZone. You can read more from them at their website. View Full User Profile

Tracking Bounce Rates for Rails Applications in New Relic Using Redis

01.23.2013
| 2257 views |
  • submit to reddit
This post comes from Lee Atchison at the New Relic Blog.

Redis logoBounce rates are a key metric for tracking the quality and usefulness of content on your site. By using New Relic to measure your bounce rates over time, you can see how changes to your site — including changes in your site performance — may be impacting your visitors’ first impressions.

It’s pretty simple to use New Relic to track bounce rates for a Rails application. To get started, all you need is a semi-persistent cache like Redis. Here’s how to do it.

Marking Hits by Visitor
Tracking unique visitors is critical for calculating your bounce rate.  To get started, you need to establish a unique identifier for each visitor on your site. For this post, we’ll assume you have a value called visitor_id representing a unique visitor.

Now we need to mark each page request in our Rails app with the visitor ID. The easiest way to do this is by adding a before_filter in the application controller. Here’s an example:

class ApplicationController < ActionController::Base
    before_filter :mark_hit_by_visitor
 
    def mark_hit_by_visitor
        visitor_id=
        record_hit visitor_id
    end
 
end

Tracking Hits in Redis
Here’s where Redis comes in. We’ll use a Redis HASH to keep track of hits to our application. We do this by using the Redis HINCRBY command. Take a look at an implementation of record_hit:

#
# Connect to your Redis instance
#
def redis
    @redis||=Redis.new host: “my_redis_server”
end
 
#
# Record a website hit
#
def record_hit visitor_id
    key=”daily_visitors_#{Date.today.strftime('%Y-%m-%d')}”
    redis.hincrby key,visitor_id,1
    redis.expire key,30*24*60*60 # Expire key after 30 days
end

The Redis HINCRBY command requires three parameters:

* First is the Redis name we use to store the hash. Use a name that contains the day, so you end up generating a new hash each day to keep track of your results by day.

* Second is the hash key. Use visitor_id as the key into the hash.

* Third is the value of the hash. It’s represented by an integer that starts at 0 and is incremented by the specified amount. In this case, we simply want to record a count of hits, so we increment by one.

The Redis EXPIRE command is used to remove keys after they are no longer needed. In this example we’ll be using 30 days.

Aggregation and Reporting
Now you have a hash representing unique site visitors on any give day. To calculate the bound rate, take the number of values in the hash that are equal to one and divide by the total number of values in the hash. Here’s a simple way to do that:

def bounce_rate_for_day the_day=Date.today
    key=”daily_visitors_#{the_day.strftime('%Y-%m-%d')}”
    vals=redis.hvals key
    #
    # Count the number of “1” entries in the vals array.
    # (note that the results are strings)
    #
    num_bounces=vals.count(“1”)
    num_visits=vals.count
    #
    # Return the ratio (as a float). This is the bounce rate
    #
    num_bounces.to_f/num_visits.to_f
end
 
# Get the bounce rate for yesterday:
bounce_rate_for_day(Date.today-1)

Reporting Data to New Relic
Next we need to report this to New Relic. That’s easy to do:

def report_to_newrelic
    # Get yesterday’s bounce rate (most recent complete day)
    bounce_rate=bounce_rate_for_day(Date.today-1)
 
    # Upload it to New Relic
    ::NewRelic::Agent.agent.stats_engine.
            get_stats_no_scope('Custom/Visitor/BounceRate').
            record_data_point(bounce_rate)
end

This routine takes the previous days bounce rate and uploads it to New Relic as a custom metric. The get_stats_no_scope method is a method of the New Relic Ruby agent that records a custom metric. The value Custom/Visitor/BounceRate is a unique name for this metric used within New Relic. (User created custom metrics all begin with the word ‘Custom’.)

Even though this value only changes daily, it’s worth reporting to New Relic as a custom metric regularly. (So we can get nice, useful charts.) When using New Relic, we’re often looking at data over a short period of time (30 minutes) rather than a longer period of time (days.) But we want to make sure the metric data appears during any period of time. This can be easily accomplished in a cron job. Personally, I report data to New Relic once every minute, so I have valid data no matter what time interval I select in the product. A bit overkill, but the cost is minimal.

Creating a Custom Dashboard
Now that data is getting into New Relic, let’s create a chart where we can view it. First, we’ll create a new custom dashboard. From the Dashboards menu, click Create custom dashboard.

Create Custom Dashboard

Enter a name for the new dashboard, choose a layout and click Create.

Create New Custom Dashboard Form

Next we’ll create a new chart by filling in the following information in the chart configuration:

Edit Chart

Make sure to add Custom/Visitor/BounceRate as the Metric, and select Average Value as the Value and To Percentage as the Number Format.

The Results
Once that’s complete, you’ll see a chart that looks like this:

Bounce Rate Chart

The Y-axis is the bounce rate as a percentage of visits. The X-axis is time and will match the specified time interval selected.

We can add other charts to this same page, which will allow us to compare bounce rate to other date about the application that has been collect by New Relic (such as page load latency, error rate, etc.)



Published at DZone with permission of Leigh Shevchik, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)