PodDisruptionBudget minAvailable in Python
Simulate a Kubernetes PodDisruptionBudget check for minAvailable and maxUnavailable constraints with a Python class.
Python code
18 linesclass PodDisruptionBudget:
def __init__(self, name, min_available=None, max_unavailable=None):
self.name = name
self.min_available = min_available
self.max_unavailable = max_unavailable
def check_availability(self, ready_pods):
if self.min_available is not None:
return ready_pods >= self.min_available
if self.max_unavailable is not None:
return ready_pods <= self.max_unavailable
return True
if __name__ == "__main__":
pdb = PodDisruptionBudget("web-pdb", min_available=3)
print(f"PDB '{pdb.name}' with 2 ready pods: {pdb.check_availability(2)}")
print(f"PDB '{pdb.name}' with 5 ready pods: {pdb.check_availability(5)}")
Output
PDB 'web-pdb' with 2 ready pods: False
PDB 'web-pdb' with 5 ready pods: True
How it works
The PodDisruptionBudget class models Kubernetes scheduling constraints. check_availability uses min_available to enforce a floor on ready pods; if min_available is set, readiness requires ready_pods >= min_available. When only max_unavailable is set, it uses ready_pods <= max_unavailable to cap disruptions. The if __name__ == "__main__" guard lets the class be imported without running the demo.
Common mistakes
- Using `==` instead of `>=` or `<=` for threshold checks
- Not handling the case where both min_available and max_unavailable are set simultaneously
- Forgetting to return a boolean when neither constraint is set
Variations
- Add a `check_availability` that considers total_pods to compute max_unavailable dynamically
- Use a dataclass to reduce boilerplate for the budget definition
Real-world use cases
- Validating rollout safety before draining nodes in a deployment automation script.
- Simulating PDB logic in unit tests for controllers that manage Kubernetes workloads.
- Building a dry-run scheduler that verifies node drains will not violate availability targets.
Sponsored
More from Production deployment patterns
- Auto Rollback on Error Rate Exceeded in Python medium
- Automate Semantic Versioning with Conventional Commits in Python medium
- Design a Data Helper for Beginners in Python easy
- Docker healthcheck CMD mock in Python easy
- Generate a Mock Artifact Version Tag in Python easy
- Generate a docker-compose.yml with mock services in Python easy
Keep learning
Related tutorials and quizzes for this topic.