IXWebSocket icon indicating copy to clipboard operation
IXWebSocket copied to clipboard

O(N^2) time complexity bug in WebsocketTransport

Open dbregman opened this issue 2 years ago • 9 comments

https://github.com/machinezone/IXWebSocket/blob/679ce519dd0d6d3919990abdee7109a5eeb99aa0/ixwebsocket/IXWebSocketTransport.cpp#L1067 https://github.com/machinezone/IXWebSocket/blob/679ce519dd0d6d3919990abdee7109a5eeb99aa0/ixwebsocket/IXWebSocketTransport.cpp#L691

The way the code is using std::vector for the receive buffer with data being added at the end and removed from the front creates a time complexity bug. When erasing at the front, vector::erase is O(N) where N is the size of the whole vec, not the size of the packet data being erased. That means that dequeuing all packets is actually O(N^2)

If for whatever reason the receive buffer grows big enough, the time to dequeue one packet can exceed the time to receive one packet at which point it's a downward spiral that cannot be recovered (the process will grind to a halt).

This is not just theoretical, I experienced it in production.

The issue can be fixed by using a different datastructure for the receive buffer, such as std::deque.

dbregman avatar Jan 06 '23 19:01 dbregman