I'm currently working on a latency critical application. After profiling my code, I concluded that the bottleneck might be related to my WebSocket client. I don't control the server, only the client.
Context
I'm running a c5d.xlarge Ubuntu instance with ENA (Elastic Network Adapter) in the same availability zone as the server. If I ping the server from my instance, the latency is below 1 ms (usually between 0.2 and 0.5 ms). My code is written in Haskell and this is the WebSocket library I use: http://hackage.haskell.org/package/websockets The difference between the message timestamp sent by the server and the timestamp I create upon receiving the message is usually below 10 ms which is good enough for me. However, sometimes this time difference increases to 4-500 ms or even worse (above 1-1.5s). I suspect this happens when the server has to deal with increased activity, thus when the server is under heavy load. Despite the fact that I didn't find any indication that it might be my code, my instance setup or the combination of both that causes this latency spike, I was still skeptical and so I headed to https://websocket.org/echo.html from my local machine (a Mac) in order to check the latencies from there (using Chrome as my browser). Since this is farther from the server than my instance, I get slightly higher latencies but usually below 50 ms. The 4-500 ms latency spikes are happening here as well.
Reproduction
In Chrome, head over to https://websocket.org/echo.html and connect to: wss://www.bitmex.com/realtime
Finally, send the following message to the server and inspect the WebSocket frames under the Network tab in Chrome Developer Tools:
{"op": "subscribe", "args": ["orderBook10:XBTUSD"]}
Question
Is there any way to further minimise latency in such situation? Are there any rules of thumb when configuring my WebSocket client connection that I might be missing? I tried using the WebSocket compression extensions but that didn't seem to help. I feel like that there isn't much I can do about this, since the server is not under my control. Thanks!