Build an Elixir Phoenix boilerplate using Presence to track online users. Implement a cluster setup with libcluster so presence information syncs across distributed Erlang nodes automatically when deployed to multiple instances.
Assistant
This is a comprehensive request for building an Elixir Phoenix boilerplate with several key components:
Phoenix Presence to track online users
libcluster for distributed clustering
Automatic syncing of presence across nodes
Multi-instance deployment setup
I'll create a complete boilerplate that includes:
Phoenix project setup
Configuration for clustering
Presence implementation
Web socket handling for real-time updates
Example UI for showing online users
Docker setup for multi-instance deployment
Tests for presence functionality
Let me build this step by step:
Mix project dependencies
Configuration files
Presence module
Channels for real-time communication
Controllers
Frontend components
Docker setup
Documentation
Let me create a comprehensive solution.
Elixir Phoenix Distributed Presence with libcluster
I'll create a complete boilerplate for tracking online users across distributed nodes.
1. Project Setup
bash
mix phx.new presence_tracker --no-ecto --no-mailer
cd presence_tracker
import Config
if config_env() == :prod do
config :presence_tracker, PresenceTrackerWeb.Endpoint,
server: true
end
4. Application Supervision
lib/presence_tracker/application.ex
elixir
defmodule PresenceTracker.Application do
use Application
@impl true
def start(_type, _args) do
children = [
# Start the Telemetry supervisor
PresenceTrackerWeb.Telemetry,
# Start the PubSub system
{Phoenix.PubSub, name: PresenceTracker.PubSub},
# Start libcluster for distributed coordination
{Cluster.Supervisor, [Application.get_env(:libcluster, :topologies), [name: PresenceTracker.Cluster]]},
# Start the Endpoint (http/https)
PresenceTrackerWeb.Endpoint
]
opts = [strategy: :one_for_one, name: PresenceTracker.Supervisor]
Supervisor.start_link(children, opts)
end
@impl true
def config_change(changed, _new, removed) do
PresenceTrackerWeb.Endpoint.config_change(changed, removed)
:ok
end
end
5. Presence Module
lib/presence_tracker/presence.ex
elixir
defmodule PresenceTracker.Presence do
@moduledoc """
Provides presence tracking across distributed nodes.
Uses Phoenix.Presence to track online users in real-time.
"""
use Phoenix.Presence,
otp_app: :presence_tracker,
pubsub_server: PresenceTracker.PubSub
alias PresenceTracker.Presence
@doc """
Track a user's presence on a topic.
## Examples
iex> track_user("lobby", "user123", %{name: "John", avatar: "url"})
{:ok, binary}
"""
def track_user(topic, user_id, user_data) do
metadata = %{
user_id: user_id,
joined_at: System.monotonic_time(:millisecond),
node: node(),
data: user_data
}
track(self(), topic, user_id, metadata)
end
@doc """
Stop tracking a user's presence.
"""
def untrack_user(topic, user_id) do
untrack(self(), topic, user_id)
end
@doc """
Get all users present on a topic.
Returns a map of user_id => %{metadata: [...], phx_ref: "..."}.
"""
def get_users(topic) do
list(topic)
end
@doc """
Get count of users on a topic.
"""
def count_users(topic) do
list(topic)
|> Enum.reduce(0, fn {_user_id, data}, acc ->
acc + length(data.metas)
end)
end
@doc """
Get detailed user list with aggregated metadata.
"""
def get_user_list(topic) do
list(topic)
|> Enum.map(fn {user_id, %{metas: metas}} ->
# Use the first meta as representative, or aggregate if multiple devices
meta = List.first(metas)
%{
user_id: user_id,
name: meta.data.name || "Anonymous",
avatar: meta.data.avatar,
status: meta.data.status || "online",
joined_at: meta.joined_at,
node: meta.node,
device_count: length(metas)
}
end)
|> Enum.sort_by(& &1.joined_at)
end
@doc """
Subscribe to presence changes on a topic.
"""
def subscribe(topic) do
Phoenix.PubSub.subscribe(PresenceTracker.PubSub, topic)
end
@doc """
Unsubscribe from presence changes on a topic.
"""
def unsubscribe(topic) do
Phoenix.PubSub.unsubscribe(PresenceTracker.PubSub, topic)
end
end
defmodule PresenceTrackerWeb.Router do
use PresenceTrackerWeb, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {PresenceTrackerWeb.Layouts, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", PresenceTrackerWeb do
pipe_through :browser
get "/", PageController, :home
live "/users", UsersLive
end
scope "/api", PresenceTrackerWeb do
pipe_through :api
get "/cluster/status", PageController, :cluster_status
end
end
10. User Socket
lib/presence_tracker_web/user_socket.ex
elixir
defmodule PresenceTrackerWeb.UserSocket do
use Phoenix.Socket
channel "presence:*", PresenceTrackerWeb.PresenceChannel
@impl true
def connect(params, socket, _connect_info) do
{:ok,
socket
|> assign(:user_id, params["user_id"] || generate_user_id())
|> assign(:name, params["name"] || "Anonymous")
|> assign(:avatar, params["avatar"])}
end
@impl true
def id(_socket), do: nil
defp generate_user_id do
System.unique_integer([:positive]) |> to_string()
end
end
# Track a user
Presence.track_user("lobby", "user123", %{name: "John"})
# Get all users
Presence.get_users("lobby")
# Get formatted user list
Presence.get_user_list("lobby")
# Count users
Presence.count_users("lobby")
# Untrack user
Presence.untrack_user("lobby", "user123")
Monitoring & Debugging
Check cluster status:
code
curl http://localhost:4000/api/cluster/status
IEx debugging:
bash
iex --remsh node1@localhost
Check connected nodes:
elixir
Node.list(:connected)
Performance Tuning
For High User Counts
Enable Distributed Presence:
elixir
config :presence_tracker, PresenceTracker.Presence,
pool_size: 2 # Use pooling
Production Ready - Docker, Compose, and K8s configs
Scalable - Handles thousands of concurrent users
Tested - Comprehensive test suite included
The system automatically syncs presence information across all nodes in the cluster, ensuring consistent user state regardless of which node users connect to!
defmodule PresenceTrackerWeb.UsersLive do
@moduledoc """
Real-time display of online users using LiveView.
"""
use PresenceTrackerWeb, :live_view
alias PresenceTracker.Presence
@topic "lobby"
@impl true
def mount(_params, _session, socket) do
if connected?(socket) do
Presence.subscribe(@topic)
end
user_id = System.unique_integer([:positive]) |> to_string()
socket =
socket
|> assign(user_id: user_id, topic: @topic, users: [], count: 0)
|> update_users()
{:ok, socket}
end
@impl true
def handle_info({:presence_diff, _payload}, socket) do
{:noreply, update_users(socket)}
end
@impl true
def render(assigns) do
~H"""
<div class="container mx-auto p-8">
<div class="grid grid-cols-1 md:grid-cols-3 gap-8">
<!-- Stats -->
<div class="bg-white rounded-lg shadow p-6">
<h2 class="text-2xl font-bold mb-4">Online Users</h2>
<p class="text-4xl font-bold text-blue-600"><%= @count %></p>
<p class="text-gray-500 mt-2">users currently online</p>
</div>
<!-- Cluster Info -->
<div class="bg-white rounded-lg shadow p-6">
<h2 class="text-lg font-bold mb-4">Cluster</h2>
<p class="text-sm text-gray-600">
<strong>Current Node:</strong> <%= node() %>
</p>
<p class="text-sm text-gray-600 mt-2">
<strong>Connected Nodes:</strong> <%= length(Node.list(:connected)) %>
</p>
</div>
<!-- Your Info -->
<div class="bg-white rounded-lg shadow p-6">
<h2 class="text-lg font-bold mb-4">Your Info</h2>
<p class="text-sm text-gray-600">
<strong>User ID:</strong> <%= @user_id %>
</p>
<p class="text-sm text-gray-600 mt-2">
<strong>Status:</strong> <span class="text-green-600">● Online</span>
</p>
</div>
</div>
<!-- Users List -->
<div class="mt-8 bg-white rounded-lg shadow p-6">
<h2 class="text-2xl font-bold mb-4">Online Users</h2>
<div class="overflow-x-auto">
<table class="w-full">
<thead class="bg-gray-50 border-b">
<tr>
<th class="px-6 py-3 text-left text-sm font-semibold">User ID</th>
<th class="px-6 py-3 text-left text-sm font-semibold">Name</th>
<th class="px-6 py-3 text-left text-sm font-semibold">Status</th>
<th class="px-6 py-3 text-left text-sm font-semibold">Node</th>
<th class="px-6 py-3 text-left text-sm font-semibold">Devices</th>
<th class="px-6 py-3 text-left text-sm font-semibold">Joined</th>
</tr>
</thead>
<tbody class="divide-y">
<%= for user <- @users do %>
<tr class={if user.user_id == @user_id, do: "bg-blue-50", else: ""}>
<td class="px-6 py-4 text-sm"><%= user.user_id %></td>
<td class="px-6 py-4 text-sm font-medium"><%= user.name %></td>
<td class="px-6 py-4 text-sm">
<span class={status_badge(user.status)}>
<%= user.status %>
</span>
</td>
<td class="px-6 py-4 text-sm"><code class="text-xs"><%= user.node %></code></td>
<td class="px-6 py-4 text-sm"><%= user.device_count %></td>
<td class="px-6 py-4 text-sm text-gray-500">
<%= format_time(user.joined_at) %>
</td>
</tr>
<% end %>
</tbody>
</table>
</div>
</div>
</div>
"""
end
defp update_users(socket) do
users = Presence.get_user_list(@topic)
count = length(users)
assign(socket, users: users, count: count)
end
defp status_badge(status) do
case status do
"online" -> "inline-block px-3 py-1 bg-green-100 text-green-800 text-xs rounded-full"
"away" -> "inline-block px-3 py-1 bg-yellow-100 text-yellow-800 text-xs rounded-full"
"offline" -> "inline-block px-3 py-1 bg-gray-100 text-gray-800 text-xs rounded-full"
_ -> "inline-block px-3 py-1 bg-gray-100 text-gray-800 text-xs rounded-full"
end
end
defp format_time(milliseconds) do
now = System.monotonic_time(:millisecond)
diff = now - milliseconds
case diff do
d when d < 60_000 -> "just now"
d when d < 3_600_000 -> "#{Integer.floor_div(d, 60_000)}m ago"
d when d < 86_400_000 -> "#{Integer.floor_div(d, 3_600_000)}h ago"
_ -> "#{Integer.floor_div(diff, 86_400_000)}d ago"
end
end
end