Database scaling & optimization
Indexing, connection pooling, read replicas, query tuning, and throughput-aware SQL.
Approximate Count with HyperLogLog in Python
A mock HyperLogLog implementation uses hash-based registers to estimate cardinality of large datasets with sublinear memory.
import hashlib
class HyperLogLog:
def __init__(self, precision=4):
if precision < 4 or precision > 16:
raise ValueError("precision must be between 4 and 16")
self.precision = precision
self.registers = [0] * (1 << precision)
def _hash(self, value):
return int(hashl…
How to Count Star vs Estimate Matches in Python
Count how many times 'star' and 'estimate' annotations match their actual labels in a list of mock comparison results.
def count_star_vs_estimate(mock_scores):
"""
Count the number of times 'star' wins and 'estimate' wins
from a list of mock comparison results.
Args:
mock_scores: list of tuples, each (annotation, actual)
where annotation is 'star' or 'estimate'
Returns:
dict w…
How to Mock a Function Call in Python with unittest.mock
Use unittest.mock.Mock to wrap a function and spy on its call count and arguments in Python.
import random
from unittest.mock import Mock, patch
def select_n_plus_one(numbers: list[int]) -> int:
"""Return the first number that appears more than once, if any."""
seen = set()
for num in numbers:
if num in seen:
return num
seen.add(num)
return -1
def detect_mock(se…
How to Shard Data by User ID Hash in Python
Deterministically map user IDs to shard indexes using an MD5 hash modulo the shard count in Python.
import hashlib
def shard_id(user_id: str, num_shards: int = 4) -> int:
"""Deterministically map a user_id to a shard index using MD5."""
digest = hashlib.md5(user_id.encode("utf-8")).hexdigest()
return int(digest[:8], 16) % num_shards
if __name__ == "__main__":
user_ids = ["alice", "bob", "carol", "d…
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.