In this episode, we're diving into tracking unique views for Laravel models using Redis, instead of the traditional (and often slow) database approach. First, we talk about why you might not want to store every view directly in your database—especially if you're just logging unique IP addresses. Managing this at scale can get clunky and slow.
Instead, we explore how to use Redis to handle this more efficiently. We start by looking at a simple articles app that has a view count for each article, but instead of incrementing this directly in the database, we set up unique Redis keys per article. You’ll see how using Redis Sets can guarantee uniqueness of views (based on IPs), but also why this might not scale well if you have tons of unique viewers.
Then, we move on to Redis’ HyperLogLog, a super space-efficient, probabilistic data structure. It's not 100% accurate, but it's fast and uses way less memory—great for when you expect a lot of views!
There's a nice terminal walkthrough where we play with the actual Redis commands (SADD
, SCARD
, PFADD
, PFCOUNT
), so you can see firsthand how these tools work. And don't worry, we'll also cover how to sync the view counts back to your database, allowing you to sort articles by popularity in your app.
By the end of this episode, you’ll be clear on the advantages and trade-offs of both methods, and why Redis (especially with HyperLogLog) can be a game-changer for counting unique views.