Production deployment patterns
Graceful shutdown, prod config, rollouts, readiness probes, and ship-with-confidence checks.
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.
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…
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.
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…
How to Mock time.sleep in a Python PreStop Hook
This code simulates a Kubernetes PreStop hook that delays shutdown, then mocks time.sleep to verify the hook logic without real delay.
import subprocess
import sys
import time
from unittest.mock import patch
def pre_stop_hook():
"""Simulate a Kubernetes PreStop hook that sleeps before shutdown."""
print("PreStop hook started: delaying shutdown")
time.sleep(3)
print("PreStop hook completed: ready to shutdown")
if __name__ == "__main_…
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.