I have a TCP server listening, and hundreds of clients connecting to the server.
Whenever a client is connected, it sends a unique ID (say "123") to the server "X", the server "X" authenticates the unique ID "123" against the database, and if it checks out, it stores another entry in the cache to indicate that "123" is connected to server "X". This is so I can put many instances of the servers and know which client is connected to which server.
When client disconnects, the server removes the entry from the cache.
Now I am running into an issue that if a client is connecting/disconnecting all the time, there is a race condition when the event is sent to the cache. I am observing that if a client connects and disconnects repeatedly, it may show as disconnected on the server side. The disconnect may take several minutes because of timeout, flushing out and closing the TCP stream, etc, that the new connection is posted first, only to be removed later by the old connection.
How do I handle this flow to correctly store client's connected status?