Khabbab Zakaria
Khabbab Zakaria

Reputation: 61

How to reduce pressure on server for when client calls APIs every moment

I am working on a game development with pygame. It is multiplayer simple card game. So, each time Player 1 does something, lets say getting a new card from the deck, an API is used to POST to the server. And I am using GET APIs every moment to make sure player 1 gets every action of player 2 and vice versa. For example, when player 2 gets a new card, an API is POSTed to the server and player 1 uses GET to receive its information. So player 1 understands that player 2 got the new card.

The problem here is, I am calling some APIs every moment of the game. And there can be many such {player 1, player 2} duo. Thus it is a heavy pressure on the server. Also, it is a pressure on the client too if they use an old machine.

I am thinking what can be a better idea to do it.

Here is a simple snippet to understand:

server.py:
r = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
@app.route('/game_state/<game_code>', methods=['GET', 'POST'])
def game_state_view(game_code):
    """Fetch or update the game state for a specific game."""
    if request.method == 'POST':
        data = request.json
        r.set(f'game_state:{game_code}', str(data))  # Save to Redis
        return jsonify(data)
    
    # Fetch the game state from Redis
    game_state = r.get(f'game_state:{game_code}')
    if game_state:
        return jsonify(eval(game_state))  # Convert string back to dict
    return jsonify({"error": "Game not found"})

player.py:
while running:
        clock.tick(FPS)
        try:
            response_state = requests.get(urlFull + f"/game_state/{game_code}")
        except:
            pass
        response_state.raise_for_status()
        game_state = response_state.json()    

Upvotes: -2

Views: 22

Answers (0)

Related Questions