Skip to content

[BUG] Message Ordering Issue with Turbo Streams and Streaming Responses #282

@fluxsaas

Description

@fluxsaas

Basic checks

  • I searched existing issues - this hasn't been reported
  • I can reproduce this consistently
  • This is a RubyLLM bug, not my application code

What's broken?

Problem

Assistant messages appear above user messages in real-time chat due to chat.ask() creating both messages within milliseconds, causing ActionCable broadcast race conditions.

Steps to Reproduce

  1. Follow ruby_llm docs setup with Turbo Streams
  2. Call chat.ask(user_content)
  3. Observe message order in UI

Expected vs Actual Behavior

❌ Actual:   Assistant: [response]
             User: [question]

✅ Expected: User: [question] 
             Assistant: [response]

Evidence

Both messages created simultaneously:

# Log output
Message created: user - 7d50d730... - 2025-07-13 20:24:46 +0200
Message created: assistant - 0df903f1... - 2025-07-13 20:24:46 +0200

Workaround

Delay assistant message broadcasts:

after_create_commit do
  if role == 'assistant'
    broadcast_append_later_to(..., wait: 0.1.seconds)
  else
    broadcast_append_to(...)
  end
end

Environment

  • ruby_llm: 1.3.1
  • Rails: 8.0.1
  • Frequency: Intermittent but common under load
  • Note: Database order always correct (reloading the page corrects ordering), only affects real-time display

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions