@@ -165,7 +165,23 @@ def optimal_cfg(metadata: Optional[Dict[str, Any]], topics: list[str], orig: Dic
165165 cfg .setdefault (k , v )
166166
167167 if latency :
168- cfg .pop ("linger.ms" , None )
168+ # For latency-sensitive applications, don't apply linger.ms optimization
169+ # Keep the original value if it exists, otherwise use a default
170+ if "linger.ms" in cfg :
171+ # Get the original linger.ms value if it exists
172+ orig_linger_key = None
173+ if lib_name == "kafka-python" or lib_name == "aiokafka" :
174+ orig_linger_key = "linger_ms"
175+ elif lib_name == "confluent" :
176+ orig_linger_key = "linger.ms"
177+
178+ if orig_linger_key and orig_linger_key in orig :
179+ # Use the original value instead of the optimized one
180+ cfg ["linger.ms" ] = orig [orig_linger_key ]
181+ logger .debug ("Using original linger.ms value ({}) for latency-sensitive application" , orig [orig_linger_key ])
182+ else :
183+ # Remove the optimized value but it will be added back as default later
184+ cfg .pop ("linger.ms" )
169185
170186 # Translate Java-style keys to library-specific keys for comparison
171187 java_keys_to_check = ["batch.size" , "linger.ms" ]
@@ -179,9 +195,17 @@ def optimal_cfg(metadata: Optional[Dict[str, Any]], topics: list[str], orig: Dic
179195 if lib_key in orig and java_key in cfg :
180196 try :
181197 if int (orig [lib_key ]) > int (cfg [java_key ]):
198+ logger .debug ("Keeping original {} value ({}) as it's larger than optimized ({})" , java_key , orig [lib_key ], cfg [java_key ])
182199 cfg [java_key ] = orig [lib_key ]
183200 except Exception :
184201 pass
185202
203+ # Ensure all core optimization parameters are present in the final config
204+ # But don't add linger.ms back if it was removed for latency sensitivity
205+ for k , v in _DEFAULTS .items ():
206+ if k not in cfg :
207+ if not (latency and k == "linger.ms" ):
208+ cfg [k ] = v
209+
186210 # Translate Java-style keys to library-specific keys
187211 return translate_java_to_lib (cfg , lib_name ), warning_msg
0 commit comments