Reference library

Database scaling & optimization

Indexing, connection pooling, read replicas, query tuning, and throughput-aware SQL.

7 matches
Database scaling & optimization medium

Cross Shard Query Scatter Gather Mock in Python

Simulate a distributed database cross-shard query using a scatter-gather pattern with a mock Python implementation.

scatter-gather sharding distributed-systems
Python
from dataclasses import dataclass
from typing import List, Dict


@dataclass
class NodeResponse:
    node_id: int
    data: Dict[str, float]


def mock_query_shard(shard_id: int, shard_data: Dict[str, float], query: str) -> NodeResponse:
    """Simulate querying a single shard, returning matches whose value > 50."""
 …
13 0 Open
Database scaling & optimization medium

How to Implement Consistent Hashing in Python

Build a consistent hash ring in Python that distributes keys across nodes and minimizes remapping when nodes are added or removed.

consistent-hashing distributed-systems sharding
Python
import hashlib
from bisect import bisect_right


class ConsistentHashRing:
    def __init__(self, nodes, replicas=3):
        self.replicas = replicas
        self.ring = {}
        self.sorted_keys = []
        for node in nodes:
            self.add_node(node)

    def _hash(self, key):
        return int(hashlib.md…
15 0 Open
Database scaling & optimization medium

How to Mock a Cross-Shard Saga in Python

Simulate a distributed saga with compensating transactions across multiple database shards using a lightweight Python class that tracks executed steps and rolls them back in reverse on failure.

saga sharding distributed-systems
Python
import json


class SagaState:
    def __init__(self, saga_id):
        self.saga_id = saga_id
        self.executed_steps = []
        self.compensations = []

    def execute_step(self, shard, step_name, operation):
        self.executed_steps.append((shard, step_name))
        print(f"[Saga {self.saga_id}] Executin…
14 0 Open
Database scaling & optimization medium

How to Mock a Hot Shard Split in Python

Simulate a database hot shard splitting into two shards by key ranges when it exceeds a threshold, with a mock class for testing.

sharding databases mock
Python
import random
from collections import defaultdict


class HotShardMock:
    """Mock implementation of a hot shard split in a distributed database."""

    def __init__(self, shard_id="shard_1", max_entries=5):
        self.shard_id = shard_id
        self.max_entries = max_entries
        self.entries = {}

    def ad…
16 0 Open
Database scaling & optimization medium

How to Simulate Colocated Shard Joins in Python

Groups shards by their node and merges co-located shards into a single logical unit, checking capacity constraints.

sharding database distributed-systems
Python
import random
from collections import defaultdict


def simulate_colocated_shards_join(nodes: list[dict], shards: list[dict]) -> dict:
    """
    Simulates the join of co-located shards (on the same node) into a single
    logical shard. Returns the resulting node-to-shard mapping.

    Each node: {'id': str, 'capaci…
11 0 Open
Database scaling & optimization medium

Idempotent Writes for Sharded Databases in Python

Implement a mock shard with idempotent write support using request IDs to prevent duplicate writes and track the latest value per key.

idempotency sharding distributed-systems
Python
import json


class ShardMock:
    """Mock distributed shard with idempotent write support."""

    def __init__(self, shard_id):
        self.shard_id = shard_id
        self._store = {}

    def write(self, key, value, request_id):
        """Write value only if request_id not yet processed; idempotent."""
        i…
13 0 Open
Database scaling & optimization medium

Two Phase Commit Cross Shard Mock in Python

Simulates a two-phase commit across shards with failure handling to demonstrate distributed transaction coordination in Python.

two-phase-commit distributed-systems transaction
Python
"""Mock cross-shard two-phase commit with caution handling."""

class Shard:
    def __init__(self, name):
        self.name = name
        self.prepared = False
        self.committed = False
        self.aborted = False

    def prepare(self):
        # Simulate potential failure (1 in 3 chance on third shard)
     …
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Database scaling & optimization — Python code examples

What you will find here

This page collects database scaling & optimization snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.