My Python WebSocket Bot is Using Too Much RAM - Any Lightweight Alternatives?
Asked by
!a vote of thanks
I'm working on a trading bot that connects to Bybit and I've run into a problem. Each trading strategy runs in its own process managed by an `asyncio` event loop, which handles three coroutines: one WebSocket for private order fills, one for public price ticks, and a main polling loop to fetch candles every 10 seconds.
Initially, my bot used only REST polling and ran smoothly on just 0.5 vCPU and 512 MB RAM. However, after adding WebSocket support, the RAM usage skyrocketed. Now, it gets Out of Memory killed on the 512 MB containers, and I can only get it to run without issue on 1 GB RAM.
For example, the old code with REST polling had a VSZ of 445 MB and RSS around 120 MB, while the new code with WebSocket support jumps to a VSZ of 753 MB and still crashes with an RSS around 109 MB.
I've tried several libraries like `websocket-client`, `websockets`, and `aiohttp`, but they all seem to inflate the memory usage significantly. Is there any lightweight Python async WebSocket client available that won't bloat memory usage this much?
Answers
It sounds like you might be running into issues with creating too many sockets. Make sure youโre not unintentionally creating new connections continuously. Also, consider how many connections you actually need โ if you have multiple clients, each one will add overhead.
Reply to this answer
Have you looked into Centrifugo? It's a standalone WebSocket handler that manages connections and messages for you, and you can easily run it alongside your bot in a Docker container.
Reply to this answer
Have you checked your code for memory leaks? It might be a good idea to use a memory profiler to track down where your allocations are going. Sometimes, it's not the library itself but how resources are being managed in your code that can lead to high memory usage.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions