sreyansjain

sreyansjain

Hi I am trying to use Server Sent Events.
I want to send chunked responses.

I am able to send them like so

conn
      |> put_resp_header("cache-control", "no-cache")
      |> put_resp_header("connection", "keep-alive")
      |> put_resp_header("content-type", "text/event-stream;")
      |> send_chunked(200)
      |> chunk("This is some respsonse")

The responses are being sent, but without gzip compression.
How do i get responses to be sent with gzip compression?

I am using the latest phoenix with latest bandit.
Please advise.

PS If I don’t send chunked response, it gets compressed. For ex -

conn
      |> put_resp_header("cache-control", "no-cache")
      |> put_resp_header("connection", "keep-alive")
      |> put_resp_header("content-type", "text/event-stream;")
      |> text("This would get compressed")

Is some magic happening in the text/2 method?

Showing Posts 1 to 3

sreyansjain

sreyansjain OP

Got it to work.
We need to set the content-encoding to gzip
and then manually compress the responses like so

conn
      |> put_resp_header("cache-control", "no-cache")
      |> put_resp_header("connection", "keep-alive")
      |> put_resp_header("content-type", "text/event-stream;")
      |> put_resp_header("content-encoding", "gzip")
      |> send_chunked(200)

And then compress the message manually and send them

defp send_chunk(conn, message) do
    message = :zlib.gzip(message)
    {:ok, conn} =
      conn
      |> prepare_sse()
      |> chunk(message)
    conn
  end
hubertlepicki

hubertlepicki

thank you for reporting back, I am sure it’ll be useful to someone

sreyansjain

sreyansjain OP

SSE compression in long lived connection for streaming updates –

# lib/aet_web/controllers/sse_controller.ex
defmodule AetWeb.SseController do
  use AetWeb, :controller

  def stream(conn, _params) do
    conn =
      conn
      |> put_resp_header("content-type", "text/event-stream")
      |> put_resp_header("content-encoding", "gzip")
      |> put_resp_header("cache-control", "no-cache")
      # |> put_resp_header("connection", "keep-alive")
      |> send_chunked(200)

    # Initialize zlib compression context with gzip wrapper
    z = :zlib.open()
    :ok = :zlib.deflateInit(z, 9, :deflated, 31, 8, :default)  # 31 = gzip format

    # Subscribe to PubSub
    Phoenix.PubSub.subscribe(Aet.PubSub, "events")

    # Start streaming
    try do
      stream_events(conn, z)
    after
      # IO.puts("Finalizing stream...")
      compressed_end = :zlib.deflate(z, "", :finish)
      # IO.inspect(compressed_end, label: "Final chunk")
      Plug.Conn.chunk(conn, compressed_end)
      cleanup_zlib(z)
    end
  end

  defp stream_events(conn, z) do
    receive do
      {:event, data} ->
        # Compress incrementally with sync flush
        compressed_chunk = :zlib.deflate(z, data, :sync)  # :sync flushes immediately

        case Plug.Conn.chunk(conn, compressed_chunk) do
          {:ok, conn} ->
            IO.puts("Chunk sent successfully")
            stream_events(conn, z)
          {:error, :closed} ->
            IO.puts("Client disconnected")
            conn  # Cleanup handled in `after` clause
        end
    after
      1000 ->  # Timeout to prevent infinite loop if no events
        IO.puts("No events received in 1s, continuing...")
        stream_events(conn, z)
    end
  end

  defp cleanup_zlib(z) do
    IO.puts("Cleaning up zlib context...")
    case :zlib.deflateEnd(z) do
      :ok -> :zlib.close(z)
      error ->
        IO.inspect(error, label: "DeflateEnd error")
        :zlib.close(z)
    end
  rescue
    e ->
      IO.inspect(e, label: "Cleanup error")
      :zlib.close(z)
  end
end
— All posts loaded —

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
bradley
I really like the adapter patterns that ecto, nebulex, waffle, etc. use and would love find something similar for a key management servic...
New
unaware8150
Hello folks! So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New
dillonoconnor
Is there any way to avoid the Hologram compiler running when using iex? It seems like the front-end code could potentially be disregarded...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews