Google Cloud Spanner UNIQUE Index Consistency
-
06-10-2020 - |
Question
As far as I understand Google Cloud Spanner is globally consistent and also fast.
Let's say I have a table with a unique username
field.
- User A in USA inserts user
johndoe
to a US Spanner node - User B in China inserts user
johndoe
to a Chinese Spanner node
Does one of them fail? If not, how fast are the queries? Or do they both succeed but later on decide that one of them is a duplicate? Or do writes with UNIQUE fields go to 1 server?
Thanks!
Solution
First, there currently isn't an option to run Cloud Spanner across continents, even though Google's internal Spanner can. The answer however is still the same, just latencies on writes, etc are different in a Regional (Multi-zone) and Global (Multi-Continent) configuration.
The trick here is that Spanner does not insert into "the node", but instead tries to reach consensus across a majority of nodes. Since we always run an odd number of nodes, one of them will reach consensus first and block the other one. This transaction will be committed, then the other transaction will fail as the row already exists.
Eric Brewer gives a good overview of how consistency is achieved in this situations in this recent article: Spanner, TrueTime & The CAP Theorem