When managing real-time data in your app, you’ll inevitably run into the dreaded merge conflict. It happens when two updates change the same thing at the exact same time and you don’t know which to use.
For example: you’re building a concert app. Users can browse upcoming events and reserve seats. Most concert data doesn’t change often, like the venue, the sponsors, and the band name, but as soon as tickets are available, all bets are off.
If the artists are popular, tickets might be gone in a matter of minutes, and there’s almost certainly going to be a conflict. Two of your clients, Bob and Carl, reserve the same seat. Normally it’s first-come first-serve, but they clicked at the same time! So, who gets the seat?
We need to show an error or success message to the clients, and store the final RSVP in the database. There can’t be any disagreement.
But we have an advantage: it doesn’t matter who we choose, so long as we make sure it’s consistent.
When clients reserve seats, they put their names on them. Gun can resolve the merge conflict using string comparison, taking the names “Bob” and “Carl”, and choosing the larger of the two. To figure out which is greater, we start with the first characters, “B” and “C”. If one is larger, we know who gets the seat, otherwise we continue until we don’t have any characters left. In this case, “C” comes after “B”, meaning Carl’s the winner, he gets the seat.
So why string comparison? Because when merge conflicts happen, it’s critical that everyone agrees on a value, otherwise your database will never reach a consistent state, and any hope of accuracy goes out the window. String comparison guarantees that every merge conflict always has a clear winner.