Single-Socket Channel

Maintain the order of the requests sent to a server by using a single TCP connection.

Problem

When using Leader and Followers , we need to ensure that messages between the leader and each follower are kept in order, with a retry mechanism for any lost messages. We need to do this while keeping the cost of new connections low, so that opening connections doesn’t increase the system’s latency.

Solution

Fortunately, the long-used and widely available TCP protocol provides all these necessary characteristics. We can get what we need by ensuring all communication between a follower and its leader goes through a single-socket channel ( Figure 30.1 ). The follower then serializes the updates from the leader using a Singular Update Queue .

Images

Figure 30.1 Single-socket channel

Once a connection to a node is open, the node never closes it and continuously reads it for new requests. Nodes use a dedicated thread per connection to read and write requests. A thread per connection isn’t needed if nonblocking-IO is used.

Here’s a simple thread-based implementation:

Click here to view code image

class SocketHandlerThread...

  @Override
  public void run() {
      isRunning = true;
      try {
          //Continues to read/write to the socket connection till it is closed.
          while (isRunning) {
              handleRequest();
          }
      } catch (Exception e) {
          getLogger().debug(e);
          closeClient(this);
      }
  }

  private void handleRequest() {
      RequestOrResponse request = clientConnection.readRequest();
      server.accept(new Message<>(request,
                                  request.getRequestId()
      ), clientConnection);
  }

  public void closeConnection() {
      clientConnection.close();
  }

The node reads requests and submits them to a Singular Update Queue for processing. Once the node has processed the request, it writes the response back to the socket.

Whenever a node establishes a communication, it opens a single-socket connection that’s used for all requests with the other party.

Click here to view code image

class SingleSocketChannel...

  public class SingleSocketChannel implements Closeable {
      final InetAddressAndPort address;
      final int heartbeatIntervalMs;
      private Socket clientSocket;
      private final OutputStream socketOutputStream;
      private final InputStream inputStream;

      public SingleSocketChannel(InetAddressAndPort address,
                                 int heartbeatIntervalMs) throws IOException {
          this.address = address;
          this.heartbeatIntervalMs = heartbeatIntervalMs;
          clientSocket = new Socket();
          clientSocket
                  .connect(new InetSocketAddress(address.getAddress(),
                          address.getPort()), heartbeatIntervalMs);
          //set socket read timeout to be more than heartbeat.
          clientSocket.setSoTimeout(heartbeatIntervalMs * 10);
          socketOutputStream = clientSocket.getOutputStream();
          inputStream = clientSocket.getInputStream();
      }

      public RequestOrResponse blockingSend(RequestOrResponse request)
              throws IOException {

          writeRequest(request);
          var responseBytes = readResponse();
          return deserialize(responseBytes);
      }

      private void writeRequest(RequestOrResponse request) throws IOException {
          var dataStream = new DataOutputStream(socketOutputStream);
          var messageBytes = serialize(request);
          dataStream.writeInt(messageBytes.length);
          dataStream.write(messageBytes);
      }

It’s important to keep a timeout on the connection so it doesn’t block indefinitely in case of errors. We use HeartBeat to periodically send requests over the socket channel to keep it alive. This timeout is generally kept as a multiple of the heartbeat interval to allow for network round trip time and some possible network delays. It’s reasonable to set the connection timeout at, say, 10 times the heartbeat interval.

Click here to view code image

class SocketListener...

  private void setReadTimeout(Socket clientSocket) throws SocketException {
      clientSocket.setSoTimeout(config.getHeartBeatIntervalMs() * 10);
  }

Sending requests over a single channel can create problems with head-of-line blocking . To avoid this, we can use a Request Pipeline .

Examples

  • ZooKeeper uses a single-socket channel 106 and a thread per follower to do all the communication.

    1. https://zookeeper.apache.org/doc/r3.4.13/zookeeperInternals.html
  • Kafka uses a single-socket channel between follower and leader partitions to replicate messages.

  • The reference implementation of the Raft consensus algorithm, LogCabin, uses single-socket channel to communicate between the leader and the followers.