Yasoob01

Yasoob01

Phoenix Channels: Prevent auto-subscription to raw client topic

TL;DR

Clients join a simple topic like "daily_agent_stats:total_inbound_calls".
On the server I expand it using workspace_id + agent_id from params.
But Phoenix still subscribes them to the raw topic too → I want to stop that and only keep the expanded subscription.


Hey folks :waving_hand:

I’m building a Phoenix channel for agent analytics stats.
Here’s a simplified version of my use case:

What I want

  • Clients connect with workspace_id and agent_id as query params.

  • Then they only subscribe with a simplified topic (no need to repeat IDs).

  • On the server, I expand that simplified topic into the full PubSub key and subscribe internally.

Example

Channel:

defmodule MyAppWeb.AgentChannel do
  use Phoenix.Channel

  # Client joins something like: "daily_agent_stats:total_inbound_calls"
  def join("daily_agent_stats:" <> stat_key, _payload, socket) do
    workspace_id = socket.assigns[:workspace_id]
    agent_id = socket.assigns[:agent_id]

    # Expand topic internally
    full_topic = "agent/analytics/daily_agent_stats:#{workspace_id}:#{agent_id}:#{stat_key}"

    IO.puts("Subscribing to #{full_topic}")
    Phoenix.PubSub.subscribe(MyApp.PubSub, full_topic)

    {:ok, socket}
  end

  def join(topic, _payload, _socket) do
    {:error, %{reason: "Invalid topic #{topic}"}}
  end
end

UserSocket:

defmodule MyAppWeb.UserSocket do
  use Phoenix.Socket

  channel "daily_agent_stats:*", MyAppWeb.AgentChannel

  def connect(%{"workspace_id" => ws_id, "agent_id" => agent_id}, socket, _connect_info) do
    {:ok, assign(socket, :workspace_id, ws_id) |> assign(:agent_id, agent_id)}
  end

  def id(_socket), do: nil
end

Client connection (via wscat):

wscat -c "ws://localhost:4000/v1/agent/websocket?workspace_id=c8f4a3a0-835d-4ee2-9c71-0c18550680e5&agent_id=47dbbab6-1abf-4392-a42f-dbde107c2793"

Join a topic without IDs:

{"topic":"daily_agent_stats:total_inbound_calls","event":"phx_join","payload":{},"ref":1}

The Issue:

Even though I subscribe manually inside join/3, Phoenix still also assigns the socket to the original "daily_agent_stats:total_inbound_calls" topic.

So the socket ends up listening on two topics:

  • "daily_agent_stats:total_inbound_calls"

  • "agent/analytics/daily_agent_stats:<workspace_id>:<agent_id>:total_inbound_calls"

I want to disable the first (auto) subscription and only rely on the expanded one.

My Question:
Is there a way to tell Phoenix not to subscribe the socket to the raw topic passed in by the client, so I can fully control subscriptions in join/3?

Any guidance on best practices here would be super helpful.

Most Liked

LostKobrakai

LostKobrakai

No. Channels are not an abstraction for communication between only the client and the server (1 to 1). They’re an abstraction to extend phoenix pubsub from just reaching processes on servers to their connected clients – it’s still pubsub on the channels topic.

If you want plain websockets without the semantics of channels take a look at: Bare Websockets | Benjamin Milde

Alternatively you could also make the client join the correct topic directly.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Yeah consider topics almost like URLs. In general a secret URL isn’t great security, you instead should perform a real authZ check on join.

Where Next?

Popular in Discussions Top

vans163
So useless benchmarks aside, Its possible to write a webserver that can serve 300k requests per second (perhaps more with optimizations)....
New
Rustixir
Hi everyone, im working on find best language/framework/system for high concurrency, high performance and stable performance after wor...
New
cvkmohan
The upcoming Phoenix 1.6 release looks very interesting. Became a habit to watch the commits - and - what they are bringing in. phx.gen...
New
jeramyRR
This is an interesting article to read. Elixir’s performance, like usual, is excellent. However, it seems like the high CPU usage is co...
New
mmmrrr
Just saw that dhh announced https://hotwire.dev/ Is it just me or is this essentially live view? :smiley: Although I like the “iFrame-e...
New
pillaiindu
I want to convert a Phoenix LiveView CRUD website to a CRUD mobile app. What do you think is the easiest way to do so?
New
CharlesO
Erlang :list.nth simple, but 1 - based nth(1, [H|_]) -&gt; H; nth(N, [_|T]) when N &gt; 1 -&gt; nth(N - 1, T). Elixir Enum.at … coo...
New
und0ck3d
Hello everyone! A few days ago I’ve created a topic here about how people were creating CMSs with Elixir and Phoenix. I’ve been studying...
New
ben-pr-p
In general I’ve been sticking to this community style guide GitHub - christopheradams/elixir_style_guide: A community driven style guide ...
New
acrolink
How does the two languages compare when it comes to server side application development? Any experiences or ideas? Thank you.
New

Other popular topics Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
274 41539 114
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30877 112
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
boundedvariable
I am going through the kafka architecture. All the features what the kafka is providing are already in Erlang. I would like hear your opi...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New

We're in Beta

About us Mission Statement