DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Software Design and Architecture
  3. Microservices
  4. Tracking Bounce Rates for Rails Applications in New Relic Using Redis

Tracking Bounce Rates for Rails Applications in New Relic Using Redis

Leigh Shevchik user avatar by
Leigh Shevchik
·
Jan. 23, 13 · Interview
Like (0)
Save
Tweet
Share
3.41K Views

Join the DZone community and get the full member experience.

Join For Free
this post comes from lee atchison at the new relic blog.

redis logo bounce 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.)



Redis (company) application

Published at DZone with permission of Leigh Shevchik, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Top 5 PHP REST API Frameworks
  • Three SQL Keywords in QuestDB for Finding Missing Data
  • Connecting Your Devs' Work to the Business
  • Handling Automatic ID Generation in PostgreSQL With Node.js and Sequelize

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: