junrao commented on code in PR #24170:
URL: https://github.com/apache/kafka/pull/24170#discussion_r4570381798


##########
clients/src/main/java/org/apache/kafka/common/network/KafkaChannel.java:
##########
@@ -437,7 +439,20 @@ public long write() throws IOException {
             return 0;
 
         midWrite = true;
-        return send.writeTo(transportLayer);
+        // A ByteBufferSend is written with one call, but SSL writes each of 
its buffers as its own TLS record
+        boolean singleWrite = send.send() instanceof ByteBufferSend && 
!(transportLayer instanceof SslTransportLayer);
+        if (!OperatingSystem.IS_LINUX || singleWrite)
+            return send.writeTo(transportLayer);
+
+        // With TCP_NODELAY off the kernel joins the small parts of a send 
into full segments, and on Linux
+        // turning it back on sends the queued data at once instead of waiting 
for an ACK (see tcp(7)).
+        SocketChannel socketChannel = transportLayer.socketChannel();
+        socketChannel.setOption(StandardSocketOptions.TCP_NODELAY, false);

Review Comment:
   @iatsuk : Thanks for the updated PR and the extensive performance numbers.
   
   For the toggle approach, here is another concern raised by Claude in 
addition to the slight increased CPU.
   
   > 2. It relies on a Linux kernel quirk, and there's no off switch. 
Coalescing without delay depends on enabling TCP_NODELAY flushing queued data 
(tcp(7): "setting this option forces an explicit flush of pending output"). The 
PR checks os.name, not which TCP stack is in use.
   > 
   > Possible exposure: gVisor's netstack and LD_PRELOAD kernel-bypass stacks 
(Onload, VMA) report Linux but have their own TCP stacks. If one doesn't flush 
on enable, the tail of every multi-part response waits for the peer's ACK. That 
could mean up to the delayed-ACK timeout, ~40 ms against a Linux peer, on every 
fetch response. I haven't checked how those stacks behave; it's a risk, not a 
confirmed bug.
   > No escape hatch: an off switch would be a new config, so it would need a 
KIP. KIP-723 already rejected making TCP_NODELAY configurable.
   > 
   
   I am not sure how common it is. However, if we go with the toggle approach, 
my feeling is that we need to add a config to be able to disable it. This will 
require a KIP.
   
   If we can validate that the gathering wrap approach is always better, we can 
go with that without introducing a new config. Claude suggests that we can do 
it more completely at the Send level.
   
   > 1. Open and close a batch around each write
   > 
   > 
   > // TransportLayer: no-ops by default, so plaintext is unchanged
   > default void startWriteBatch() { }
   > default void endWriteBatch() throws IOException { }
   > // KafkaChannel.write()
   > transportLayer.startWriteBatch();
   > try {
   >     // A send can be complete with records still held after a partial 
flush; then only flush them
   >     return send.completed() ? 0 : send.writeTo(transportLayer);
   > } finally {
   >     transportLayer.endWriteBatch();   // flushes the held records
   > }
   > Only KafkaChannel.write opens a batch. The handshake, SASL and close paths 
write to the transport directly, so they keep flushing after every record.
   > 
   > 2. Append records instead of flushing each one
   > Today write(src) (SslTransportLayer.java:723-755) does flush → clear → 
wrap → flip for every record. The clear() requires the buffer to be empty, so 
every record has to be flushed first. In a batch, it should instead append 
behind the records it's holding:
   > 
   > 
   > 
   > private boolean batching;
   > private boolean flushBlocked;   // the last flush could not write 
everything
   > // Makes room for another record. In a batch, it flushes only when there 
is no room.
   > private boolean makeRoomForRecord() throws IOException {
   >     if (!batching || netWriteBuffer.capacity() - 
netWriteBuffer.remaining() < netWriteBufferSize()) {
   >         if (!flush(netWriteBuffer)) {
   >             flushBlocked = true;
   >             return false;
   >         }
   >     }
   >     netWriteBuffer.compact();   // switch to write mode, keeping held 
records in front
   >     return true;
   > }
   > public int write(ByteBuffer src) throws IOException {
   >     ... state checks
   >     int written = 0;
   >     while (src.hasRemaining() && makeRoomForRecord()) {
   >         SSLEngineResult wrapResult = sslEngine.wrap(src, netWriteBuffer);
   >         netWriteBuffer.flip();
   >         ... existing status handling, written += wrapResult.bytesConsumed()
   >     }
   >     if (!batching)
   >         flush(netWriteBuffer);   // today's behavior outside a batch
   >     return written;
   > }
   > In transferFrom, the initial if (!flush(netWriteBuffer)) return 0; (:1033) 
changes in the same way. Outside a batch it stays as is. In a batch it returns 
0 only if flushBlocked is set. File chunks then reach write(fileChannelBuffer) 
and append like everything else.
   > 
   > endWriteBatch() sets batching = false and does flushBlocked = 
!flush(netWriteBuffer). That's the single socket write for the whole batch.
   > 
   > 3. Pending writes and send completion (the subtle part)
   > Every part's completion currently includes "the transport has nothing 
pending":
   > 
   > ByteBufferSend.writeTo records pending = channel.hasPendingWrites(), and 
the send isn't complete while it's set (ByteBufferSend.java:57-63).
   > RecordsSend.writeTo does the same (RecordsSend.java:46-60).
   > MultiRecordsSend.writeTo moves on to the next part only once the current 
one is complete (MultiRecordsSend.java:88-95).
   > SslTransportLayer.hasPendingWrites() is netWriteBuffer.hasRemaining() 
(:227-229).
   > So with a naive batch, the first part would always look pending, because 
its record is being held. MultiRecordsSend would stop after one part, and 
batching would achieve nothing. Two changes fix this:
   > 
   > In a batch, held records don't count as pending:
   > 
   > 
   > public boolean hasPendingWrites() {
   >     return batching ? flushBlocked : netWriteBuffer.hasRemaining();
   > }
   > Parts then complete as soon as their bytes are wrapped. If the socket 
refuses a flush, flushBlocked makes them pending again, so the loop stops. 
That's the correct back-pressure.
   > The whole send completes only once its bytes are flushed. In 
KafkaChannel.maybeCompleteSend (KafkaChannel.java:398-407), add && 
!transportLayer.hasPendingWrites(). After endWriteBatch this is accurate again. 
If the final flush was partial, the send stays incomplete and OP_WRITE stays 
registered. The next write() only flushes, through the send.completed() ? 0 : 
... in section 1, because MultiRecordsSend.writeTo throws if it's called on a 
complete send (:83-84).
   > Without the second change, a send could be reported complete, and its 
connection closed, for example for a CloseConnectionResponse or after an 
authentication failure, while its last records are still in netWriteBuffer.
   > 
   > 4. Buffer size and memory
   > netWriteBuffer currently holds one packet (getPacketBufferSize(), about 
16.7 KB; :119, :881-882). How much more it needs depends on SunJSSE:
   > 
   > If wrap only needs room for the record it produces, many small records fit 
in today's buffer. A wrap that doesn't fit would flush and retry instead of 
growing the buffer, at no extra memory.
   > If wrap returns BUFFER_OVERFLOW unless there's room for a full packet (I 
believe newer JDKs do, but verify), the buffer needs held bytes plus one 
packet, for example 2 × getPacketBufferSize(). That's about 16 KB more per SSL 
connection, roughly 160 MB for 10k connections.
   > A way to avoid the extra memory: share one batch buffer per network 
thread, and copy only what's left after a partial flush into the connection's 
own buffer. That's more code.
   > 
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to