Build an Elixir Phoenix boilerplate with Phoenix LiveView for a real-time dashboard. Implement PubSub where an external Python cron job pushes data to Redis and the Phoenix server broadcasts to all connected LiveView clients.
Assistant
Outlining Phoenix-Redis PubSub bridge
The plan is to build a Phoenix LiveView dashboard updated in real time by bridging Redis PubSub (fed by a Python cron job) to Phoenix.PubSub via a GenServer using Redix.PubSub, then broadcast events to LiveView clients. I'll produce succinct boilerplate code covering mix.exs, config, application supervision, the Redis listener module, endpoint setup, router LiveView route, live dashboard module, and a simple Python script pushing to Redis.
Below is a minimal end‑to‑end example of how you can structure a Phoenix app with LiveView for a real‑time dashboard, fed by data coming from a Python cron job that publishes messages to Redis. The Phoenix server will subscribe to Redis (via Redix), then broadcast over Phoenix PubSub to all connected LiveView clients.
3) Start Redis PubSub bridge in your supervision tree
Create a module to subscribe to Redis and forward messages to Phoenix PubSub. For clarity, we’ll broadcast to topic "dashboard:updates".
lib/realtime_dash/redis_listener.ex:
elixir
defmodule RealtimeDash.RedisListener do
@moduledoc """
Listens to a Redis PubSub channel and re-broadcasts messages
via Phoenix PubSub to LiveView clients.
"""
use GenServer
require Logger
alias Phoenix.PubSub
@redis_channel "cron_updates" # Python job publishes here
@broadcast_topic "dashboard:updates"
# Public API
def start_link(opts) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
# GenServer callbacks
@impl true
def init(_opts) do
redis_url = Application.get_env(:realtime_dash, RealtimeDash.Redis)[:redis_url] || "redis://localhost:6379"
# Start a Redix connection
{:ok, redix_pubsub} = Redix.PubSub.start_link(redis_url)
# Subscribe to the channel
Redix.PubSub.subscribe(redix_pubsub, @redis_channel, self())
Logger.info("RedisListener subscribed to #{@redis_channel}")
{:ok, %{redix_pubsub: redix_pubsub}}
end
@impl true
def handle_info({:redix_pubsub, _from, :subscribed, %{channel: @redis_channel}}, state) do
# Successfully subscribed
{:noreply, state}
end
# This fires whenever a Redis PUBLISH arrives
@impl true
def handle_info({:redix_pubsub, _from, :message, %{channel: @redis_channel, payload: payload}}, state) do
Logger.info("Received payload from Redis: #{inspect(payload)}")
# Forward to Phoenix PubSub topic
PubSub.broadcast(RealtimeDash.PubSub, @broadcast_topic, {:new_data, payload})
{:noreply, state}
end
@impl true
def terminate(_reason, %{redix_pubsub: redix_pubsub}) do
# Clean up the connection if needed
Redix.PubSub.stop(redix_pubsub)
end
end
Update lib/realtime_dash/application.ex to start the listener:
elixir
defmodule RealtimeDash.Application do
use Application
def start(_type, _args) do
children = [
RealtimeDashWeb.Telemetry,
RealtimeDash.Repo,
{Phoenix.PubSub, name: RealtimeDash.PubSub},
RealtimeDashWeb.Endpoint,
# Start Redis listener
RealtimeDash.RedisListener
]
opts = [strategy: :one_for_one, name: RealtimeDash.Supervisor]
Supervisor.start_link(children, opts)
end
end
4) Expose the PubSub configuration in Endpoint
lib/realtime_dash_web/endpoint.ex:
elixir
defmodule RealtimeDashWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :realtime_dash
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
# ... your static plugs, code reloader, etc ...
# The PubSub name must match what you used above
@impl true
def init(_key, config) do
{:ok, Keyword.put(config, :pubsub_server, RealtimeDash.PubSub)}
end
end
(If generated by phx.new --live, it’s already set, but double‑check pubsub_server: RealtimeDash.PubSub.)
5) Router and LiveView
Add a Live route in lib/realtime_dash_web/router.ex:
elixir
defmodule RealtimeDashWeb.Router do
use RealtimeDashWeb, :router
import Phoenix.LiveView.Router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_live_flash
plug :put_root_layout, {RealtimeDashWeb.Layouts, :root}
plug :protect_from_forgery
plug :put_secure_browser_headers
end
scope "/", RealtimeDashWeb do
pipe_through :browser
live "/", DashboardLive, :index
end
end
6) The LiveView module
lib/realtime_dash_web/live/dashboard_live.ex:
elixir
defmodule RealtimeDashWeb.DashboardLive do
use RealtimeDashWeb, :live_view
@topic "dashboard:updates"
@impl true
def mount(_params, _session, socket) do
# subscribe to PubSub topic so this LiveView gets updates
if connected?(socket) do
Phoenix.PubSub.subscribe(RealtimeDash.PubSub, @topic)
end
# initial state
{:ok, assign(socket, :messages, [])}
end
# handle messages broadcasted by Redis listener
@impl true
def handle_info({:new_data, payload}, socket) do
messages = socket.assigns.messages ++ [payload]
{:noreply,
socket
|> assign(:messages, messages)
}
end
@impl true
def render(assigns) do
~H"""
<div class="container mx-auto">
<h1 class="text-2xl font-bold mb-4">Real-Time Dashboard</h1>
<div class="bg-white shadow rounded p-4">
<h2 class="text-xl font-semibold mb-2">Incoming Data</h2>
<ul class="list-disc pl-5">
<%= for msg <- @messages do %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
</div>
"""
end
end
The LiveView subscribes to "dashboard:updates". When the Redis listener receives a new payload, it broadcasts {:new_data, payload}, and each client updates its view.
7) Python cron job that publishes to Redis
Install redis in Python:
bash
pip install redis
Create a simple script cron_publish.py:
python
import redis
import json
import time
import random
# Connect to Redis
r = redis.Redis(host='localhost', port=6379, db=0)
channel = 'cron_updates'
def make_sample_payload():
return {
'timestamp': time.time(),
'value': random.randint(1, 100)
}
if __name__ == "__main__":
# Example: send one message
payload = make_sample_payload()
# Convert to JSON for clarity
message = json.dumps(payload)
r.publish(channel, message)
print(f"Published: {message}")
You can hook this script up to cron (or any scheduler) to push updates on a schedule. For example, every minute:
mix ecto.setup # if you use a DB; otherwise skip
mix phx.server
Visit http://localhost:4000 in your browser. When your Python cron job publishes messages, the data appears live in the dashboard.
How It Works
Python cron → Redis: The external script publishes to the Redis channel cron_updates.
Phoenix Redis listener: RealtimeDash.RedisListener subscribes to cron_updates using Redix.PubSub. Whenever it receives a message, it broadcasts via Phoenix PubSub to "dashboard:updates".
LiveView: On mount, each LiveView subscribes to "dashboard:updates". When it receives a {:new_data, payload} message, it updates its state (:messages) and re-renders in real time.
This gives you a small but complete boilerplate for real-time dashboards with Phoenix LiveView, Redis, and an external publisher (e.g., a Python cron job).