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.
Python code
44 linesimport 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_env:
return f"Cannot deploy to active environment {target_env}"
self.environments[target_env] = version
return f"Deployed {version} to {target_env}"
def health_check(self, env):
return random.random() > 0.1 # 90% healthy
def switch_traffic(self, target_env):
if target_env == self.active_env:
return f"Already on {target_env}"
if not self.health_check(target_env):
return f"Health check failed on {target_env}, aborting switch"
self.active_env = target_env
return f"Traffic switched to {target_env}"
def rollback(self):
previous = "blue" if self.active_env == "green" else "green"
self.active_env = previous
return f"Rolled back to {previous}"
def status(self):
return f"Active: {self.active_env} ({self.environments[self.active_env]}), " \
f"Inactive: {'green' if self.active_env == 'blue' else 'blue'} ({self.environments['green' if self.active_env == 'blue' else 'blue']})"
if __name__ == "__main__":
deploy = BlueGreenDeployment()
print("Initial:", deploy.status())
print(deploy.deploy_new_version("v2.0", "green"))
print(deploy.switch_traffic("green"))
print("After switch:", deploy.status())
print(deploy.rollback())
print("After rollback:", deploy.status())
Output
Initial: Active: blue (v1.0), Inactive: green (v1.0)
Deployed v2.0 to green
Traffic switched to green
After switch: Active: green (v2.0), Inactive: blue (v1.0)
Rolled back to blue
After rollback: Active: blue (v1.0), Inactive: green (v2.0)
How it works
This implementation models the core mechanics of a blue-green deployment: separate environments, deploy to the inactive one, validate health, then switch traffic. The health check uses random success to simulate flaky deployments, and rollback toggles the active environment back to the previous one. The class encapsulates state so switching and deploying are simple method calls. This pattern reduces downtime and enables instant rollbacks in real production systems.
Common mistakes
- Deploying directly to the active environment, which defeats the purpose of blue-green.
- Skipping health checks before switching traffic, leading to possible outages.
- Not persisting the active environment state across restarts (this mock holds it in memory).
- Assuming only one environment can be active; in a real system, both may exist but only one serves traffic.
Variations
- Use a load balancer or DNS to switch traffic instead of a simple attribute.
- Add a weighted traffic split to gradually shift users while monitoring metrics.
Real-world use cases
- Deploying a new version of a web service with zero downtime, then switching load balancer target.
- Releasing a mobile app backend feature where the old environment stays for instant rollback.
- Testing a database migration against a staging environment that can be promoted and reverted quickly.
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.