Skip to content

Commit

Permalink
Show how to replicate state immediately during normal shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
nathanl committed Sep 26, 2024
1 parent 16918cf commit 9938a5f
Showing 1 changed file with 36 additions and 1 deletion.
37 changes: 36 additions & 1 deletion lib/phoenix/tracker.ex
Original file line number Diff line number Diff line change
Expand Up @@ -62,13 +62,48 @@ defmodule Phoenix.Tracker do
An optional `handle_info/2` callback may also be invoked to handle
application specific messages within your tracker.
## Special Considerations
## Stability and Performance Considerations
Operations within `handle_diff/2` happen *in the tracker server's context*.
Therefore, blocking operations should be avoided when possible, and offloaded
to a supervised task when required. Also, a crash in the `handle_diff/2` will
crash the tracker server, so operations that may crash the server should be
offloaded with a `Task.Supervisor` spawned process.
## Application Shutdown
A tracker does not automatically replicate its state across the cluster as it
shuts down. This means that your supervision tree shuts down normally - as it
does when you call `System.stop()` or the BEAM receives a `SIGTERM` - any
presences that the local tracker instance has will continue to be seen as
present by other trackers in the cluster until the `:down_period` for the
instance has passed.
To update the cluster more quickly during a normal shutdown, you can add a
GenServer to your supervision tree after the tracker instance (to be started
after it and shut down before it) which calls `graceful_permdown/1` on the
tracker as it shuts down.
defmodule MyApp.TrackerShutdownHandler do
use GenServer
def start_link(opts \\\\ []) do
GenServer.start_link(__MODULE__, %{}, name: __MODULE__)
end
@impl GenServer
def init(init_arg) do
# So that terminate/2 will be called during graceful shutdown
Process.flag(:trap_exit, true)
{:ok, init_arg}
end
@impl GenServer
def terminate(_reason, _state) do
Phoenix.Tracker.graceful_permdown(MyAppWeb.Tracker)
:ok
end
end
"""
use Supervisor
require Logger
Expand Down

0 comments on commit 9938a5f

Please sign in to comment.