Repository navigation
Streaming flow run result? #18852
Replies: 2 comments
|
A workable approach is to persist a small archive reference as the flow result, then stream the archive directly from its storage. For a filesystem that both the flow and your API can access, the core pattern is: from collections.abc import Iterator
from pathlib import Path
from zipfile import ZipFile
from fastapi.responses import StreamingResponse
from prefect import flow
@flow(persist_result=True)
def build_archive(archive_path: str) -> str:
path = Path(archive_path).resolve()
path.parent.mkdir(parents=True, exist_ok=True)
with ZipFile(path, "w") as archive:
archive.writestr("report.txt", "report contents\n")
return str(path)
def read_chunks(path: str, chunk_size: int = 64 * 1024) -> Iterator[bytes]:
with open(path, "rb") as archive:
while chunk := archive.read(chunk_size):
yield chunk
def archive_response(archive_path: str) -> StreamingResponse:
return StreamingResponse(
read_chunks(archive_path),
media_type="application/zip",
headers={"Content-Disposition": 'attachment; filename="report.zip"'},
)In your API, retrieve the completed run's persisted result as you already do, then pass that returned path to The archive needs its own durable storage and retention policy. A worker's private or ephemeral local path will not work for a separate API host. For distributed infrastructure, upload the ZIP to shared storage, return its key/URI, and have your API use that storage provider's streaming read. Configure shared Prefect result storage as well, so the API can retrieve the small reference. Prefect's result guide explains that result storage persists serialized return values; it does not control where your flow writes its separate files. I tested this with Prefect 3.8.8, FastAPI 0.143.0, and Python 3.12.14 against a temporary local Prefect server. Fetching the run through the client and calling its state's |
|
Thank you for your answer. This is indeed a workaround and one which I had adopted in the meantime. I'll mark it as answered. |
Uh oh!
There was an error while loading. Please reload this page.
I have a workflow with persisted results which may return a large ZIP, and an API that allows clients to retrieve the results from completed flow runs.
Currently I use the python client to get the flow run object and then the result through
flow_run.state.result(). However, this entails deserialising the whole payload into memory which may yield excessive memory usage. I'd like a way to have a streaming handle (e.g. a file-like object) to in turn allow my API to return a stream (e.g. FastAPI'sStreamingResponse).I have not seen a built‑in streaming result API in the
Stateobject, but is there a recommended workaround that avoids full deserialisation? Or maybe it could be a valuable addition?All reactions