@@ -590,24 +590,32 @@ export async function initNetwork(
590590 return ;
591591 }
592592
593- // Re-check connection limit after dial completes to prevent race conditions
594- // Multiple concurrent dials could all pass the initial check, then all add channels
595- try {
596- checkConnectionLimit ( ) ;
597- } catch {
598- // Connection limit reached - close the dialed channel and queue the message
599- logger . log (
600- `${ targetPeerId } :: connection limit reached after dial, queueing message` ,
601- ) ;
602- // Explicitly close the channel to release network resources
603- await connectionFactory . closeChannel ( channel , targetPeerId ) ;
604- queue . enqueue ( message ) ;
605- // Start reconnection to retry later when limit might free up
606- handleConnectionLoss ( targetPeerId ) ;
607- return ;
608- }
593+ // Check if a concurrent call already registered a channel for this peer
594+ // (dialIdempotent may return the same channel due to deduplication)
595+ const existingChannel = channels . get ( targetPeerId ) ;
596+ if ( existingChannel ) {
597+ // Another concurrent call already registered the channel, use it
598+ channel = existingChannel ;
599+ } else {
600+ // Re-check connection limit after dial completes to prevent race conditions
601+ // Multiple concurrent dials could all pass the initial check, then all add channels
602+ try {
603+ checkConnectionLimit ( ) ;
604+ } catch {
605+ // Connection limit reached - close the dialed channel and queue the message
606+ logger . log (
607+ `${ targetPeerId } :: connection limit reached after dial, queueing message` ,
608+ ) ;
609+ // Explicitly close the channel to release network resources
610+ await connectionFactory . closeChannel ( channel , targetPeerId ) ;
611+ queue . enqueue ( message ) ;
612+ // Start reconnection to retry later when limit might free up
613+ handleConnectionLoss ( targetPeerId ) ;
614+ return ;
615+ }
609616
610- registerChannel ( targetPeerId , channel ) ;
617+ registerChannel ( targetPeerId , channel ) ;
618+ }
611619 } catch ( problem ) {
612620 outputError ( targetPeerId , `opening connection` , problem ) ;
613621 handleConnectionLoss ( targetPeerId ) ;
0 commit comments