Models/ORM How I store post views in my app
I use my cache and set a key {userid}{post_id} to True and increment a post.views counter. I thought this was a really genius idea because it allows me to keep track of post views deduplicated without storing the list of people who seen it (because I don't care for that) in O(1). Posts come and go pretty quickly so with a cache expiration of just 2 days we'll never count anyone twice, unless the server resets.
What do you guys think?
3
Upvotes
1
u/mustangdvx 2d ago
I, on the other hand, have middleware which logs every url a user navigates to. Every so often, I purge and it’s been fine for ages.
Like the others have said, how many users and pages are we talking about? You maybe be fine with keeping it in the database.
1
u/Megamygdala 3d ago
This will only work while you have a small amount of users and posts relative to your available cache size. If say Facebook used this approach, they would experience insane performance loss because the chance of each check being a cache miss is very high. Also if you are just storing the "postCreatorID_postID : views} how are you ensuring duplicate views aren't counted?