class ViewCounter
def bump(snip_id)
Redis.current.incr("snip:views:#{snip_id}")
end
end
class ViewCounterFlushJob < ApplicationJob
queue_as :maintenance
def perform
keys = Redis.current.keys('snip:views:*')
keys.each do |key|
snip_id = key.split(':').last.to_i
delta = Redis.current.get(key).to_i
next if delta.zero?
Snip.where(id: snip_id).update_all("views = views + #{delta}")
Redis.current.del(key)
end
end
end
Sometimes exact counters aren’t worth the write cost. For high-traffic views, track increments in Redis and periodically aggregate into the DB. It’s an operational tradeoff that can dramatically reduce DB pressure.