Reference library

Database scaling & optimization

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

37 matches
Database scaling & optimization medium

How to Simulate Distributed Transactions in Python with a Mock

Model distributed transaction behavior with a mock Transaction class that supports commit, rollback, and failure simulation.

transactions mock database
Python
class Transaction:
    def __init__(self, id):
        self.id = id
        self.operations = []
        self.committed = False

    def add_operation(self, op, data):
        self.operations.append((op, data))

    def commit(self):
        if not self.operations:
            raise ValueError("No operations to commit…
13 0 Open
Database scaling & optimization medium

How to Simulate a Stable Sort Cursor in Python

Build a MongoDB-style cursor mock that stably sorts records by a key while preserving original order for ties, with next() and rewind() methods.

sorting cursors database
Python
```python
import random

class CursorStableSortMock:
    """Simulates stable sorting with a cursor-like pointer for MongoDB-style queries."""
    
    def __init__(self, data, sort_key, reverse=False):
        self.data = list(data)
        self.sort_key = sort_key
        self.reverse = reverse
        self._index = …
13 0 Open
Database scaling & optimization easy

How to Validate Data Before Scaling in Python

A reusable Python helper that validates required fields and constraint checks on data rows before entering a database pipeline, improving data quality and throughput.

validation data-quality scaling
Python
def validate_data(data, required_fields, constraints=None):
    """
    Basic validation helper demonstrating data-quality workflows
    before scaling (catches bad rows early, improves throughput).
    """
    constraints = constraints or {}

    errors = []
    for field in required_fields:
        if field not in d…
15 0 Open
Database scaling & optimization easy

How to enforce a unique index constraint in Python

Mock a database unique index in Python that rejects duplicate rows based on one or more columns.

database unique index constraint
Python
class MockIndex:
    def __init__(self, columns):
        self.columns = columns
        self._values = set()

    def insert(self, row):
        key = tuple(row[col] for col in self.columns)
        if key in self._values:
            raise ValueError(f"Duplicate key {key} for columns {self.columns}")
        self._v…
14 0 Open
Database scaling & optimization medium

How to mock batch commit of transactions in Python

Simulate a transaction batch writer with commit, rollback, and summary logic to test database write patterns without a real database.

transactions mock batch
Python
import json
from datetime import datetime, timezone

class TransactionBatch:
    def __init__(self):
        self.pending = []
        self.committed = []
        self._log = []

    def add(self, operation):
        self.pending.append(operation)

    def commit(self):
        if not self.pending:
            return …
16 0 Open
Database scaling & optimization easy

How to mock directory-based sharding in Python

Simulates distributing files into logical shards using a deterministic hash of each filename, mocking how a database might shard rows across nodes.

sharding hash partitioning
Python
import os
import hashlib
from collections import defaultdict
from pathlib import Path


def get_shard_for_key(key: str, num_shards: int) -> int:
    """Return a deterministic shard index (0..num_shards-1) for a key."""
    digest = hashlib.md5(key.encode('utf-8')).hexdigest()
    return int(digest, 16) % num_shards


…
14 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 easy

Monitor Database Index Bloat in Python

Simulates index bloat checks for database tables using random ratio thresholds and reports alerts per index.

database index monitoring
Python
import random
import time

class IndexBloatMonitor:
    def __init__(self, thresholds=(0.5, 0.8, 0.9)):
        self.thresholds = thresholds
        self.indices = {
            "users_pk": 48.2,
            "orders_created_idx": 124.7,
            "products_name_idx": 15.3,
            "payments_user_idx": 203.9,
   …
15 0 Open
Database scaling & optimization medium

Offset vs Keyset Pagination in Python

Demonstrate offset-based pagination and keyset (cursor) pagination with a simple in-memory dataset, showing how each returns pages of records.

pagination keyset offset
Python
"""Demonstrate pagination using offset vs keyset (cursor) approach."""

ITEMS = [
    {"id": 1, "name": "Alice"},
    {"id": 2, "name": "Bob"},
    {"id": 3, "name": "Carol"},
    {"id": 4, "name": "David"},
    {"id": 5, "name": "Eve"},
]

def offset_paginate(items, page, page_size):
    """Return a page using offset…
14 0 Open
Database scaling & optimization easy

Route SELECT Queries to Read Replicas in Python

A mock round-robin router that forwards SELECT queries to read replicas and sends writes to the primary.

database replication routing
Python
import random

class ReadReplicaRouter:
    """Round-robin router that sends SELECT queries to read replicas."""
    
    def __init__(self, replicas):
        self.replicas = replicas
        self.counter = 0
    
    def route(self, sql):
        if sql.strip().upper().startswith("SELECT"):
            replica = sel…
13 0 Open
Database scaling & optimization easy

Simulate PostgreSQL Vacuum to Reclaim Space in Python

A Python class that safely rewrites a data file to remove deleted rows and reclaim physical space, mimicking PostgreSQL's VACUUM operation.

vacuum file-management database
Python
import shutil
import os

class VacuumCleaner:
    """Simulates PostgreSQL-style vacuum reclaiming dead space in a file."""
    
    def __init__(self, filepath, fill_ratio=0.7, dead_marker="[DELETED]"):
        self.filepath = filepath
        self.fill_ratio = fill_ratio
        self.dead_marker = dead_marker
    
  …
13 0 Open
Database scaling & optimization medium

Simulate Shard Key Cardinality in Python

Generate mock data with configurable cardinality to evaluate shard key distribution and detect hotspots in database scaling design.

sharding cardinality database
Python
import random
import string

def calculate_cardinality(values):
    """Return the number of distinct values in the given list."""
    return len(set(values))

def generate_mock_data(num_records, cardinality):
    """Generate mock records for a shard key with given cardinality."""
    possible_keys = [f"key_{i:04d}" fo…
17 0 Open
Database scaling & optimization easy

UUID vs sequential primary key in Python

Simulate and compare UUID vs sequential primary key generation in Python to understand trade-offs in ordering and uniqueness.

uuid primary-key database
Python
import uuid
import time

def create_record_with_uuid(name):
    record_id = uuid.uuid4()
    return {"id": record_id, "name": name}

def create_record_with_sequential_id(name, counter):
    counter += 1
    return {"id": counter, "name": name}

if __name__ == "__main__":
    # Simulate users inserting records
    sequ…
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.