Is Application.fetch_env expensive?

Hi,

In terms of performance, is it ok to call Application.fetch_env! in a function that is called every time my Phoenix application receives a new websocket connection?

Should I wrap my function in a GenServer just to keep the value in the state? (I don’t think so but just checking)

Is there any “context” that Phoenix might provide that I could use to store this value and somehow would end up being available to me in the socket structure?

The long story is like this: I have this Phoenix application that accepts websocket connections and I am using Joken to verify a token that comes in the connection request. It’s a JWT generated by another system and signed using RS256 so I need to know the public key for verifying it. When the application starts, my runtime.exs reads the public key from an environment variable and stores it as an application configuration. Then, every time a new websocket connection comes in my verify function in my Token module reads the public key using Application.fetch_env! and verifies the token.

Thanks for any guidance.

Yes. It is cheap enough. also you don’t want to use stale env if those can be updated by user triggered actions within your application.

6 Likes