quda

quda

I am building a json REST API with Phoenix that (among other services) has to convert static CSV files from a repository and “serve” them as response in json format; that will be used downstream by other services in our project. Some of these csv files are quite big, ranging for a several hundred kb to tens of MB.
So far so good, I made it work with several lines of code.
So, in my backend side:

 defp csv(file) do
   file
    |> Path.expand(__DIR__)
    |> File.stream!()
    |> CSV.decode(headers: true)
    |> Enum.map(fn {:ok, val} -> val end)
  end

in the API controller:

  def show(conn, bhandler) do
    conn
    |> Plug.Conn.put_resp_header("content-type", "application/json; charset=utf-8")
    |> Plug.Conn.send_resp(200, Jason.encode!(bhandler, pretty: true))
  end
end

The program is doing well what is supposed to do but on small files.
When the file gets bigger and response time gets exponentially bigger:

  • for 69kb (csv file) → 124ms :grinning:
  • 234kb → 2.8s :slightly_smiling_face:
  • 1.1MB → 24s :neutral_face:
  • 22.4MB → 835s :flushed:

Obviously something is very wrong with these implementation, or with its libraries (CSV, Jason). A similar (simple) API we have, in php, took a few of seconds to read/convert/send/receive 40MB csv file.

Do you have any suggestion ?

Showing Posts 1 to 10

moogle19

moogle19

Maybe try nimble_csv. It has NimbleCSV.RFC4180 build in, which should parse your file.

"path/to/file"
|> File.read!() 
|> NimbleCSV.RFC4180.parse_string()

seems also faster than streaming the file (at least for ~20MB sized files).

The only downside is, that parse_string/1 returns a list of lists and you have to map it to a map yourself.

krasenyp

krasenyp

I see two possible solutions. First, as @moogle19 suggested, you can use NumbleCSV’s parse_stream and send a chunked response using Plug.Conn.send_chunked/2, never loading the whole file into memory. Second, you can, again, use parse_stream to stream the contents into a temporary file and use Plug.Conn.send_file/5. I believe the second one is trickier because in case you have a lot of requests there should be rate limiting in order to not fill your disk memory.

lud

lud

Can you measure which code is slow ? Is it the parsing, the JSON encoding, etc.

Also you could:

  • use Stream.map instead of Enum.map to avoid keeping too much data in memory
  • use Jason.Fragment on each in Stream.map to encode to JSON line by line
  • use Jason.encode_to_iodata instead of Jason.encode to avoid converting the full JSON structure to a string before sending it
  • convert your files to JSON once and serve the JSON files instead of converting from CSV for every request
quda

quda OP

Can you measure which code is slow ? Is it the parsing, the JSON encoding, etc.

Good idea, to find out which is the “culprit” and isolate the problem.
But I don’t know how to do that.

dimitarvp

dimitarvp

When input data is expected to be large, always use streaming and never keep all of it in memory.

kokolegorille

kokolegorille

You can use Benchee…

moogle19

moogle19

I tested it with a ~130MB CSV file and the default benchee config:

Name             ips        average  deviation         median         99th %
nimble         0.121         8.24 s     ±0.00%         8.24 s         8.24 s
csv           0.0173        57.91 s     ±0.00%        57.91 s        57.91 s

Code is:

file = "samples/large.csv"

Benchee.run(%{
  "nimble" => fn ->
    file
    |> File.stream!()
    |> NimbleCSV.RFC4180.parse_stream()
    |> Stream.map(fn [first, second, third, fourth, fifth] -> %{f: first, s: second, t: third, fo: fourth, fi: fifth} end)
    |> Enum.into([])
  end,
  "csv" => fn ->
    file 
    |> File.stream!() 
    |> CSV.decode!() 
    |> Enum.into([])
  end
})

It seems nimble_csv is much faster for large files.

lud

lud

You can wrap each part of the code with :timer.tc/1:

{decode_µs, data} = :timer.tc(fn -> decode_from_csv(file) end)
{encode_µs, json} = :timer.tc(fn -> Jason.encode_to_iolist!(data) end)

etc.

quda

quda OP

Thank you all, I managed to do this implementation using NimbleCSV:

 defp csv(p) do

    [header | data] = p
      |> Path.expand(__DIR__)
      |> File.stream!()
      |> NimbleCSV.RFC4180.parse_stream(skip_headers: false)
      |> Enum.into([])

    Enum.map(data, fn x -> Enum.zip(header, x) |> Map.new() end)
 end

It does the job but not much improvement
3.5MB → 22.46s
21.4MB → 7.2min (tested this file on a similar API, written long time ago, in php5, calling a humble fgetcsv() with no streams and we got 22.22s :pensive:)

So still far for being usable.
I presume the issue is not streaming in the csv file but the second part - assembling the map and sending out the json.

LostKobrakai

LostKobrakai

Is there a reason to stream the data into memory? If not try using the non streamed API, which should be faster.

Where Next? Top

Trending in Questions Top

itzmidinesh
Hi all, I’m working on a Phoenix project where I need to make external HTTP requests and I’m trying to choose between Req and HTTPoison....
New
yarrichar
I’m very new to Elixir, so sorry if this is a silly question: I am wondering what happens to the mailbox of a process when the machine i...
New
pragdave
How do I tell Hologram not to escape HTML when substituting into templates? {Textile.render(@product.long_description)} escapes the HTM...
New
Fl4m3Ph03n1x
Background When trying to execute mix release on a Windows 11 machine for a Phoenix project I get the following error: * assembling mark...
New
rlipscombe
I’d like to create a file with 600 permissions (rw-------), but there’s a race condition if I create it and then change the permissions. ...
New
saleyn
Is there a way to import record definitions in the iex shell for pretty printing (similar to the rr command in the erl shell)? This woul...
New
rlipscombe
When I use Mix.install with a git dependency, using git@github.com:... how do I change the SSH identity used? I’ve got two Github accoun...
New

Other Trending Topics Top

dominicletz
Hey there, I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first. ...
New
raa-ziq
Hi everyone :waving_hand: I wanted to share something I’ve been building — NowBlind, a random chat app designed to help people discover ...
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
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
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New
kip
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews