Erlang : gen_server - reply to two clients

415 Views Asked by At

As a newbie, writing a toy matching (trading) engine using gen_server.

Once a trade/match occurs there is need to notify both the clients.

Documentation says that :

reply(Client, Reply) -> Result

Types:

Client - see below
Reply = term()
Result = term()

This function can be used by a gen_server to explicitly send a reply to a client that called call/2,3 or multi_call/2,3,4, when the reply cannot be defined in the return value of Module:handle_call/3.

Client must be the From argument provided to the callback function. Reply is an arbitrary term, which will be given back to the client as the return value of call/2,3 or multi_call/2,3,4.

The return value Result is not further defined, and should always be ignored.

Given the above how is it possible to send notification to the other client.

SAMPLE SEQUENCE OF ACTIONS

   C1 -> Place order  IBM,BUY,100,10.55
   Server -> Ack C1 for order
   C2 -> Place order  IBM,SELL,100,10.55
      Server -> Ack C2 for order
             -> Trade notification to C2
             -> Trade notification to C1 %% Can I use gen_server:reply() 
                                         %% If yes - How ?
1

There are 1 best solutions below

2
Lol4t0 On

Well, you can't. Your ACK is already a reply. And only single reply is acceptable by gen_server:call contract. I mean, gen_server:call will only wait for one reply.

Generally gen_server:reply can be implemented like

reply({Pid, Ref}, Result) ->
    Pid ! {Ref, Result}.

That means that if you try sending multiple replies, you just get some weired messages in the message box of the caller process.

Proposal

Instead, I believe, you should send associate every trade with some reference, and send message to the caller with that reference CX_Ref during the ACK procedure. Then, when you have to send a notification, you just emit message {C1_Ref, Payload} to C1 and {C2_Ref, Payload} to C2.

Also you may want to introduce some monitoring to handle broker crashes.