title: Firebase: How to match opponents in a game?
body: <p>I'm implementing a social chess game. Every user can create a new game, and they'll wait until the system will find an opponent for them.</p>
  
  <p>When user creates a game, they specify constraints: color they'd like to play, and opponent's minimal chess rating.</p>
  
  <p><strong>Opponents can either match or not match.</strong> For example, the following two opponents will match:</p>
  
  <pre><code>// User 1 with rating 1700              // User 2 with rating 1800
  // creates this game                    // creates this game
  game: {                                 game: { 
    color: 'white',                         minRating: 1650
    minRating: 1600                       }
  }                                       // User did not specify a preferred color,
                                          // meaning they do not care which color to play
  </code></pre>
  
  <p>So, if User 1 is the first user in the system, and created their game, they'll wait. Once User 2 creates their game, they should be matched immediately with User 1.</p>
  
  <p>On the other side, the following two opponents won't match, because they both want to play white. In this case, both should wait until someone else creates a game with <code>color: 'black'</code> (or color not specified), and <code>minRating</code> that would match the requirements.</p>
  
  <pre><code>// User 1 with rating 1700              // User 2 with rating 1800
  // creates this game                    // creates this game
  game: {                                 game: { 
    color: 'white',                         color: 'white'  
    minRating: 1600                         minRating: 1650
  }                                       }
  </code></pre>
  
  <p>My concerns related to scenarios where thousands of users creates new games at the same time. How do I make sure that I match opponents without creating deadlocks? i.e. how do I prevent scenarios when User 1, User 2, and User 3 are trying to find an opponent at the same time, and their matching algorithms return User 99. How do I recover from this scenario, assigning User 99 to only one of them?</p>
  
  <p>How would you use the power of Firebase to implement such a matching system?</p>