Distributed Queries, Transactions, and Consistency

16 min read

Welcome back to the freeCodeCamp database optimization track! In the previous modules, you learned how to slice a monolithic database into multiple shards. Your write volume scaled, storage headaches disappeared, and everything seemed peaceful.

Then, your product manager walked in and asked:

"Can we run a query that joins our users shard with our orders shard, calculates the global average basket size, paginates page 5,000, and ensures the whole financial checkout happens with strict ACID guarantees across three different database clusters?"

You stared into the middle distance. Because in a single database, this is Tuesday afternoon SQL. In a sharded database, this is a distributed systems minefield.

In this guide, you will learn how distributed queries, distributed transactions, and data consistency actually work in high-throughput industry architectures—along with what is physically possible, what is strictly impossible, and the engineering compromises required in between.


🧭 System Boundaries: What Sharding Gives You vs. What It Breaks

Before writing code, let's establish the architectural boundaries.

  • What is possible: Horizontal linear scale for single-shard read/write operations (e.g., retrieving orders WHERE customer_id = 42 when sharded by customer_id).
  • What is expensive: Scatter-gather queries across all shards, multi-shard aggregations, and cursor-based cross-shard pagination.
  • What is impossible (by laws of physics and information theory): Zero-latency cross-region atomic distributed transactions with 100% uptime during network partitions.

Every pattern below is an explicit trade-off designed to work within these boundaries.


SubTopic 1: Executing Cross-Shard Joins, Aggregations, and Pagination 🔍

The Problem

When tables are split across physical nodes (e.g., Shard-01 holds users 1–1,000,000 and Shard-02 holds users 1,000,001–2,000,000), a single database engine can no longer walk a local B-Tree index to perform a join or calculate an aggregation. The data lives in separate memory spaces on different physical servers.

scss
       [ Client / API Gateway ]
                  │
        [ Query Coordinator / Router ]
        ┌─────────┴─────────┐
        ▼                   ▼
    [ Shard 01 ]        [ Shard 02 ]
  (Users 1 - 1M)     (Users 1M+ - 2M)

1. Cross-Shard Joins

Executing SELECT * FROM users u JOIN orders o ON u.id = o.user_id across shards will grind your cluster to a halt if tackled naively. In production, teams handle this using three distinct patterns:

A. Co-located Sharding (The Golden Path)

Ensure related records live on the exact same physical shard by sharing a Sharding Key (also known as a Partition Key).

  • If both users and orders use user_id as their shard key, all orders for User 42 reside on the same shard as User 42.
  • Result: The join executes locally on that specific shard with zero network overhead.

B. Broadcast / Reference Tables

Small, rarely changing lookup tables (e.g., countries, tax_rates, currency_codes) are replicated in their entirety to every single shard.

  • Result: Any shard can join its local data against the lookup table locally.

C. Two-Stage Application-Side / Coordinator Joins

If data cannot be co-located (e.g., joining products and merchants where both have distinct sharding keys), the query coordinator or your backend service must fetch both sets and join them in memory.

python
# Simulated Coordinator Fetch
# 1. Fetch orders from the orders shard cluster
orders = db_router.query("orders_cluster", "SELECT id, product_id, amount FROM orders WHERE user_id = ?", user_id)
product_ids = [order['product_id'] for order in orders]

# 2. Fetch the matched products in batch using an IN-clause
products = db_router.query("products_cluster", "SELECT id, title, price FROM products WHERE id IN (?)", product_ids)

# 3. Stitch in memory
product_map = {p['id']: p for p in products}
for order in orders:
    order['product'] = product_map.get(order['product_id'])

2. Distributed Aggregations: Scatter-Gather

Aggregations fall into three mathematical categories, each with varying complexity in distributed systems:

Aggregation Type SQL Functions How It Works in Sharded Environments
Distributive COUNT, SUM, MIN, MAX Easy: Every shard runs the query locally; coordinator sums the sums or finds the max of maxes.
Algebraic AVG Moderate: A shard cannot just return its local AVG. It must return SUM and COUNT. The coordinator calculates: ∑(all sums)∑(all counts)\frac{\sum(\text{all sums})}{\sum(\text{all counts})}.
Holistic MEDIAN, PERCENTILE_CONT Brutal: Shards cannot easily summarize percentiles without shipping massive raw distributions. Solved using probabilistic algorithms like t-digest or HyperLogLog.

Scatter-Gather Engine Execution Flow

