Skip to content

Lesson 4 of 9 · 24m

Phoenix Request Flow, Contexts, and Where Logic Belongs

Trace endpoint, router, pipelines, controllers, contexts, schemas, and changesets so web concerns stay separate from domain behavior.

Phoenix is fast because the BEAM is fast, but Phoenix stays maintainable because it gives you places to put things. Teams get into trouble when controllers become domain models, schemas become validation dumping grounds, and contexts become meaningless folders. Learn the request flow and the pressure points.

The request path is explicit

A normal HTTP request travels through a clear chain:

Cowboy/Bandit -> Endpoint -> Router -> Pipeline -> Controller/LiveView -> Context -> Repo

Contexts are operational seams

A context exposes operations the application performs:

def create_room(account, attrs) do
  %Room{}
  |> Room.changeset(attrs)
  |> Ecto.Changeset.put_change(:account_id, account.id)
  |> Repo.insert()
end

Changesets are input boundaries

def changeset(room, attrs) do
  room
  |> cast(attrs, [:name, :topic, :public])
  |> validate_required([:name])
  |> unsafe_validate_unique(:name, Pulse.Repo)
end

Controllers translate, they do not decide policy

def create(conn, %{"room" => room_params}) do
  case Chat.create_room(conn.assigns.current_account, room_params) do
    {:ok, room} -> conn |> put_status(:created) |> json(%{id: room.id, name: room.name})
    {:error, %Ecto.Changeset{} = cs} -> conn |> put_status(:unprocessable_entity) |> json(%{errors: translate_errors(cs)})
  end
end

Authorization belongs in object loading

If a user can only view rooms in their account, encode the relationship in the query:

def get_room_for_account!(account_id, room_id) do
  Repo.one!(from r in Room, where: r.id == ^room_id and r.account_id == ^account_id)
end

Field notes

  • conn.assigns is request-local state, not a general-purpose domain bag.
  • Fallback controllers are useful for uniform API errors, but they do not define domain semantics.
  • Keep JSON encoding deliberate; returning whole schemas often leaks internal fields.
  • Database constraints are not duplication of validations. They are concurrency-resistant truth.
  • Future maintainers will look in contexts for behavior before reading controllers.

Was this lesson helpful?

Sign in to rate