How to execute Ecto query once per session

I’m building a webapp wherein a post can have a view count. Each time /posts/:id route is access, it increments the view field but I want to only increment it when the current session hasn’t visited the /posts/:id route yet.

I’m thinking of using a in-memory storage with ttl like Cachex to store somewhat a composite key of post id and session id or remote ip . Then in the /posts/:id controller action, I will check if the composite key already exists in the cache, if it is then it will not increment the view field otherwise increment it.

I would like to ask for your thoughts or any better solution.

Thank you.

1 Like

The challenge here is deploys and multi-node. Every time you do a deploy or a node has to be rebooted for some reason you’d lose that state. It also gets tricky to sync across multiple nodes.

Given that you’re thinking about a TTL, one option is to store this inside the user session itself. You gotta be careful about space, but you could probably fit a large number of ids in a list in the session before you exceeded the allowed cookie size.

1 Like

Thanks for the advice. Will probably use user session itself instead of in memory store.