Laravel-websockets: Are eloquent queries and other IO stuff non-blocking ?

Created on 15 Jun 2019  路  6Comments  路  Source: beyondcode/laravel-websockets

I hear in an async environment like ratchet or node.js the database drivers should work non-blocking to deliver a good performance, otherwise we get the worst out the two worlds.

So we definitely need a non-blocking mysql driver or something like that. (maybe send the queries to a child process)
I wanted to know is it ok and straight forward to just install the package on laravel and start to query the database or we have to change something ?

All 6 comments

Eloquent queries are blocking IO. Laravel unfortunately does not support any non-blocking/async IO backends by default.

You can use https://github.com/friends-of-reactphp/mysql which is an implementation of an async MySQL client, compatible with ReactPHP, which is what laravel-websockets is based on. You won't be able to use Eloquent with this though (unless you use the query builder, get the SQL, then run it raw with the async MySQL library, but then you'll still need to do model hydration yourself, etc, and ->save() won't work anyways)

It depends what you're trying to do though. If you're trying to trigger events to have some SQL run, I'd suggest trying to focus on sending ajax requests from your frontend instead. Probably much simpler, depending on the task.

@francislavoie I see this in the docs

Make sure that you do not perform any IO blocking tasks in your AppProvider, as they will interfere with the asynchronous WebSocket execution.

However I don't see the same warning in the docs for Custom Websocket Handlers. Does this mean that IO blocking is ok in Custom Websocket Handlers?

Nope, it's all running in the same event loop. Any blocking IO is not ideal.

I see. I might try this lib https://github.com/spatie/async

That's a good idea actually. Not sure why I didn't think of process forking to do stuff like that. I'd recommend using https://reactphp.org/child-process/ instead, which is an officially supported way to spawn some processes from within a ReactPHP event loop.

Great - thanks for the recommendation!

Was this page helpful?
0 / 5 - 0 ratings