Video in progress

While writing a large response to a non-blocking channel, `write()` wrote only part of the bytes. How do you handle this correctly?

You keep the remaining bytes in the connection's outgoing queue and turn on OP_WRITE. When the channel is ready to write again, you continue, and when the queue is empty you turn OP_WRITE off, otherwise the selector spins idle.

📖 Answer

A non-blocking write writes as much as fits in the socket's kernel buffer and returns right away. If the client reads slowly (a mobile network), the buffer fills up and write returns 0. Spinning it in a while (buf.hasRemaining()) ch.write(buf) loop means putting the event loop into a busy spin.

The correct scheme:

void send(SelectionKey key, ByteBuffer data) throws IOException {
    Connection conn = (Connection) key.attachment();
    conn.outbox.add(data);
    flush(key);
}

void flush(SelectionKey key) throws IOException {
    Connection conn = (Connection) key.attachment();
    SocketChannel ch = (SocketChannel) key.channel();
    while (!conn.outbox.isEmpty()) {
        ByteBuffer head = conn.outbox.peek();
        ch.write(head);
        if (head.hasRemaining()) {           // the kernel buffer is full
            key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
            return;
        }
        conn.outbox.poll();
    }
    key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
}

Leaving OP_WRITE on all the time is a mistake: the socket is almost always ready to write, the selector returns immediately every time, and the CPU burns.

This raises the backpressure question. If outbox is unbounded, a single slow client can fill the server's heap. So you need a limit: if the queue grows past some size, you stop reading from that connection (turn off OP_READ) or drop the connection. In Netty the ready-made form of this is Channel.isWritable() and the WRITE_BUFFER_WATER_MARK setting.

In an interview I want to hear these three things: a partial write is a normal case, OP_WRITE only when needed, and a bound on the queue.