Reference library

Production deployment patterns

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

34 matches
Production deployment patterns easy

Docker healthcheck CMD mock in Python

Runs a subprocess to curl a health endpoint and returns exit code 0 when healthy, 1 when unhealthy, mimicking a Docker HEALTHCHECK command.

docker healthcheck subprocess
Python
import subprocess
import sys


def run_healthcheck() -> int:
    result = subprocess.run(["curl", "-fsS", "http://localhost:8080/health"], capture_output=True, text=True)
    if result.returncode == 0:
        print("healthy")
        return 0
    print("unhealthy", file=sys.stderr)
    return 1


if __name__ == "__ma…
15 0 Open
Production deployment patterns easy

Generate a Mock Artifact Version Tag in Python

Creates a mock build artifact version tag from a branch name and build number, with a date stamp.

artifact versioning ci
Python
import re
from datetime import datetime

def mock_version_tag(branch_name: str, build_number: int) -> str:
    """Generate a mock build artifact version tag from branch and build number."""
    branch_slug = re.sub(r'[^a-zA-Z0-9]+', '-', branch_name).strip('-').lower()
    date_part = datetime.utcnow().strftime('%Y%m%…
13 0 Open
Production deployment patterns easy

How to Attach an SBOM to a Release in Python (Mock)

A mock function that attaches a Software Bill of Materials (SBOM) to a GitHub-style release by counting its components and marking the upload as attached.

sbom release json
Python
import json
from pathlib import Path


def attach_sbom_mock(sbom_path: Path, release_tag: str, artifact_name: str) -> dict:
    """Mock attaching an SBOM to a release, returning the simulated upload result."""
    sbom = json.loads(sbom_path.read_text())
    return {
        "release_tag": release_tag,
        "artifa…
14 0 Open
Production deployment patterns easy

How to Build a Data Helper for Production Deployment in Python

Build a reusable DataHelper class that loads configs, validates required keys, normalizes string values, and logs schema details — a production-ready data processing pattern.

json pathlib data-processing
Python
import json
from pathlib import Path
from typing import Any, Dict

class DataHelper:
    """Common data processing patterns for production deployment."""
    
    def __init__(self, config_path: str | Path):
        self.config_path = Path(config_path)
        self.config = self._load_config()
    
    def _load_confi…
14 0 Open
Production deployment patterns easy

How to Build a Mock Trivy Image Scan Gate in Python

Simulate a Trivy image scan and enforce a security gate that fails the pipeline when vulnerabilities meet or exceed a severity threshold.

trivy security ci-cd
Python
import json
import sys


def mock_trivy_scan(image_name, severity_threshold="HIGH"):
    """Simulate a Trivy image scan result."""
    mock_vulnerabilities = [
        {"ID": "CVE-2023-1234", "Severity": "HIGH", "Package": "openssl", "FixedVersion": "3.0.9"},
        {"ID": "CVE-2024-5678", "Severity": "CRITICAL", "Pa…
13 0 Open
Production deployment patterns easy

How to Build a Simple Data Helper Class in Python

A beginner-friendly DataHelper class that safely saves and loads JSON files with automatic directory creation, perfect for production-style file handling.

json file-handling data-persistence
Python
from pathlib import Path
import json


class DataHelper:
    """Simple production-style helper for loading and saving JSON data."""

    def __init__(self, data_dir="data"):
        self.data_dir = Path(data_dir)
        self.data_dir.mkdir(exist_ok=True)

    def save(self, filename, data):
        filepath = self.da…
12 0 Open
Production deployment patterns easy

How to Build a Simple Data Helper Class in Python

A beginner-friendly DataHelper class that stores Python dataclass objects as JSON records to disk, with load, add, and save methods.

dataclass json file-io
Python
import json
from dataclasses import dataclass, asdict
from pathlib import Path

@dataclass
class User:
    name: str
    age: int
    email: str

class DataHelper:
    def __init__(self, filepath: str = "data.json"):
        self.filepath = Path(filepath)
        self._data = self._load()
    
    def _load(self) -> l…
12 0 Open
Production deployment patterns easy

How to Build a Synthetic Monitor Mock in Python

Simulates a synthetic monitoring system in Python that collects latency samples, averages them, and reports service status as UP or DEGRADED.

monitoring dataclass simulation
Python
import random
import time
from dataclasses import dataclass, field
from statistics import mean


@dataclass
class SyntheticMonitor:
    service: str
    endpoint: str
    latency_ms: list[float] = field(default_factory=list)

    def check(self) -> float:
        latency = random.uniform(50.0, 250.0)
        self.late…
13 0 Open
Production deployment patterns easy

How to Create a Liveness Probe HTTP Mock in Python

Build a lightweight HTTP server in Python that mimics a Kubernetes-style liveness endpoint, returning JSON health status for local testing.

http healthcheck mock-server
Python
import http.server
import threading
import time


class LivenessHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/healthz":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfi…
15 0 Open
Production deployment patterns easy

How to Implement a Data Helper Class in Python for Production Deployments

Build an environment-aware data helper in Python that loads config, extracts, transforms, and reports on JSON data using small, testable functions.

data-helper production json
Python
"""Production-style data helper for beginners.

Demonstrates:
- environment-aware config
- central data extraction
- small, testable functions
"""

import os
import json
from pathlib import Path
from typing import List, Dict, Any


def load_config(env: str = os.getenv("APP_ENV", "development")) -> Dict[str, Any]:
    …
12 0 Open
Production deployment patterns easy

How to Implement a Manual Approval Gate Mock in Python

Simulates a manual approval workflow with threshold-based rules, random decisions for medium amounts, and logs each result with timing.

approval simulation workflow
Python
import random
import time


def approve_request(amount: float) -> bool:
    if amount <= 1000:
        return True
    if amount <= 5000:
        return random.random() < 0.7
    return False


def main():
    requests = [500, 1200, 7500, 3000, 50]
    for amount in requests:
        start = time.perf_counter()
      …
18 0 Open
Production deployment patterns easy

How to Merge Helm Chart Values Per Environment in Python

Merge default Helm chart values with environment-specific overrides using a recursive dictionary merge function, then write each environment's YAML file.

helm merge yaml
Python
from pathlib import Path
import json
import tempfile


DEFAULT_VALUES = {
    "image": "nginx:latest",
    "replicas": 1,
    "resources": {"cpu": "100m", "memory": "128Mi"},
}

ENV_OVERRIDES = {
    "dev": {"replicas": 1, "resources": {"cpu": "50m"}},
    "staging": {"replicas": 2, "resources": {"cpu": "250m", "memor…
11 0 Open
Production deployment patterns easy

How to Mock Docker Image Non-Root User in Python

This Python class simulates Docker image layers and inspects whether the final user is a non-root user, returning UID, GID, and security status.

docker security mock
Python
from pathlib import Path


class DockerImageMock:
    def __init__(self, name, tag):
        self.name = name
        self.tag = tag
        self.layers = []
        self.user = "root"

    def add_file(self, path, content):
        self.layers.append({"file": path, "content": content})

    def set_user(self, usernam…
11 0 Open
Production deployment patterns easy

How to Mock Multi-Stage Docker Builds in Python

Simulate a multi-stage Docker build in pure Python using classes and temp directories to understand how build stages copy artifacts into a final image.

docker multi-stage simulation
Python
# Simulate multi-stage Docker build with pure Python
from pathlib import Path
import tempfile
import shutil

class BuildContext:
    """Mimics a Docker build context with stages."""
    
    def __init__(self, name):
        self.name = name
        self.files = {}
    
    def add_file(self, dest, content):
        s…
14 0 Open
Production deployment patterns easy

How to Mock Terraform Plan and Apply in Python

This code provides a lightweight Python mock of Terraform's plan and apply commands, helping you simulate infrastructure changes without real cloud resources.

terraform mock simulation
Python
class MockTerraform:
    def __init__(self):
        self.plans = [
            {"id": 1, "action": "create", "resource": "aws_instance.web"},
            {"id": 2, "action": "update", "resource": "aws_s3_bucket.data"},
            {"id": 3, "action": "destroy", "resource": "aws_iam_user.legacy"}
        ]
        sel…
14 0 Open
Production deployment patterns easy

How to Mock a CI Pipeline with Build, Test, and Deploy Stages in Python

Simulate a three-stage CI pipeline (build, test, deploy) in Python with random pass/fail logic, early exit on failure, and measured stage durations.

ci-cd simulation dataclasses
Python
import time
import random
from dataclasses import dataclass


@dataclass
class StageResult:
    name: str
    status: str
    duration: float


def run_stage(name: str, success_chance: float = 0.9) -> StageResult:
    """Simulate a pipeline stage with random success/failure."""
    start = time.time()
    time.sleep(r…
14 0 Open
Production deployment patterns easy

How to Mock a Container Registry in Python

Build an in-memory container registry mock with push, tag listing, and manifest retrieval logic for testing deployment tooling.

containers testing mocking
Python
import json
from collections import defaultdict


class MockRegistry:
    def __init__(self):
        self.repositories = defaultdict(dict)

    def push_image(self, repo: str, tag: str, layers: list[str]) -> None:
        self.repositories[repo][tag] = {
            "layers": layers,
            "size": sum(len(layer…
14 0 Open
Production deployment patterns easy

How to Mock a Dependency for Readiness Probe in Python

Use unittest.mock.Mock to simulate a dependency's readiness check response for testing a service's is_ready method without hitting a real connection.

unittest.mock mock readiness probe
Python
import time
import unittest
from unittest.mock import Mock

class Service:
    def __init__(self, dependency):
        self.dependency = dependency

    def is_ready(self):
        try:
            result = self.dependency.check()
            return result == "ready"
        except Exception:
            return False
…
17 0 Open
Production deployment patterns easy

How to Mock a Dockerfile Multi-Stage Build in Python

Simulate a Dockerfile multi-stage build process in Python using dataclasses to validate stage ordering and file availability before you write the real Dockerfile.

dockerfile multi-stage simulation
Python
from dataclasses import dataclass
from pathlib import Path


@dataclass
class BuildStage:
    name: str
    base_image: str
    files: list[str]
    commands: list[str]


def run_build(stage: BuildStage, context_dir: Path):
    print(f"=== Stage: {stage.name} (base: {stage.base_image}) ===")
    for file in stage.file…
14 0 Open
Production deployment patterns easy

How to Mock a Feature Flag Rollout Percentage in Python

Simulate a percentage-based feature flag rollout by hashing a user ID to deterministically enable features for a subset of users.

feature-flags rollout deterministic
Python
import random
from dataclasses import dataclass


@dataclass
class FeatureFlag:
    name: str
    rollout_percentage: int


def is_feature_enabled(feature_flag: FeatureFlag, user_id: str) -> bool:
    hashed_id = hash(user_id) % 100
    return hashed_id < feature_flag.rollout_percentage


if __name__ == "__main__":
  …
11 0 Open
Production deployment patterns easy

How to Mock a GitHub Actions Workflow in Python

Build a dataclass-based model of a GitHub Actions workflow and simulate its execution to validate steps and outputs before deployment.

github-actions dataclasses mock
Python
import json
from dataclasses import dataclass, asdict
from typing import List, Dict, Any


@dataclass
class Step:
    name: str
    run: str


@dataclass
class Job:
    name: str
    steps: List[Step]
    runs_on: str = "ubuntu-latest"


@dataclass
class Workflow:
    name: str
    jobs: List[Job]

    def to_github_a…
13 0 Open
Production deployment patterns easy

How to Mock a Kubernetes Rolling Update with maxSurge in Python

Simulate a Kubernetes rolling update with maxSurge policy, tracking peak and final replica counts during roll transitions.

kubernetes rolling-update maxsurge
Python
from collections import deque

class RollingUpdateMaxSurge:
    def __init__(self, replicas, max_surge):
        self.replicas = replicas
        self.max_surge = max_surge
        self.available = replicas
        self.history = deque()

    def roll(self, desired_replicas):
        """
        Simulate a rolling upd…
13 0 Open
Production deployment patterns easy

How to Mock a SIGTERM Handler in Python

Create a graceful shutdown handler for SIGTERM and SIGINT signals, then test it by simulating a signal delivery without terminating the process.

signals graceful-shutdown sigterm
Python
import signal
import time

class Service:
    def __init__(self):
        self.running = True

    def shutdown(self, signum, frame):
        print(f"Received signal {signum}, shutting down gracefully...")
        self.running = False

    def run(self):
        signal.signal(signal.SIGTERM, self.shutdown)
        sig…
13 0 Open
Production deployment patterns easy

How to Mock a Slow Startup Probe for Fast Testing in Python

This code shows how to replace a slow startup probe's initialization with a mock to make tests run fast and reliably.

mock testing startup-probe
Python
import time
from unittest.mock import Mock, patch


class StartupProbe:
    def __init__(self, init_time):
        self.init_time = init_time
        self.ready = False

    def initialize(self):
        time.sleep(self.init_time)
        self.ready = True
        return self.ready


def run_startup_probe(probe):
    …
15 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.