pgsql
Client: SELECT AVG(price) FROM items;
   │
   ├─► Shard 1: SELECT SUM(price) as s1, COUNT(price) as c1;  ──► Returns (1000, 20)
   ├─► Shard 2: SELECT SUM(price) as s2, COUNT(price) as c2;  ──► Returns (3000, 40)
   │
Coordinator: Total Sum = 4000, Total Count = 60. AVG = 4000 / 60 = 66.66

3. The Deep Pagination Trap (OFFSET vs. Cursor)

Consider this query sent to a coordinator managing 10 shards:

sql
SELECT * FROM audit_logs ORDER BY created_at DESC LIMIT 20 OFFSET 10000;

Why Naive Offset Breaks Sharded Systems

To give you rows 10,001 through 10,020 globally, every single shard must fetch its local top 10,020 rows and send them to the coordinator.

  • Network payload: 10 shards×10,020 rows=100,200 rows10 \text{ shards} \times 10,020 \text{ rows} = 100,200 \text{ rows} sent across the internal network.
  • The coordinator sorts all 100,200 rows in memory, discards 100,180 of them, and returns 20 to the client.
  • At OFFSET 1000000, your coordinator will run out of memory.

The Production Fix: Keyset (Cursor-Based) Pagination

Instead of an offset, sort by an indexed deterministic composite key (e.g., (created_at, id)):

sql
-- Client requests the next page after receiving cursor: (2026-03-31 10:00:00, log_98412)
SELECT * FROM audit_logs 
WHERE (created_at, id) < ('2026-03-31 10:00:00', 'log_98412')
ORDER BY created_at DESC, id DESC 
LIMIT 20;
  • Why this works: Every shard fetches only 20 rows using a local B-Tree index scan.
  • The coordinator gathers at most 10×20=20010 \times 20 = 200 rows, sorts 200 items, and yields the top 20. The resource cost is constant O(1)O(1) regardless of how deep the user paginates.

Scope Boundary: Arbitrary, random-access page jumping (e.g., "Jump directly to page 8,412") is essentially unscalable across massive sharded clusters without generating heavy, dedicated secondary index stores (like Elasticsearch or Apache Pinot).


SubTopic 2: Two-Phase Commit (2PC) vs. Saga Pattern for Distributed Transactions 🔄

The Problem

In a single database, transactions follow ACID properties. The database engine writes to the Write-Ahead Log (WAL), locks records, commits, and releases locks in microseconds.

In a sharded architecture, an operation like "Deduct 100fromAlice(ShardA)anddeposit100 from Alice (Shard A) and deposit 100 to Bob (Shard B)" requires coordinating multiple independent database processes over unreliable network cables. If Shard A succeeds and Shard B crashes, Alice's money vanishes into the ether.


Option 1: Two-Phase Commit (2PC)

2PC is a strongly consistent (ACID) protocol managed by a central Transaction Coordinator.

css
       Coordinator               Shard A (Alice)            Shard B (Bob)
           │                           │                          │
           │── 1. PREPARE ────────────►│                          │
           │── 1. PREPARE ───────────────────────────────────────►│
           │                           │                          │
           │◄── VOTE_COMMIT ───────────│                          │
           │◄── VOTE_COMMIT ──────────────────────────────────────│
           │                           │                          │
   [All voted YES]                     │                          │
           │── 2. GLOBAL_COMMIT ──────►│ (Writes to WAL & Unlock) │
           │── 2. GLOBAL_COMMIT ─────────────────────────────────►│ (Writes to WAL & Unlock)
           ▼                           ▼                          ▼
  1. Phase 1 (Prepare): The coordinator asks each participant: "Can you commit this change?" Each shard acquires locks, checks constraints, writes the pending data to its local undo/redo log, and votes VOTE_COMMIT or VOTE_ABORT.
  2. Phase 2 (Commit): If all shards voted yes, the coordinator sends GLOBAL_COMMIT. If even one shard votes no (or times out), the coordinator sends GLOBAL_ABORT, rolling back all shards.

The Reality of 2PC in Modern High-Scale Systems

2PC guarantees linearizable atomicity, but it is notoriously disliked in massive distributed web applications for a critical reason: it is a blocking protocol.

  • While Shard A is waiting for Phase 2, it holds row locks.
  • If the coordinator crashes or the network partitions between Phase 1 and Phase 2, Shard A must keep those locks held indefinitely. Other queries pile up, connection pools exhaust, and your entire database cascades into failure.

⚠️ Industry Rule of Thumb: Use 2PC only within specialized distributed SQL engines that use consensus layers (like Google Spanner, CockroachDB, or YugabyteDB via Raft/Paxos). Avoid implementing manual 2PC across separate application databases.


