[erlang-questions] Stateful gen_servers

David King <>
Sun Oct 7 07:28:39 CEST 2007

>>> I would like to use gen_server to develop a stateful server
>> You could have each client do something like: [...]
> Thanks David for the tip. I think I can use session-id to track  
> state and have the client pass it with each request. Though, I  
> would liked it if somehow that session-id is implicitly passed.

You could have the session implicitly passed by storing it in the  
process dictionary, like this:


[gen_server stuff...]

login() ->

eat_cookies() ->
   case get(my_server_session_id) of
     undefined -> {error,not_logged_in};
     Session ->

eat_cookies(Session) ->

There are two versions of eat_cookies so that you can explicitly  
specify a session if you need to, like if you need to use a session  
from a different process than that created it. Generally speaking,  
using the process dictionary is frowned upon, but this is how you'd  
do it if you wanted to use implicit sessions (see <http:// 

> Also, it would help if you can share a sample application.

Sure, here's an example: <http://www.ketralnis.com/xythoswfs/webui/ 
_xy-4309_1-t_IwEbcrLc> (That link will remain valid for a few days at  

That's a tarball of the tictactoe server. I wrote that as an example  
for someone, so it's not made for easy starting, just easy reading,  
but you probably don't need to start it. The gen_server that you're  
looking for is src/board_server.erl, which is effectively just a  
state-server to keep track of the boards. It also includes  
rudimentary garbage collection for those sessions

Please feel free to comment on the code, I promise I won't be  
offended, and everybody needs a good code-review :) You can read,  
modify and keep it around, but please don't re-distribute it in any  
way. I'll describe it in an article as an example application after  
it's served its offline purpose, and I'll release the code then with  
an actual licence, but this isn't final, and it doesn't have a  
licence or anything, so please don't re-distribute it.

To actually run it, you'd have to compile Erlyweb (it's in the  
tarball in lib/), modify paths in various files (mostly start.sh and  
yaws.conf, but there may be others), run start.sh, and copy-paste the  
lines that it echoes before it starts yaws into the yaws prompt. Then  
connect to <http://localhost:4000/tictactoe>

More information about the erlang-questions mailing list