Ask HN: How to return large response over an API?
I am using a third party service which would transcribe an audio file and give me the entire transcription in a json format, I would read this and make a new json file by transforming it and send to s3. I am using python/django for it along with json, requests and boto3 module, however I noticed as the application kept running the memory consumption kept increasing.
To fix this I had to write it as a streaming response to a json file and use ijson (https://pypi.org/project/ijson/) to read the content which decreased memory utilisation a lot. So while looking around, I found many people had the same issue, so this got me thinking how would I have sent this content if i had built the third party api myself.
Some previous questions asked on stackoverflow,
https://stackoverflow.com/questions/2400643/is-there-a-memory-efficient-and-fast-way-to-load-big-json-files-in-python
https://stackoverflow.com/questions/11057712/huge-memory-usage-of-pythons-json-module
How do you send a response via an api for very large content, along with their advantages/disadvantages.
9 comments
[ 4.3 ms ] story [ 38.4 ms ] threadThink about it. They’re sending you data. You’re processing that data. If you don’t delete that data then it’s going to persist especially if you don’t do anything about it. Here’s a suggestion - do something about it! Clear unnecessary data immediately after it’s not needed so you don’t have to rely on python/django’s crappy garbage collection.
The server can incrementally stream a chunk and client incrementally consume a chunk keeping flat memory usage.
I think gRpc also supports streaming but don’t know much on it.
JSON is a bad format for large files as generally you need to read the entire file in to memory before you can use it as you observed.
The problem here I am facing is, when the object is loaded a lot of memory is used and the memory used is not freed fully, so the difference in this accumulates gradually. So I was looking for formats which can be processed without keeping the entire text in memory.
For the first one: look in specific json lib forums, ask there, check open issues, open issue. (all those stackoverflow questions/answers are really confusers, not helpers).
For the second one: so it's text, i'd transfer text then. It's too much text? Process it in chunks. Your final format is json? Encapsulate your text as json at the last final step.