Option 2: The Saga Pattern

Instead of locking records across shards simultaneously, a Saga splits a distributed transaction into a sequence of local transactions across services or shards.

Each step commits locally and releases database locks immediately. If a step fails downstream, the Saga issues Compensating Transactions that backtrack and undo previous steps semantically.

pgsql
Step 1: Shard A [Deduct $100 from Alice] -> Committed! (Lock released)
Step 2: Shard B [Deposit $100 to Bob]   -> Failed! (Account frozen/closed)
Step 3: Compensation on Shard A [Refund $100 to Alice] -> Committed!

Orchestration vs. Choreography

  • Choreography (Event-Driven): Shard A emits an event AliceDeducted. Shard B listens, tries to credit Bob, fails, and emits BobCreditFailed. Shard A listens and triggers refund logic.
    • Trade-off: Good for small flows; turns into unmaintainable "spaghetti architecture" when operations involve more than 3–4 steps.
  • Orchestration (Centralized Controller): A dedicated state machine (using engines like Temporal, AWS Step Functions, or custom workers) directs each shard directly.
python
# Simplified Saga Orchestration Worker Pattern
class MoneyTransferSaga:
    def __init__(self, coordinator_db, shard_a_client, shard_b_client):
        self.db = coordinator_db
        self.shard_a = shard_a_client
        self.shard_b = shard_b_client

    def execute(self, transfer_id, from_user, to_user, amount):
        # Step 1: Debit Alice locally
        self.shard_a.execute("UPDATE accounts SET balance = balance - %s WHERE id = %s", (amount, from_user))
        self.db.log_step(transfer_id, step="DEBIT_SOURCE", status="SUCCESS")

        try:
            # Step 2: Credit Bob locally
            self.shard_b.execute("UPDATE accounts SET balance = balance + %s WHERE id = %s", (amount, to_user))
            self.db.log_step(transfer_id, step="CREDIT_DEST", status="SUCCESS")
            return {"status": "COMPLETED"}
        except Exception as error:
            # Step 2 Failed! Run Compensation Step
            self.db.log_step(transfer_id, step="CREDIT_DEST", status="FAILED")
            self.compensate_debit(from_user, amount)
            self.db.log_step(transfer_id, step="COMPENSATION", status="COMPLETED")
            return {"status": "FAILED_AND_REFUNDED", "reason": str(error)}

    def compensate_debit(self, from_user, amount):
        # Semantic inverse operation
        self.shard_a.execute("UPDATE accounts SET balance = balance + %s WHERE id = %s", (amount, from_user))

Comparison Matrix

Feature Two-Phase Commit (2PC) Saga Pattern
Consistency Immediate / Strict ACID Eventual / BASE
Lock Duration Entire duration of distributed roundtrip Microseconds (per local transaction)
Isolation High (prevents dirty reads across steps) None (Intermediate states are visible to users)
Fault Tolerance Low (blocks on coordinator failure) High (retries & compensations resume cleanly)

Scope Boundary: Sagas break isolation. While Alice has been debited and Bob has not yet been credited, an external analytics job reading both shards will observe that $100 has temporarily vanished from the system. Your domain logic must be resilient to these temporary states.


SubTopic 3: Distributed Unique ID Generation 🪪

The Problem

On a single MySQL or PostgreSQL node, you slap AUTO_INCREMENT or BIGSERIAL on the primary key and call it a day.

In a sharded system with 16 shards, if Shard 1 and Shard 2 both independently generate id = 1001, your primary keys collide when data moves, aggregates, or links between systems. Centralizing ID generation into one SQL instance creates a single point of failure and bottleneck that defeats the purpose of sharding.

crmsh
       [ Shard 1 ] ──► inserts order (id: 1001) ──┐
                                                  ├──► COLLISION!
       [ Shard 2 ] ──► inserts order (id: 1001) ──┘

Three primary patterns solve this at scale:


1. Auto-Increment with Step Allocations (The Cluster Offset Method)

Configure each database instance's sequence generator to increment by the total number of shards (NN) with a distinct offset (kk):

  • Shard 1 (k=1,N=3k=1, N=3): Generates IDs: 1, 4, 7, 10, 13...

  • Shard 2 (k=2,N=3k=2, N=3): Generates IDs: 2, 5, 8, 11, 14...

  • Shard 3 (k=3,N=3k=3, N=3): Generates IDs: 3, 6, 9, 12, 15...

  • Pros: Built into database engines without external tools.

  • Cons: Adding a 4th shard requires re-indexing or complex re-allocation of offsets across the entire fleet.


