vertti

vertti

Channels - Where to store state?

I’m building a sort of highly customized chat application with Phoenix, with some functionality similar with XMPP MUC.

Now, I have both persistent as well as transient state for both, users and channels. While the persistent data is comfortably saved in Ecto/pg, my problem is the transient state. Particularly for the channels, as user-specific transient state can be stored in socket.assigns.

Where to store channel-specific transient state in Phoenix?

For example, each channel has a quiet mode. With quiet mode on, users below certain rank cannot send messages to the channel (=topic in Phoenix slang).

Currently, my approach is to have a table in mnesia which holds all transient data for each channel. However, I don’t feel it’s quite the right approach to query mnesia every single time any user sends a message to check if quiet mode is on. I understand mnesia queries are cheap, but I was thinking if there’s a more sort of Phoenix way to handle this. I guess the most ideal way would be to carry around a channel-specific attribute, much like socket.assigns is.

Moreover, some parts of the channel-specific transient state have an expiry time, meaning that after a period of time they need to be removed from the state. What’s the best approach to handle this - should I spin up another process just to monitor them and when the expiry time hits, remove them from the state in mnesia?

Most Liked

sasajuric

sasajuric

Author of Elixir In Action

It’s a bit hard to recommend the concrete approach, because the description is quite vague, but I’ll give it a try :slight_smile:

To avoid ambiguity with the term channel, I’ll use the term topic instead.

My first take on this would be to use a separate GenServer for each topic. You could hold all the transient data of the topic in that server. The server would also need to keep track of whether it’s in the quite mode. So now, whenever someone wants to send a message to the topic, they need to do it through the corresponding server. Since the server knows about its mode, it can easily decide whether to send the message or not.

Adding expiry logic can now be fairly simple with the help of :timer.send_interval or Process.send_after which would be invoked in the topic server. Either approach will result in some message sent to the server, which you’d need to handle in the corresponding handle_info and remove expired items.

This approach is very consistent, and when done properly, you’ll have no race conditions or strange behaviour. However, the topic server might turn out to be a bottleneck if you have frequent activity on a topic (frequent messages, mode changes, or other state changes). In that case, you could consider using an ETS table. ETS tables can boost your performance significantly, but they are appropriate only for some situations, so you need to think it through. In some cases a hybrid approach is needed, where all the writes are serialized through the server process, while reads are performed directly from the table.

If you go for ETS tables, and want to expire items, you could look into some of the caching libraries, such as CachEx, or my own con_cache. Cachex has more features and higher activity, so as the author of con_cache, I’d myself recommend looking into Cachex first.

If the transient state is really simple, then I’d consider ETS from the start. For example, if we only need to deal with the quiet mode, then I’d just have one ETS table where I’d store that info for each topic.

In more complex cases, I’d start with GenServer and do some testing to see if it can handle the desired load.

Again, the problem is vaguely defined, so it’s hard to precisely say which of the two would be a more suitable choice in this particular case.

vertti

vertti

Yes I understand I didn’t specify the domain very accurately here, thanks for giving your input nevertheless! It’s actually very interesting building a sort of modern administrated Multi-User Chat on Elixir/Phoenix, without the headaches of XMPP.

The nature of my application is:

  • topics are set up (=transient state established) whenever a user subscribes to it as the first user
  • a topic dies when the last user leaves it (=transient state is wiped clean)
  • lots of topics are born and die constantly at a high frequency
  • some topics will be massive = having tons of users subscribed to them, actively sending messages

The transient state each topic has:

  • title - changes rarely
  • member privileges (VIP etc.) - currently this is stored in socket.assigns, which feels like the best approach
  • keyword list - a list of strings which changes constantly based on user messages. These will each have an expiry time, and I believe the birth & expiry logic will get very complex as the app evolves
  • quiet mode (boolean) - will change rarely but needs to be checked on just about every message sent
  • message history - a list of the past (max) 100 messages or so. I want to avoid saving this persistently for now.

So my trouble has been trying to decide whether to make one sort of global state tree (like :mnesia) or whether to prefer more local approaches for each topic.

Your GenServer approach was also my first thought, but I read somewhere that in big topics (lots of subscribers) the GenServer could become the bottleneck, as it is just one process. Now I’m thinking to use a GenServer for the keyword list and maybe for the message history, and ETS / CachEx or your con_cache for the rest.

By the way, is there any reason not to prefer :mnesia over ETS? From what I understand, if I use the transactions :mnesia could be a more safe choice, although it does carry some performance penalty. However, that way, I wouldn’t need to serialize the writes through a channel specific GenServer, but I could still perform fast dirty_reads (if that makes sense).

dom

dom

Honestly the way you’re doing it sounds totally reasonable. Queries to ram or disc copy mnesia tables go through ETS which is fast. In fact I think pg2 phoenix pubsub hits ETS a couple times on every broadcast anyway.

I have a process like you suggest to expire keys, although it’s for postgresql rather than mnesia, and it works great. It doesn’t get much load anyway so I never bothered optimizing or sharding its work.

Where Next?

Popular in Questions Top

9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
PeterCarter
There are pre-rolled solutions for other frameworks that do work. However, Phoenix does not seem to have these. Have people had good expe...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement