Reference library

Production deployment patterns

Graceful shutdown, prod config, rollouts, readiness probes, and ship-with-confidence checks.

16 matches
Production deployment patterns medium

Auto Rollback on Error Rate Exceeded in Python

Simulate a service that monitors a rolling window of request errors and automatically rolls back when the error rate exceeds a threshold.

error-rate rollback rolling-window
Python
import random
import time


def simulate_requests(total_requests=1000, rollback_threshold=0.2):
    """
    Simulate a service that automatically rolls back when the error rate
    exceeds a threshold within a rolling window.
    """
    window_size = 100
    errors_seen = []
    rolled_back = False

    for req_num i…
15 0 Open
Production deployment patterns medium

Automate Semantic Versioning with Conventional Commits in Python

Automatically bump a semantic version based on conventional commit messages (feat, fix, BREAKING CHANGE) and write the new version to a file.

semantic-versioning conventional-commits automation
Python
import re
from pathlib import Path


def get_next_version(current: str, commit_messages: list[str]) -> str:
    """Return the next semantic version based on conventional commit messages."""
    major, minor, patch = map(int, current.split("."))
    if any(msg.startswith("BREAKING CHANGE") for msg in commit_messages):
…
14 0 Open
Production deployment patterns medium

How to Build a GitOps Argo CD Sync Mock in Python

Simulate Argo CD-style GitOps deployment sync with Python dataclasses, random success rates, and force-sync retry logic.

gitops argo-cd deployment
Python
import random
import time
from dataclasses import dataclass, field
from typing import List, Dict