2. Twitter Snowflake (Bit-Packed 64-bit Integer)

Twitter Snowflake generates 64-bit signed integers that fit into a standard SQL BIGINT. Crucially, they are roughly time-ordered (k-sorted), meaning new inserts hit the right-most edge of B-Tree indexes, avoiding index fragmentation.

tap
 1 bit   41 bits (Millisecond Timestamp)     10 bits (Worker ID)    12 bits (Sequence)
┌──────┬────────────────────────────────────┬─────────────────────┬────────────────────┐
│  0   │ 011110110101010101111011010101010  │     0101100010      │    000000000001    │
└──────┴────────────────────────────────────┴─────────────────────┴────────────────────┘
       ▲                                    ▲                     ▲
     Sign bit                            Node/Shard ID         Up to 4,096 IDs
                                         (0 to 1023)           per millisecond

Implementation in Python

python
import time

class SnowflakeGenerator:
    def __init__(self, node_id: int, epoch: int = 1704067200000): # Jan 1, 2024
        self.node_id = node_id
        self.epoch = epoch
        self.sequence = 0
        self.last_timestamp = -1

    def next_id(self) -> int:
        timestamp = int(time.time() * 1000)

        if timestamp < self.last_timestamp:
            # NTP drift detected: Clock moved backwards!
            raise RuntimeError("Clock moved backwards. Refusing to generate ID.")

        if timestamp == self.last_timestamp:
            self.sequence = (self.sequence + 1) & 0xFFF  # 12-bit mask: max 4095
            if self.sequence == 0:
                # Sequence exhausted for this millisecond; spin-wait for next ms
                while timestamp <= self.last_timestamp:
                    timestamp = int(time.time() * 1000)
        else:
            self.sequence = 0

        self.last_timestamp = timestamp

        # Bitwise packing
        return (
            ((timestamp - self.epoch) << 22) |
            (self.node_id << 12) |
            self.sequence
        )

gen = SnowflakeGenerator(node_id=42)
print("Snowflake ID:", gen.next_id())
  • Pros: Compact (8 bytes), fits cleanly in native integer types, preserves write locality in B-Trees.
  • Cons: Requires a registry (e.g., Kubernetes StatefulSets, Consul, ZooKeeper) to ensure no two nodes share a node_id. Prone to issues if system clocks drift backwards.

3. UUIDv7 (RFC 9562 Standard)

Historically, engineers used UUIDv4, which generates 128 random bits (e.g., f47ac10b-58cc-4372-a567-0e02b2c3d479).

Because UUIDv4 is completely random, inserting millions of records into a table indexed by a UUIDv4 primary key results in B-Tree Index Thrashing—the database engine constantly splits index pages and flushes random disk pages to memory, killing write throughput.

UUIDv7 (formalized in RFC 9562) fixes this by embedding a 48-bit Unix timestamp at the front of the 128-bit identifier, followed by random bits for uniqueness.

asciidoc
 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                           unix_ts_ms                          | (48 bits)
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|          unix_ts_ms           |  ver (0111)   |   rand_a      |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|var(10)|                        rand_b                         | (62 bits)
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
sql
-- PostgreSQL 17+ / Modern distributed DBs
-- Sortable, non-colliding, zero coordination needed between app servers!
SELECT gen_random_uuid(); -- UUIDv7 functions natively supported in modern engines
  • Pros: Standardized, requires zero worker coordination (unlike Snowflake), highly friendly to B-Tree caches.
  • Cons: 128 bits (16 bytes) vs. Snowflake's 64 bits (8 bytes). Consumes roughly double the space in secondary indexes.

SubTopic 4: CAP Theorem Tradeoffs and Eventual Consistency in Sharded Systems ⚖️

The Problem

You have two database shards replicating data between AWS us-east-1 (Virginia) and eu-central-1 (Frankfurt). Undersea fiber cables occasionally get severed by errant anchors, causing a network partition. What happens to your sharded application when Shard 1 can no longer talk to Shard 2?


The Reality of the CAP Theorem

Eric Brewer’s CAP Theorem states that a distributed system can guarantee at most two out of three properties:

  • Consistency (CC): Every read receives the most recent write or an error.
  • Availability (AA): Every non-failing node returns a non-error response (without guaranteeing it contains the latest write).
  • Partition Tolerance (PP): The system continues to operate despite arbitrary network dropped packets or splits.
