Hello!
I have a NextJS Project that uses websockets. I have deployed to Railway successfully, but am concerned about the memory usages of the server. For those who are not aware railway deploys code and you rent a server for the whole month rather than vercel architecture where you pay for the time that you use on your server. Since I am using websockets and need the connections to persist for a long time, I chose to go this route.
The problem is this. After deploying a change to the website the server load is around 200mb. Then when a user connects to the website the server load suddenly jumps up to around 400-500mbs. Even though this is quite a significant load, I am not worried about this spike.
The issue that I am worried about is that this spike seems to persist even if that user ceases to use the website. So that 400mbs-500mbs will stay with the server until after another deployment. It is constantly using resources and I am not quite sure why.
I have stress tested my website with multiple clients open all sending messages and the server spiked to 1.5GB of memory usage which would not fall down even after all clients disconnected.
Here is a list of the things that I have tried to fix this issue:
-
Used export const dynamic = 'force-dynamic' in order to stop caching of data inside of the server in case this was a problem.
Reasoning: I thought that the server would cache the html from the website into the server and serve it to the client, in order to prevent this i disabled caching in the routes with the most html. -
Disabled Polling Inside Of My Website
Reasoning: My project Uses Websockets, and when a socket is not connected it reverts to polling. I figured that this setup could be persistently calling the server and putting on a load. -
Checked logs To See if Sockets are disconnecting correctly (They Are)
-
https://github.com/vercel/next.js/issues/49929
I have also checked this github issues post. However most of the comments seem to suggest that the issue is with the appdir. I am using the app directory structure in my application, and cannot turn off the appdir like some in this thread are saying to do as a solution.
I believe that there is some sort of memory leak happening, since the memory usage is constantly slowly creeping upwards. If there are tools that anyone knows about that check for memory leaks, or if there are common patterns that I should look out for. Please let me know!
I am also willing to completly start over with this project if that is needed. This is my first nextjs project and I would like to understand what I need to do to prevent memory leaks. I have started the process of finding the leak by having every route returning null so that none of my code is being run. However I am slightly worried since the memory usage on the server is still slowly creeping up from 350mb to 400mb without any usage in the course of a day.