Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions news/6734.performance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Remove the per-update `asyncio.create_task` wrapper in `EventNamespace.emit_update`, cutting scheduling overhead roughly in half for every outgoing state update while keeping the event-loop tick that flushes interim updates before a sync handler resumes.
14 changes: 9 additions & 5 deletions reflex/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -1712,11 +1712,15 @@ async def emit_update(self, update: StateUpdate, token: str) -> None:
f"Attempting to send delta to disconnected client {token!r}"
)
return
# Creating a task prevents the update from being blocked behind other coroutines.
await asyncio.create_task(
self.emit(str(constants.SocketEvent.EVENT), update, to=socket_record.sid),
name=f"reflex_emit_event|{token}|{socket_record.sid}|{time.time()}",
)
# Await the emit directly: wrapping it in a task does not unblock the
# caller (awaiting the task blocks just the same) and only adds task
# creation/scheduling overhead on every update.
await self.emit(str(constants.SocketEvent.EVENT), update, to=socket_record.sid)
# The emit may complete without suspending (the packet is queued, not
# sent). Yield one loop tick so the websocket writer can flush the
# packet before the caller potentially blocks the event loop (e.g. a
# sync event handler resuming after a yield).
await asyncio.sleep(0)

async def on_event(self, sid: str, data: Any):
"""Event for receiving front-end websocket events.
Expand Down
Loading