nix
                   P (Partition Tolerance)
                      /                  \
                     /                    \
     [ Network partition happens! ]   [ Pick your survival strategy ]
                   /                        \
                  ▼                          ▼
           CP (Consistency)           AP (Availability)
      Refuse writes/reads until      Accept writes/reads on both sides.
      split heals to avoid stale     Reconcile later (Eventual Consistency).
      or conflicting data.           Risk: Split-Brain / Data divergence.

The Hard Truth: In real-world physical networks, you cannot "choose" CA. Network interruptions are a physical reality of distributed infrastructure (PP is mandatory). Your actual choice is: When a Partition occurs, do you choose Consistency (CPCP) or Availability (APAP)?


PACELC: Beyond Basic CAP

Computer scientist Daniel Abadi noted that CAP only describes what happens during an active failure. But systems run normally 99.9% of the time!

The PACELC Theorem extends CAP:

If P (Partition), choose A∨C;Else, choose L (Latency)∨C (Consistency).\text{If } \mathbf{P} \text{ (Partition)}, \text{ choose } \mathbf{A} \lor \mathbf{C}; \quad \mathbf{E} \text{lse}, \text{ choose } \mathbf{L} \text{ (Latency)} \lor \mathbf{C} \text{ (Consistency)}.
  • MongoDB / Spanner (PC/EC): Prefers consistency during partitions; prefers consistency during normal times (pays a latency cost waiting for replica acknowledgments).
  • Cassandra / DynamoDB (PA/EL): Prefers availability during partitions; prefers low latency during normal times (returns reads quickly, even if a replica hasn't caught up yet).

Practical Consistency Models in Sharded Backends

Most consumer systems choose Eventual Consistency. But "eventual" can cause terrible user experiences if unmanaged. Teams apply these specific guarantees:

1. Read-Your-Own-Writes Consistency (Session Consistency)

A user posts a comment on an article. If their next request routes to a read replica that is 200ms behind, their comment is missing. The user panics and clicks "Submit" five more times.

The Solution: Route reads to the primary shard for a short time window following any write by that user, or attach the write's Log Sequence Number (LSN) to the client's session cookie.

pgsql
[ Client Writes Comment ] ──► [ Primary Shard ] (Writes at LSN: 4501)
                                      │
Client stores cookie: `last_write_lsn = 4501`
                                      │
[ Client Reads Feed ]   ──► [ Gateway Router ]
                                      │
                     Is Replica caught up to LSN 4501?
                      ├── YES: Route read to Replica
                      └── NO:  Route read to Primary (or wait)

2. Conflict Resolution: LWW vs. CRDTs

When two shards accept conflicting updates during a network partition, how do they merge?

  • Last-Write-Wins (LWW): Uses the wall-clock timestamp of the update. The newest timestamp overrides the older one.
    • Flaw: Clock skew can silently erase legitimate customer writes.
  • Conflict-Free Replicated Data Types (CRDTs): Data structures designed with mathematical properties (associative, commutative, and idempotent) so that updates can be applied in any order across shards and arrive at the exact same state.
    • Example: A Grow-Only Counter (G-CounterG\text{-}\text{Counter}) where each shard tracks its own increments independently:Global Count=∑(Shard1,Shard2,…,Shardn)\text{Global Count} = \sum(\text{Shard}_1, \text{Shard}_2, \dots, \text{Shard}_n)

🛠️ Summary & Engineering Best Practices

  1. Query Alignment: Co-locate tables by a shared sharding key whenever possible to turn expensive cross-shard joins into local operations.
  2. Scatter-Gather Restraint: Keep scatter-gather queries off customer-facing critical paths. Offload heavy analytic summaries to analytical warehouses or column stores (ClickHouse, BigQuery).
  3. Cursor Navigation: Avoid OFFSET for pagination across shards. Adopt deterministic keyset cursors.
  4. Prefer Sagas to 2PC: Avoid blocking 2PC across disparate microservices or manual shards; adopt orchestrator-driven Sagas with compensating logic.
  5. Modern IDs: Migrate from random UUIDv4 to UUIDv7 or Snowflake IDs to protect your B-Tree index caches from write fragmentation.
  6. Embrace PACELC: Choose your consistency model consciously. Provide session consistency so users always read their own updates.

📚 References & Recommended Reading

Challenge

Conceptual Challenge: Sharding Trade-offs and Patterns

This is a conceptual challenge to test your understanding of distributed database sharding patterns. Based on the summary, answer the following questions by filling in the blank lines in the editor. Do not write code – just provide short explanations or lists. Your answers will be evaluated for correctness and completeness.

Expected result

Your answers will be evaluated by an LLM for correctness based on the provided summary. No code execution is required.

plain text

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.