Fix EmbeddingService blocking event loop by offloading encode to thread#262
Fix EmbeddingService blocking event loop by offloading encode to thread#262dolliecoder wants to merge 1 commit intoAOSSIE-Org:mainfrom
Conversation
…vent loop blocking
📝 WalkthroughWalkthroughThe EmbeddingService now offloads blocking Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant EventLoop as Event Loop
participant ThreadPool as Thread Pool
participant Model as Model.encode()
rect rgba(100, 150, 200, 0.5)
Note over Client,Model: Before: Blocking
Client->>EventLoop: await get_embedding()
EventLoop->>Model: model.encode() [BLOCKING]
Note over EventLoop: ⚠ Other requests stall
Model-->>EventLoop: result
EventLoop-->>Client: embedding
end
rect rgba(100, 200, 100, 0.5)
Note over Client,Model: After: Non-blocking
Client->>EventLoop: await get_embedding()
EventLoop->>ThreadPool: asyncio.to_thread(_encode_sync)
Note over EventLoop: ✓ Event loop free
ThreadPool->>Model: model.encode() [in thread]
rect rgba(150, 200, 255, 0.5)
Note over EventLoop: Other requests run
end
Model-->>ThreadPool: result
ThreadPool-->>EventLoop: result
EventLoop-->>Client: embedding
end
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@vaishcodescape do you think its ready to be merged? |
Fixes #261
Problem:
EmbeddingService.get_embedding() and get_embeddings() call SentenceTransformer.encode() inside async methods.
Since encode() is synchronous and CPU-heavy, it blocks the asyncio event loop and prevents concurrent requests.
Solution:
Moved encode calls to asyncio.to_thread() using a small synchronous helper method.
Result:
Embedding generation no longer blocks the event loop.
Improves concurrency without changing public API or behavior.
Summary by CodeRabbit