user2924127
user2924127

Reputation: 6252

Store views using redis

I have an idea to store view counts for posts on my site, but am having trouble which methods to use and how to design it. My users post many small posts so there will be a lot of unique posts

My requirements are the following:

The flow pseudocode:

//Page view comes to server, lets add the unique postId. 

//Using SADD because it will not insert a key that already exists. Not sure of the difference between sadd and pfadd?
sadd "post:tracking", @post.id

//Add the unique user who viewed this page
sadd "post:#{@post.id}:uniques", @userId

I then run a cronjob which will do the following:

//Run this every 30 minutes
loop through smembers(post:tracking).For each post do{
      //Get number of views for this post:
        var cnt = SCARD("post:@postId:uniques")
       //post to database new count
}

Every 30 minutes it will loop through all the sets (posts) and get the cardinality(count) of the members in that set and update the Mysql database. There is one problem here and that is I am not distinguishing between new posts (not older than 1 week) and older posts (older than 1 week). In my example the time the posts were created is not included because I am not sure where to store this information and this is what I am looking for help with. I am looking at making this more efficient.

Upvotes: 1

Views: 541

Answers (1)

Chris Tanner
Chris Tanner

Reputation: 1660

Have you looked at hyperloglogs?. They store unique things (viewers) very efficiently, with pretty good accuracy (around 1%). You could leave them running and pull stats from them every hour/day/week to get overall viewer figures.

Upvotes: 1

Related Questions