Handling Simultaneous Messages in a Telegram Bot

I’m developing a contest bot and encountered an issue: when two participants submit their answers nearly at the same moment, both are awarded a point and the bot advances to the next question. I need the system to credit only the fastest responder. Can someone suggest how to resolve this? Here’s an alternative code snippet to illustrate the approach:

def select_fastest_answer(entries, correct_val):
    valid_entries = [e for e in entries if e.get('reply') == correct_val]
    if valid_entries:
        quickest = min(valid_entries, key=lambda e: e.get('timestamp'))
        return quickest.get('user_id')
    return None

# Example:
responses = [
    {'user_id': 201, 'reply': 'answer', 'timestamp': 1020},
    {'user_id': 202, 'reply': 'answer', 'timestamp': 1010}
]
winner = select_fastest_answer(responses, 'answer')
print('Winner:', winner)

hey, try using an atomic update in your db. i used a flag that gets set only on the first correct response, so any near-simultaneous requests fail to update. it worked well in my case. hope this helps!

I encountered a similar issue while working on a quiz bot. I had to implement a mechanism that prevents multiple updates when responses come in almost simultaneously. In my project, I opted for using a locking approach where the first message gets a lock and subsequent messages are disregarded until the operation completes. I also experimented with carefully designing the message queue to maintain order and prevent race conditions. This method worked reliably to acknowledge only the fastest responder while maintaining overall system stability.