dify icon indicating copy to clipboard operation
dify copied to clipboard

Streaming a chat answer costs API CPU in proportion to the conversation length for every chunk

Open Theysua opened this issue 3 weeks ago • 2 comments

Self Checks

  • [x] I have read the Contributing Guide and Language Policy.
  • [x] This is only for bug report, if you would like to ask a question, please head to Discussions.
  • [x] I have searched for existing issues search for existing issues, including closed ones.
  • [x] I confirm that I am using English to submit this report, otherwise it will be closed.
  • [x] 【中文用户 & Non English User】请使用英语提交,否则会被关闭 :)
  • [x] Please do not modify this template :) and fill in all the required fields.

Dify version

1.19.0 (the affected code is unchanged on main at e07c1f42b)

Cloud or Self Hosted

Self Hosted (Docker)

Steps to reproduce

  1. Start Dify 1.19.0 with Docker Compose and an OpenAI-compatible model whose answer streams 400 chunks over 4 seconds (a stand-in server is enough).
  2. Create a Chat app with that model and an API key.
  3. In one conversation, send 20 messages so the conversation has history. Do the same for 10 users.
  4. Have the 10 users send one more streaming message each (POST /v1/chat-messages) and read the CPU time the API container used for it (cpu.stat of its cgroup, before and after).
  5. Repeat step 4 in new conversations with no history.

✔️ Expected Behavior

The CPU spent on a streamed answer depends on the length of the answer. The length of the conversation matters once, when the prompt is built, not again for each chunk.

❌ Actual Behavior

Each streamed chunk costs API CPU in proportion to the number of messages in the prompt.

API process CPU per answer, one API process, 10 answers streaming at the same time (nothing queues):

Answer Conversation CPU per answer
20 chunks new 44 ms
100 chunks new 70 ms
400 chunks new 165 ms
400 chunks 20 earlier turns (46 prompt messages) 230 ms (six rounds, 220–241)

So the 20 earlier turns add about 65 ms to a 400-chunk answer, 0.16 ms per chunk, and the amount grows with both the answer and the history.

Where it comes from:

  • The model runtime puts the prompt of the call on every streamed chunk (chunk.prompt_messages = prompt_messages in _stream_invoke_result_chunks, re-added in #17883 after the plugin daemon stopped sending it for #17799).
  • AppRunner._handle_invoke_result_stream publishes each chunk as it comes: queue_manager.publish(QueueLLMChunkEvent(chunk=result), ...).
  • AppQueueManager.publish runs self._check_for_sqlalchemy_models(event.model_dump()) on every event. For a chunk event that dumps the whole prompt into dictionaries and walks them, once per streamed token.

The guard alone, timed on its own with the real classes (same machine for all rows, so only the ratio matters):

Prompt messages on the chunk Guard per chunk
2 6.6 µs
12 20 µs
42 60 µs
102 140 µs

Text length does not matter (a 16,000-character system prompt costs the same as a short one); the number of messages does. Nothing reads the prompt from the later chunks: EasyUIBasedGenerateTaskPipeline takes it from one chunk, and the terminal QueueMessageEndEvent carries it again.

#17799 was the same data riding on every chunk between the plugin daemon and the API; this is the part that remained inside the API process.

I have a fix that publishes the prompt with the first chunk event of a stream only, and will open a pull request. With it the same 400-chunk answer on the 20-turn conversations costs 171 ms (six rounds, 159–183), and what is stored as the prompt of the message is unchanged.

Theysua avatar Nov 14 '26 12:11 Theysua

Spot-on analysis. The $O(N \times M)$ overhead comes down to AppQueueManager.publish running self._check_for_sqlalchemy_models(event.model_dump()) on every emitted QueueLLMChunkEvent, which forces a full Pydantic dump of the prompt message array per chunk.

Two clean ways to tackle this:

  1. Exempt pure chunk events from model dumps in api/core/app/apps/base_app_queue_manager.py:
def publish(self, event: AppQueueEvent, pub_to_redis: bool = False):
    if not isinstance(event, QueueLLMChunkEvent):
        self._check_for_sqlalchemy_models(event.model_dump())

QueueLLMChunkEvent only carries transient token payloads and prompt copies, so recursively checking for detached SQLAlchemy models on every single token is unnecessary.

  1. Decouple the prompt history from intermediate chunks in _stream_invoke_result_chunks: only attach prompt_messages to the initial or final chunk if listeners downstream require it for token counting.

Option 1 is the cleanest hotfix and flattens per-chunk CPU time back to a constant baseline regardless of context size. A PR for this would be very welcome.

grinem avatar Nov 14 '26 12:11 grinem

Thanks for reading it through. The pull request is #46398 and takes your second route, one layer up: _stream_invoke_result_chunks lives in the model runtime package, so the app runner strips the prompt from every chunk event after the first where it takes the chunks over, and the pipeline reads it from the chunk that has it.

I did not exempt chunk events from the guard, for two reasons. The guard would then depend on a list of event types that someone has to keep right, and the prompt would still ride through the queue on every chunk for no reader. With the prompt sent once the guard stays as it is and costs the same per chunk whatever the history (about 5 µs against 60 µs with 42 messages, in the same micro-benchmark as the table above).

Theysua avatar Nov 14 '26 12:11 Theysua