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