Can LiveView sockets be used for caching data?

Let’s say I have a single-page LiveView app with many users - each user having name, id, avatar link, score, etc - and these user details might need to be shown several hundred times (e.g. each time a comment is viewed, the user details are displayed next to the comment), would it be appropriate to gather the details from the database and store them in the socket, so the next time that user’s details are requested within the same session, it can be fetched from the socket instead of another DB query? If not, what would be the recommended way to handle this?

I’m not actually familiar with LiveView yet, but wouldn’t one of the issues here be that you should at least have a way to tell if the data you’re keeping in the socket has changed? Names, scores, etc. may change, so you’re going to want to do a DB query at some point anyway.

if you’re only in a single liveview, i don’t see why not.
it becomes a problem when you are navigating between different liveviews, as the socket’s assigns will be reset.

If you are staying within the same LiveView, then those would be in the assigns, so you wouldn’t be fetching from the db for every comment. You’d be finding the user details from a preloaded map with, say, the user’s ID or name as the key.

If a new user adds a comment, the assigns would be updated by the event, which would update the message list and the map of users, so you only had to pull one user from the db to add to the map. If an existing user adds a comment, the map doesn’t need to change, only the list of comments.

If you are talking about between LiveViews, then you probably want some sort of global caching mechanism separate from LiveView, such that it can be shared across LV’s or Dead Views. If this is the case, take a look at something like Cachex (cachex | Hex). Cachex will allow you to cache the user record with a TTL and a fallback function. If you get a cache miss, the callback is called and the cache entry rehydrated/created for the TTL timespan. However you want to be careful what you cache. If the ‘score’ changes, the cached value will not be updated until a rehydration event unless you programmatically change or expire it in the cache. It’s all about trade-offs.

If you need to keep the score displayed with the comment, then the LV could pull the list of users into the map and then subscribe to changes on the user records that are in the map. That way if the user changes outside of the LV, an event is pushed to the LV, updating the map, which triggers LV to push the new assign up. In this way, you are not making any more db queries because the ‘user_updated’ event could provide the new state of the user in its payload.

neat, i didn’t know about Cachex. been writing my own small Agent to cache info