@Override
        public byte[] encode(int msgType, Routable obj) {
            try {
                var protoMsg = encoderFn.apply(apiClass.cast(obj));
                int protoSize = protoMsg.getSerializedSize();
                // The message payload contains a 4-byte header int which specifies the type of the message
                // that follows. We want to write this header and the subsequence message bytes using a single
                // allocation and without unneeded copying, so we create one array for both purposes and encode
                // directly into it. Aside from the header, this is pretty much a mirror image of what the
                // toByteArray() method on Protobuf message objects already does.
                var buf = new byte[4 + protoSize];
                ByteBuffer.wrap(buf).putInt(msgType); // In network order (default setting)
                var protoStream = CodedOutputStream.newInstance(buf, 4, protoSize);
                protoMsg.writeTo(protoStream); // Writing straight to array, no need to flush
                protoStream.checkNoSpaceLeft();
                return buf;
            } catch (IOException | RuntimeException e) {
                log.severe("Error during Protobuf encoding of message type %s: %s".formatted(apiClass.getSimpleName(), Exceptions.toMessageString(e)));
                log.log(Level.FINE, "Protobuf encode error has exception trace:", e);
                return null;
            }
        }
Implementation of MessageBus message request/response serialization built around Protocol Buffers.
documentapi/src/main/java/com/yahoo/documentapi/messagebus/protocol/RoutableFactories80.java