Skip to content

Commit 2507928

Browse files
committed
add exponential backoff to socket restarts
1 parent ab4503d commit 2507928

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

lib/chat_bot/socket.ex

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,15 @@ defmodule ChatBot.Socket do
6565
@impl true
6666
@spec terminate(%{reason: WebSockex.close_reason() | WebSockex.close_error()}, SocketState.t()) :: term
6767
def handle_disconnect(%{reason: reason}, state) do
68-
Logger.info("Web socket disconnected. (attempt=#{state.reconnect}, reason=#{inspect(reason)})")
69-
if state.reconnect < 2 do
68+
Logger.warn("Web socket disconnected. (attempt=#{state.reconnect}, reason=#{inspect(reason)})")
69+
if state.reconnect < 4 do
70+
case state.reconnect do
71+
0 -> Process.sleep(1_000)
72+
1 -> Process.sleep(5_000)
73+
2 -> Process.sleep(10_000)
74+
3 -> Process.sleep(20_000)
75+
end
76+
7077
{:reconnect, SocketState.increment_reconnect(state)}
7178
else
7279
{:ok, state}
@@ -76,7 +83,7 @@ defmodule ChatBot.Socket do
7683
@impl true
7784
@spec terminate(WebSockex.close_reason(), SocketState.t()) :: term
7885
def terminate(close_reason, _state) do
79-
Logger.info("Web socket terminated. (reason=#{inspect(close_reason)})")
86+
Logger.error("Web socket terminated. (reason=#{inspect(close_reason)})")
8087
end
8188

8289
defp handle_message(%{"type" => "post", "message" => text, "delay" => delay} = message, state) do

lib/chat_bot/socket_supervisor.ex

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ defmodule ChatBot.SocketSupervisor do
4646
@spec socket_spec(channel :: String.t()) :: any
4747
defp socket_spec(channel) when is_binary(channel) do
4848
{ChatBot.Socket, channel: channel}
49-
|> Supervisor.child_spec(id: socket_id(channel), restart: :transient)
49+
|> Supervisor.child_spec(id: socket_id(channel), restart: :temporary)
5050
end
5151

5252
@spec socket_id(channel :: String.t()) :: {atom, String.t()}

0 commit comments

Comments
 (0)