Server to Server authentication for client - Single threaded Server to Server authentication for client - Single threaded multithreading multithreading

Server to Server authentication for client - Single threaded


Assuming that you have full control of all system:

Assign an ID for each client connection in the server. Then when you need to authenticate the user, include this connection ID in the request from the server to the login server and return without waiting for the reply from the login server.

Some time in the future your server will receive login response from the login server. If the login response contains the client connection ID - use that ID to find a connection from a server to a client and relay that reply back to the client.


Here is how I did it.

Setup

Create a Channel wrapper class, so that you can identify which channel belongs to which client.

public class CustomChannel implements Channel {    private final Channel channel;    private final String clientId;    ...}

Create a custom ChannelMatcher for matching client's channel:

public class CustomChannelMatcher implements ChannelMatcher {    private final String clientId;    public CustomChannelMatcher(String clientId) {        this.clientId = clientId;    }    @Override    public boolean matches(Channel channel) {        if (channel instanceof CustomChannel) {            return clientId.equals(((CustomChannel) channel).getClientId());        }        return false;    }    ...}

Handling Request

In your client handler, use ChannelGroup to keep track of your clients' channels.

ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);...channelGroup.add(new CustomChannel(ctx.channel(), clientId));// send request to another server without blocking

Handling Response

In your server handler, use your CustomChannelMatcher to match the client's channel.

// when the server responds sometimes laterchannelGroup.writeAndFlush(responseMessage,     new CustomChannelMatcher(clientId));

The code above will find a matching client's channel and write the message to it.


You are worried to block an NIO worker thread, but you spin another thread to perform the login. You just used one more thread anyway. So define more threads in your server for http(s) and be done with it. Unless you expect over 100 concurrent logins, there is no issue here.

NIO is way overrated; the OS is great at scheduling threads and context switching, much better than you would in java doing backflips with asyn apis. Waiting threads do not consume CPU.