geofflane

geofflane

How do I avoid DB disconnect on chunked streaming of large amount of data?

So let’s say I want to export a whole bunch of data from a database and stream it back to a user as a CSV, totally hypothetical. :slight_smile:

I’m taking in 40k ids, for example, and want to load those records and return the data as CSV. This is for a substantially wide data set, and a reasonably large table (millions of rows) so loading all 40k and saving as CSV take some time. I converted to loading the records in chunks, and streaming the results using the Plug.Conn.chunk and this increased my output before timeout from about 3k records to about 20k records. So far so good.

But I still eventually get an error if it takes too long:

[error] Postgrex.Protocol (#PID<0.432.0>) disconnected: ** (DBConnection.ConnectionError) client #PID<0.1160.0> exited

How do I avoid that? I don’t necessarily want to set a global connection checkout time to infinite if I can avoid it. Ideally I would be able to do something that would say, “Hey, as long as we’re still doing work keep going” or “Give me a new connection for each Repo.all” so the timeout would be per query and then I could play with the chunk size to optimize overall throughput.

Thanks in advance.

Example code below:

  def index(conn, %{"id" => id}) do
    ids = Query.decode_multi(id)

    conn
    |> put_resp_content_type("text/csv")
    |> put_resp_header("content-disposition", ~s[attachment; filename="feed.csv"])
    |> send_stream(ids)
  end

  # This can be a lot of data, so we're doing a stream to a chunked response
  # which requires us to interleave the loading of data and the streaming of
  # the response.
  defp send_stream(conn, ids) do
    streams =
      ids
      |> Enum.sort()
      |> Enum.chunk_every(250)
      |> Stream.map(fn(ids) ->
        Feed.Query.by_id(ids)
      end)

    streams
    |> Stream.with_index()
    |> Stream.map(fn({s, i}) ->
      {Repo.all(s), i}
    end)
    |> Stream.flat_map(&chunk_to_csv/1)
    |> Enum.reduce_while(Plug.Conn.send_chunked(conn, 200), fn chunk, conn ->
      case Plug.Conn.chunk(conn, chunk) do
        {:ok, conn} -> {:cont, conn}
        {:error, :closed} -> {:halt, conn}
      end
    end)
  end
  
   defp chunk_to_csv({feeds, i}) do
     # ...
   end

Most Liked

jola

jola

You can pass options to Repo.all assuming that’s the one that’s timing out. Repo.all(timeout: 15000) is default.

But the timeout is not per request, it’s per query. If you’re sure a query is timing out, it’s because a single query is taking longer than 15s. Are you sure it’s not your request connection timing out? By default cowboy closes a connection after a period of inactivity, depending on whether some data was sent (you can configure this).

I’m not sure how to read that error message, but it does say that the client exited. The client in this case is the request? Again, not sure how to interpret it.

Where Next?

Popular in Questions Top

vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New

Other popular topics Top

KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36352 110
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
AstonJ
We’ve put together this wiki for Phoenix LiveView - please feel free to add any info you feel is worth including. What is Phoenix LiveV...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39467 209
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement