@@ -407,8 +407,7 @@ defmodule Tortoise311.Connection do
407407 # Apply a short delay before connecting to limit the max rate of reconnects
408408 # if the GenServer crashes. The delay is jittered by 50% of its value. The
409409 # default is 1 second.
410- delay = Keyword . get ( state . opts , :first_connect_delay , 1000 )
411- delay_with_jitter = round ( delay * ( 1.0 + ( :rand . uniform ( ) - 0.5 ) ) )
410+ delay_with_jitter = first_connect_delay_with_jitter ( state )
412411
413412 Process . send_after ( self ( ) , :connect , delay_with_jitter )
414413
@@ -529,8 +528,15 @@ defmodule Tortoise311.Connection do
529528 { :noreply , % State { state | status: status } }
530529
531530 :down ->
532- Logger . info ( "[Tortoise311] Connection went down. Reconnecting." )
533- send ( self ( ) , :connect )
531+ # Try to reconnect after the same jittered delay as for a first connect
532+ # This should help avoid excessive numbers of connects when network access is flapping
533+ delay_with_jitter = first_connect_delay_with_jitter ( state )
534+
535+ Logger . info (
536+ "[Tortoise311] Connection went down. Reconnecting after #{ delay_with_jitter } ."
537+ )
538+
539+ Process . send_after ( self ( ) , :connect , delay_with_jitter )
534540 { :noreply , % State { state | status: status } }
535541 end
536542 end
@@ -590,6 +596,12 @@ defmodule Tortoise311.Connection do
590596 end
591597
592598 # Helpers
599+
600+ defp first_connect_delay_with_jitter ( state ) do
601+ delay = Keyword . get ( state . opts , :first_connect_delay , 1000 )
602+ round ( delay * ( 1.0 + ( :rand . uniform ( ) - 0.5 ) ) )
603+ end
604+
593605 defp handle_suback_result ( % { :error => [ ] } = results , % State { } = state ) do
594606 subscriptions = Enum . into ( results [ :ok ] , state . subscriptions )
595607 { :ok , % State { state | subscriptions: subscriptions } }
0 commit comments