@dataclass
class Application:
    name: str
    source_repo: str
    target_revision: str
    synced: bool = False
    health_status: str = "Healthy"
    history: List[Dict] = field(default_factory=list)

    def sync(se…
13 0 Open
Production deployment patterns medium

How to Drain a Connection Pool Before Exit in Python

Gracefully close all pooled sockets using a thread-safe ConnectionPool that drains connections before program exit.

connection-pool sockets threading
Python
import socket
import threading
import time
import random

class ConnectionPool:
    def __init__(self, size=5):
        self.pool = []
        self.lock = threading.Lock()
        self.closed = False
        for _ in range(size):
            self.pool.append(self.create_connection())
    
    def create_connection(sel…
13 0 Open
Production deployment patterns medium

How to Expand a Contract and Migrate Data in Python

Expand an old data contract by renaming fields and adding defaults, then migrate to a final version with deepcopy isolation.

contract migration deepcopy
Python
import json
from copy import deepcopy

# Mock data representing a user record (old contract)
old_contract = {
    "id": 1,
    "name": "Alice",
    "email": "alice@example.com",
    "age": 30,
    "status": "active"
}

# Expanded contract: adds fields with defaults and renames some fields
expand_rules = {
    "id": "u…
14 0 Open
Production deployment patterns medium

How to Mock Canary Deployment Traffic Split in Python

Simulate a canary deployment's stable/canary traffic split using deterministic request hashing to mock rollout behavior with precise percentage control.

canary-deployment traffic-split simulation
Python
class CanaryDeployment:
    def __init__(self, stable_weight: float = 0.9, canary_weight: float = 0.1):
        self.stable_weight = stable_weight
        self.canary_weight = canary_weight
        self.total_weight = stable_weight + canary_weight

    def route_request(self, request_id: int) -> str:
        """Route …
13 0 Open
Production deployment patterns medium

How to Mock Image Signing Cost in Python

Create a deterministic mock signing cost calculator that predicts resource usage for image signatures before real signing infrastructure is staged.

mock signing cost-model
Python
import math
import struct


def sign_image_cost(image_signature: bytes) -> int:
    """Deterministic mock signing cost based on image signature bytes."""
    if not image_signature:
        raise ValueError("Empty image signature")
    digest = 0
    for byte in image_signature:
        digest = (digest * 31 + byte) &…
13 0 Open
Production deployment patterns medium

How to Mock Kubernetes Secret Mounts in Python

Create and inspect a mock Kubernetes secret volume mount using the official client library and unittest.mock.

kubernetes mock testing
Python
import json
from kubernetes import client, config, watch
from unittest.mock import Mock, patch

def create_mock_mount_spec():
    """Create a mock Kubernetes secret volume mount."""
    mock_client = Mock()
    mock_client.api_version = "v1"
    mock_client.kind = "Secret"
    mock_client.metadata = {"name": "my-secre…
13 0 Open
Production deployment patterns medium

How to Mock Kubernetes Services with a ClusterIP Registry in Python

Simulate Kubernetes service discovery by assigning ClusterIP addresses to dataclass-defined services, with JSON export for inspection or testing.

kubernetes clusterip mock
Python
import json
from dataclasses import dataclass, asdict
from typing import Dict, Optional


@dataclass
class Service:
    name: str
    namespace: str
    cluster_ip: str
    selector: Dict[str, str]
    port: int
    target_port: Optional[int] = None


class ClusterIPServiceRegistry:
    _ip_counter = 0

    def __init…
12 0 Open
Production deployment patterns medium

How to Simulate Blue-Green Deployment Switch in Python

A mock Blue-Green deployment class that deploys new versions to an inactive environment, runs a health check, switches traffic, and supports rollback in Python.

deployment blue-green mock
Python
import random
import time

class BlueGreenDeployment:
    def __init__(self, initial_env="blue"):
        self.environments = {"blue": "v1.0", "green": "v1.0"}
        self.active_env = initial_env
        self.running = True

    def deploy_new_version(self, version, target_env):
        if target_env == self.active_…
15 0 Open
Production deployment patterns medium

How to Smoke Test a Deployment in Python with unittest.mock

Run a post-deploy smoke test by mocking the deployment status check to verify your health-check logic returns PASS/FAIL.

deployment smoke-test unittest-mock
Python
import unittest
from unittest.mock import Mock, patch

class DeploymentService:
    def check_status(self):
        return "unknown"

def smoke_test_deploy():
    service = DeploymentService()
    with patch.object(service, "check_status", return_value="healthy") as mock_check:
        status = service.check_status()
…
12 0 Open
Production deployment patterns medium

How to mock Kustomize overlay patches in Python

Simulate Kustomize overlay behavior by deep-merging a base Kubernetes manifest with a patch dictionary in pure Python.

kubernetes kustomize deep-merge
Python
import json

SOURCE = {
    "apiVersion": "apps/v1",
    "kind": "Deployment",
    "metadata": {"name": "app", "namespace": "prod"},
    "spec": {
        "replicas": 3,
        "template": {
            "spec": {
                "containers": [{"name": "app", "image": "nginx:1.19"}]
            }
        }
    }
}

P…
14 0 Open
Production deployment patterns medium

How to mock S3 remote backend for Terraform in Python

Simulate a Terraform S3 remote backend using moto to write and read state files, enabling local testing without real AWS.

boto3 moto terraform
Python
import boto3
from moto import mock_aws
import json
from pathlib import Path

@mock_aws
def demo_s3_remote_backend():
    s3 = boto3.client("s3", region_name="us-east-1")
    bucket = "terraform-state-bucket"
    key = "env/prod/terraform.tfstate"
    
    s3.create_bucket(Bucket=bucket)
    
    # Simulate Terraform w…
13 0 Open
Production deployment patterns medium

Mock ConfigMap Mount Environment Variables in Python

Simulate reading environment variables from a Kubernetes ConfigMap-mounted directory and test it with mocks.

kubernetes configmap mocking
Python
import os
import tempfile
from unittest.mock import patch

def load_config_from_mount(mount_path):
    """Simulate reading environment variables from a ConfigMap-mounted directory."""
    config = {}
    for filename in os.listdir(mount_path):
        file_path = os.path.join(mount_path, filename)
        if os.path.i…
13 0 Open
Production deployment patterns medium

Mock Kubernetes HPA CPU Scaling in Python

Python function that simulates CPU utilization and calculates desired replicas using the Kubernetes HPA formula.

kubernetes hpa autoscaling
Python
import random
import time


def simulate_cpu_utilization(target_utilization=50, samples=10):
    """Simulate CPU utilization readings for HPA mock."""
    utilizations = []
    for _ in range(samples):
        # Simulate fluctuating CPU with random noise around target
        current = target_utilization + random.unif…
13 0 Open
Production deployment patterns medium

Zero Downtime Migration with Dual Write Pattern in Python

Implement a dual-write pattern that writes user data to both legacy and new systems simultaneously to enable zero-downtime migration.

migration dual-write zero-downtime
Python
from datetime import datetime
import json


class UserService:
    def __init__(self):
        self.legacy_db = {}
        self.new_db = {}
        self.migration_log = []

    def write_user(self, user_id, name, email):
        # Write to new system first
        user_record = {
            "id": user_id,
           …
12 0 Open

Browse by section

Each section groups closely related Python snippets.

Production deployment patterns — Python code examples

What you will find here

This page collects production deployment patterns 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.