Detecting when Phoenix.Channel.Server is starting/restarting

I have a chat phoenix channel that when a socket connect or disconnect, I set this on my postgres database (update users set online = true/false where id = ?)

How can I monitor Channel server to set all users on database to offline when it is starting (due a crash, server offline, etc) before accepts socket connects again?

thanks!

1 Like

Is there any reason why You don’t want to use Presence for this?

Otherwise a simple solution would be to store this inside ETS table, and when server goes down, table is reset too.

I use Presence.

But rest of my application need to know who is online in database queries level.

For example, when a user connect to chat, I sent a list of friends online,

with database:
=> select users that is friend and online --> result a list of 100 users

without
=> select users that is friend --> result a list of 1000 users
=> find who from this 1000 friends is online using Presence.list (another 10k random users)
=> Repeat this to every connected socket

Ok I see your use case better.

It seemed strange to use a persistant storage for volatil information.

Still, I would rather take a list of ids from Presence.list, and then only query users where id in […]

Maybe you can have a start script that does an update like this

UPDATE users SET online=false;

Yes, I know that is a volatil data on database…

But I have more or less 10k online users… so my selects will be:
select * from users where is_friend and id in (10k ids send through network to database many times per second).

My presence (a using my impl of Tracker) is sync online/offline, my question is when all server is down and come back, or presence crash … where is the better place do monitor and reset this database info?

basically, what I want is:

  • All sockets crash/close by any circumstance ? So, I want cleanup database before reconnect they all.

see if something like in this article can’t get you closer to a solution using Presence with no DB…

if you trap_exit in the channel you should be able to catch all the crashes/proper shutdowns - however for the catastrophic failures (eg pulled power plug) you will be needing a solution on startup (in the application callback module - but what about distributed deployment?) - but try and see if the article doesn’t work for you - I smell that what you are trying to do with the DB might be a bit of an anti-pattern perhaps, but let’s see…

1 Like

Hi @maxguzenski how did you solve this problem. I have similar problem. Please help me if you did.

If you mean running DB operations on app startup, this post has a nice summary of two methods you may use. Using the Task module seems to be the easiest.