Stupid Redis Tricks

Starr Horne

Redis, What?

I PostgreSQL

(This isn't a religious war)

Then Why Bother?

But is it web scale?

(I don't care, where's the code?)

Tracking pixels: fun since 1997

#
# To get the event counts for each day
#
#   Redis.current.hgetall("stats:daily:purchase")
#
class LogController < ActionController::Base

  def pixel
    key = "stats:daily:#{ params[:event] }"
    Redis.current.hincrby(key, Date.today.to_s, 1)
    render text: Pixel, content_type: "image/gif"
  end

end
  

Tracking unique users

#
# To get the count for a page:
#
#   Redis.current.scard("stats:uniq:123")
#
class LogController < ActionController::Base

  def log_uniq
    key = "stats:uniq:#{ params[:id] }"
    Redis.current.sadd(key, cookies['session'])
    render :text => ""
  end

end
  

Workers using pub / sub

#
# The worker subscribes to a channel
#
Redis.current.subscribe("mail") do |on|
  on.message do |channel, message|
    send(message)
  end
end

#
# And the main app sends it jobs
#
Redis.current.publish("mail", message.to_json)
  

Votes

#
# To get the top 10 items:
#
#   Redis.current.zrevrange("thumbs_up", 0, 9)
#
class LogController < ActionController::Base
  def thumbs_up
    Redis.current.zincrby("thumbs_up", params[:id], 1)
    render :text => ""
  end
end
  

Data Caching

#
# To cache a json blob for 10 minutes:
#
#   cache("money", 600) { expensive_calculation().to_json }
#
def cache(key, expiry)

  redis = Redis.current

  if cached = redis.get(key)
    return cached
  end

  data = yield

  redis.multi do
    redis.set(key, data)
    redis.expire(key, expiry)
  end

  data
end
  

In Short

Slide Deck @ www.honeybadger.io/blog

/

# k