Should I Make My Whole Python App Async If I’m Using Websockets?

0
7
Asked By CuriousCoder22 On

I'm working on a Python application that follows the Clean Architecture pattern. In the infrastructure layer, I've created a lightweight websocket wrapper using aiohttp that communicates with a server. This websocket will listen indefinitely, reconnecting if the connection drops. Since this implementation is asynchronous, I'm wondering if I need to make the entire code base—including the application and domain layers—async as well. Or is it feasible (and sensible) to keep the async code confined to the websocket wrapper while keeping the rest of the code in synchronous form? For context, the application primarily functions as a client that listens to many high-frequency incoming messages through the websocket, and there will also be moments when I'll send messages back. Additionally, it will handle sending REST requests to another endpoint while managing its various tasks like updating a local cache and monitoring the overall process.

3 Answers

Answered By TechSavvy77 On

You don't necessarily have to make your entire codebase async. It's quite usual to keep the async parts limited to I/O operations, such as your websocket and HTTP client interactions. This helps maintain a clear separation, preventing async from seeping into other areas of your app. Trying to run everything async can complicate things unnecessarily unless your entire stack is focused on I/O.

Answered By AsyncAdventurer On

Remember, the rule of thumb is to consider whether your tasks are I/O bound. If they're not, using async might just slow things down without any real benefit. Async will allow your program to run other tasks while waiting for responses, but it’s not necessary for every single function—especially if they’re just doing basic work without any async calls. Focus on the I/O aspects where async can really shine.

Answered By DevNinja99 On

It's okay to mix async and sync in your code. I’ve set up my system where the adapters handle async, but all my business logic is sync. The application service coordinates between them. Just make sure the asynchronicity doesn't become overwhelming. You definitely want to consider making calls to REST endpoints async, and maybe even the local cache updates if they make sense. It’s all about finding that balance.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.