Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

29 matches
Errors & debugging medium

How to Add a Correlation ID to Logging Records in Python

Attach a unique correlation ID to every log record using a custom logging.Filter, making distributed request tracking traceable.

logging correlation-id filter
Python
import logging
import uuid
from dataclasses import dataclass, field


@dataclass
class CorrelationIdFilter(logging.Filter):
    correlation_id: str = field(default_factory=lambda: str(uuid.uuid4()))

    def filter(self, record: logging.LogRecord) -> bool:
        record.correlation_id = self.correlation_id
        re…
14 0 Open
System design patterns medium

How to implement saga orchestration with compensating steps in Python

Orchestrate a distributed transaction across services, rolling back completed steps with compensations when a later step fails.

saga distributed-transactions compensation
Python
class InventoryService:
    def reserve(self, order_id):
        print(f"[Inventory] Reserving stock for order {order_id}")
        return True

    def compensate(self, order_id):
        print(f"[Inventory] Releasing stock for order {order_id}")


class PaymentService:
    def charge(self, order_id):
        print(f…
14 0 Open
System design patterns medium

Implement a Consistent Hash Ring in Python

Build a minimal consistent hash ring with virtual nodes to map keys to servers stably as nodes are added or removed.

consistent-hashing hashing distributed-systems
Python
import hashlib
import bisect


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

    def _hash(self, key):
        return i…
15 0 Open
API design & gRPC easy

How to Propagate X-Request-ID in Python

Generate a unique request ID when one is missing and pass it through API calls for distributed tracing.

request-id tracing api
Python
import uuid


def generate_request_id() -> str:
    """Generate a unique request ID similar to X-Request-ID header."""
    return str(uuid.uuid4())


def propagate_request_id(request_id: str | None) -> str:
    """Return the request ID for propagation, generating one if missing."""
    if request_id:
        return re…
12 0 Open
Caching & Redis medium

How to implement Redlock distributed lock in Python

Simulate Redis Redlock multi-instance locking to show how a distributed lock is acquired only when a majority of instances agree.

redlock distributed-locking redis
Python
import time
import random
import threading
from dataclasses import dataclass


@dataclass
class MockRedisLock:
    """Simple mock of a Redis lock instance."""
    name: str
    key: str
    ttl: int
    acquired: bool = False
    expires_at: float = 0.0

    def acquire(self, sleep_fn=time.sleep):
        """Try to ac…
17 0 Open
Caching & Redis medium

Mock Redis Distributed Lock in Python with SET NX EX

A minimal in-memory mock of Redis SET NX EX distributed lock semantics for testing concurrent code without a real Redis server.

redis distributed-lock concurrency
Python
import time
import threading
import uuid
from typing import Optional


class RedisLockMock:
    """A minimal mock of Redis SET NX EX distributed lock semantics."""

    def __init__(self):
        self._store = {}  # key -> (value, expiry_epoch)

    def acquire(self, key: str, token: str, ttl_seconds: int) -> bool:
 …
15 0 Open
Reliability & rate limiting medium

Mock Distributed Rate Limiter with Dict in Python

Simulates a distributed token-bucket rate limiter with a thread-safe dict, useful for testing before moving to Redis.

rate-limiting token-bucket threading
Python
import time
import threading
from collections import defaultdict


class DistributedRateLimiter:
    """
    A mock distributed rate limiter using a dict with thread-safe access.
    Implements a token bucket algorithm per user.
    """

    def __init__(self, rate_per_second=5, burst_capacity=10):
        self.rate_p…
13 0 Open
Reliability & rate limiting medium

Mock a Two-Phase Commit Coordinator in Python

Simulates a two-phase commit protocol where a coordinator asks participants to prepare, then commits or aborts based on unanimous readiness.

two-phase commit distributed systems transactions
Python
import random
import time
from typing import Dict, List


class TwoPhaseCommitCoordinator:
    def __init__(self, participants: List[str]):
        self.participants = participants
        self.participant_state: Dict[str, bool] = {}

    def prepare(self) -> bool:
        print("[Coordinator] Phase 1: Prepare")
     …
12 0 Open
Reliability & rate limiting medium

Saga Compensating Transaction Mock in Python

Simulates a distributed transaction using a saga pattern with compensating actions that roll back steps on failure.

saga transaction compensation
Python
import random
import time


class OrderService:
    def __init__(self):
        self.orders = {}

    def create_order(self, order_id):
        print(f"[Order] Creating order {order_id}...")
        time.sleep(0.1)
        if random.random() < 0.3:  # 30% chance of failure
            raise RuntimeError(f"Order {order…
12 0 Open
Observability & SRE easy

How to Generate and Propagate W3C Trace Context Headers in Python

Generate and propagate W3C traceparent and tracestate headers for distributed tracing in Python, with mock service headers.

observability tracing w3c
Python
import uuid


def generate_w3c_traceparent(trace_id=None, parent_id=None, flags="01"):
    if trace_id is None:
        trace_id = uuid.uuid4().hex[:32]
    if parent_id is None:
        parent_id = uuid.uuid4().hex[:16]
    return f"00-{trace_id}-{parent_id}-{flags}"


def create_mock_headers(service_name, trace_id=N…
12 0 Open
Microservices patterns easy

Correlation ID HTTP header mock in Python

A lightweight HTTP server that echoes or generates correlation IDs to help test distributed systems.

correlation-id http-server mock
Python
import json
import uuid
from http.server import BaseHTTPRequestHandler, HTTPServer


class CorrelationHandler(BaseHTTPRequestHandler):
    CORRELATION_HEADER = "X-Correlation-ID"

    def do_GET(self):
        correlation_id = self.headers.get(self.CORRELATION_HEADER) or str(uuid.uuid4())
        response = {
        …
13 0 Open
Microservices patterns medium

Distributed tracing with contextvars in Python

Propagate trace and span IDs across function calls using contextvars to mock distributed tracing in a single process.

tracing contextvars microservices
Python
import contextvars
import uuid
import time

_trace_context = contextvars.ContextVar("trace_context", default=None)


class TraceContext:
    def __init__(self, trace_id, parent_span_id):
        self.trace_id = trace_id
        self.parent_span_id = parent_span_id
        self.span_id = uuid.uuid4().hex[:16]
        s…
13 0 Open
Microservices patterns medium

How to Implement a Two-Phase Commit Mock in Python

Simulate a distributed two-phase commit with prepare, commit, and abort phases, including deterministic failure injection for testing.

2pc transaction microservices
Python
import random
from dataclasses import dataclass
from typing import Dict, List, Optional


@dataclass
class Transaction:
    tx_id: int
    data: Dict[str, str]


class TwoPhaseCommitMock:
    """Simple two-phase commit mock with prepare and commit phases."""

    def __init__(self) -> None:
        self.prepared: List…
13 0 Open
Microservices patterns easy

How to Mock Eventual Consistency UI Notes in Python

Simulates a UI note that shows local state until a pending server update is confirmed, mocking eventual consistency behavior in distributed systems.

eventual-consistency microservices ui
Python
class EventualConsistencyNote:
    def __init__(self, entity_id, note):
        self.entity_id = entity_id
        self.note = note
        self.confirmed = False
        self.pending_updates = []

    def add_pending_update(self, update):
        self.pending_updates.append(update)

    def confirm_update(self):
    …
17 0 Open
Microservices patterns medium

How to Mock a Choreography Saga in Python

Simulate a choreography-based saga with event envelopes, status tracking, and compensating actions to model distributed transactions.

saga microservices events
Python
import json
from dataclasses import dataclass, asdict
from typing import List, Optional
from enum import Enum


class SagaStatus(Enum):
    PENDING = "PENDING"
    COMPLETING = "COMPLETING"
    COMPLETED = "COMPLETED"
    FAILED = "FAILED"


@dataclass
class EventEnvelope:
    event_type: str
    order_id: str
    sta…
13 0 Open
Microservices patterns medium

Python Saga Compensating Steps Mock

Mock a distributed transaction saga with forward steps and compensating actions that reverse partial progress on failure.

saga microservices compensation
Python
from datetime import datetime


def make_payment(user_id, amount):
    print(f"[{datetime.now():%H:%M:%S}] Payment of ${amount} processed for user {user_id}")
    return {"step": "payment", "status": "ok", "details": f"${amount} charged"}


def deduct_inventory(order_id, items):
    print(f"[{datetime.now():%H:%M:%S}]…
14 0 Open
Microservices patterns medium

Saga pattern orchestration with rollback in Python

Orchestrate a distributed transaction with Saga steps and automated compensation rollback on failure.

saga microservices transaction
Python
import time
import random


class SagaStep:
    def __init__(self, name):
        self.name = name
        self.executed = False

    def execute(self):
        print(f"Executing {self.name}...")
        time.sleep(0.2)
        if random.random() < 0.3:
            raise RuntimeError(f"{self.name} failed")
        sel…
14 0 Open
Microservices patterns easy

Scatter Gather Aggregate Pattern in Python

Simulates a scatter/gather/aggregate pattern by distributing work across items, gathering results, and aggregating them.

scatter-gather aggregation pattern
Python
import random

def process_items(items, scatter_fn, gather_fn, aggregate_fn):
    """Simple scatter/gather/aggregate pattern simulation."""
    scattered = [scatter_fn(item) for item in items]
    gathered = [gather_fn(item) for item in scattered]
    return aggregate_fn(gathered)

if __name__ == "__main__":
    data …
13 0 Open
Big data & Spark medium

Skew Join Salting Key in Python (Demo)

Demonstrates skew join salting by expanding a smaller side with salt keys and matching rows on the larger side via random salt assignment.

skew join salting distributed
Python
import random


def skew_join_salting_key(left_df, right_df, salt_range=4):
    """
    Demonstrates skew join salting: expand the smaller side with salt keys,
    then attach a salt key to each row on the larger side.
    Returns a list of (left, right, salt) tuples.
    """
    skewed_left = []
    for row in left_d…
14 0 Open
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 easy

How to Replicate Data Across All Shards in Python

Mocks a global table that replicates a key-value pair to every shard, ensuring reads return the same value from any shard.

sharding replication distributed systems
Python
from dataclasses import dataclass
from typing import Dict, List


@dataclass
class Shard:
    id: str
    data: Dict[str, int]


class GlobalTable:
    def __init__(self, shards: List[Shard]):
        self._shards = {s.id: s for s in shards}

    def set_value(self, key: str, value: int) -> None:
        """Replicate …
14 0 Open

Browse by section

Each section groups closely related Python snippets.

Guide: free Python code samples library

Copy-ready Python snippets for learners and developers

PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.

How to use this library

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. Run it in the IDE, tweak values, then take a related quiz or tutorial lesson

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.