Skip to content

Instantly share code, notes, and snippets.

@Dev-Dipesh
Created April 27, 2024 09:27
Show Gist options
  • Save Dev-Dipesh/231c1b17cd42337c5a4e37689a091cc0 to your computer and use it in GitHub Desktop.
Save Dev-Dipesh/231c1b17cd42337c5a4e37689a091cc0 to your computer and use it in GitHub Desktop.
Google Cloud Spanner Transaction Commit Explanation with an Example

Google Cloud Spanner Transaction Commit using True Time API

Mermaid Diagram

Imagine you're organizing a surprise party (a transaction) that needs to happen precisely at 5 PM (the commit time). However, all your friends (the database nodes) have slightly different watches, and you can't trust them to be perfectly synchronized. To avoid the surprise being ruined by someone arriving early or late, you decide to use a special app (TrueTime) that allows everyone to agree on a time window when 5 PM will definitely occur, say between 4:59 PM and 5:01 PM.

You tell your friends to be ready and in position anytime within that window, but the surprise will only start exactly at 5 PM, as determined by the app. Because of the app's accuracy, you're confident that no one will act before 4:59 PM or after 5:01 PM, and since everyone prepares in advance, the party kicks off flawlessly at 5 PM without further coordination needed. This is akin to how Spanner uses TrueTime to set a global commit timestamp that ensures all nodes can agree on the exact moment a transaction is committed, reducing the need for constant back-and-forth communication.

CleanShot 2024-04-27 at 14 53 23@2x
sequenceDiagram
    participant Organizer as Party Organizer (Transaction Coordinator)
    participant TrueTime as TrueTime API
    participant Friend1 as Friend 1 (Node 1)
    participant Friend2 as Friend 2 (Node 2)
    participant Friend3 as Friend 3 (Node 3)

    Organizer->>+TrueTime: Ask for commit time window
    TrueTime-->>-Organizer: Provides time window (4:59 PM - 5:01 PM)
    Organizer->>Friend1: Be ready between 4:59 PM - 5:01 PM
    Organizer->>Friend2: Be ready between 4:59 PM - 5:01 PM
    Organizer->>Friend3: Be ready between 4:59 PM - 5:01 PM
    Note over Friend1,Friend3: Friends prepare for the party
    
    loop Each Friend at their own time
        Friend1->Friend1: Gets ready
        Friend2->Friend2: Gets ready
        Friend3->Friend3: Gets ready
    end

    TrueTime->>Organizer: It's now officially 5 PM
    Organizer->>Friend1: Start the surprise!
    Organizer->>Friend2: Start the surprise!
    Organizer->>Friend3: Start the surprise!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment