2

I'm trying to create a game where users are matched with each other randomly using Firebase.

My idea to match them is like this:

  1. User A comes, reads list of games. If there aren't any games waiting start game. Sets himself as initiator, opponent as null.
  2. User B comes, reads list of games. Finds User A's game (opponent is null) and joins it (he becomes the opponent)
  3. What happens if User C comes between the moment where User B read the games list and the moment User B wrote himself as the opponent (for him opponent would still be null). Basically the concurrency problem.

I've read about transactions but I'm not 100% sure they help in this case (Read games with no Opponent, Write opponent to one of the games) because I've seen them used a lot in increasing values rather than reading/writing data.

michal.jakubeczy
  • 8,221
  • 1
  • 59
  • 63
Petrescu Silviu
  • 247
  • 1
  • 11
  • 1
    Firebase had done a great talk on this subject and they did something similar to what you wanted. Watch it here: https://www.youtube.com/watch?v=8wF-mKMsynE –  Sep 11 '17 at 14:24
  • I'd also recommend Doug Stevenson's I/O talk, which has a section on matchmaking: https://www.youtube.com/watch?v=eWj6dxfN63g – Frank van Puffelen Sep 11 '17 at 14:39
  • See this: “Match-making with Firebase — Hashnode” by Shukant Pal https://link.medium.com/v00Z0PTUcU – Shukant Pal Feb 13 '19 at 01:36
  • 2
    Does this answer your question? [Randomly pairing users in Firebase](https://stackoverflow.com/questions/63713126/randomly-pairing-users-in-firebase) – Amon C Sep 04 '20 at 22:31

1 Answers1

2

Transactions blocks are used for concurrency. What they do is prevent issues when two users attempt to write to the same area at the same time. Like you said this is commonly seen with likes. So if the game currently only has 1 player and you save a value of 0 so other players know the game is "open". When a player attempts to connect to that game they write to that area and change the 0 to a 1. If another player attempted to connect at the same time their transaction block will now fire. When they get the data they will see a 1 though not a zero. At this point you back out and look for a new game. Not sure if this is the best method, but it should work.

DoesData
  • 6,594
  • 3
  • 39
  • 62