0

I'am trying to implement kind of a matchmaking REST service for the game. My matchmaking table is simple as

ID (Serial)
Client_Name_1 (String)
Client_Name_2 (String)

Basic idea is that when client sends me his "Name" I check if there is a row with Client_Name_2 = NULL and update this row. If there is no "NULL" rows I create new row with Client_Name_1 as recieved client "Name"

Here is the router code:

post '/api/start' do
    #parsing a request with client name
    body = JSON.parse request.body.read

    #checking if there is a row to update
    t = Match.first(:Client_Name_2 => nil)

    #matchmaking client to existing game if found
    if t != nil
    t.update(
    Client_Name_2:  body['name']    
    )
    response = {:playerIs => '2', :id => t['id']} 

    #creating new game if nowhere to matchmake
    elsif 
    m = Match.create(
    Client_Name_1:      body['name']
    )

    Task.create(
    Match_ID:       m['id']
    )

    response = {:playerIs => '1', :id => m['id']} 

    end 
    status 201
    response.to_json    
end

The tricky part for me is that when this router called simultaneously at the very same second from several different clients, all of these requests get the same row id from

  #checking if there is a row to update
  t = Match.first(:Client_Name_2 => nil)

and this code updates the same row for each request.

Is there a simple solution for this or i will have to implement something like queue to handle such simultaneous requests consequentially?

I will really appreciate your advice.

Vertexwahn
  • 7,709
  • 6
  • 64
  • 90

0 Answers0