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.

Medium Python 3.9+ Aug 9, 2026 Production deployment patterns 16 views 0 copies

Python code

44 lines
Python 3.9+
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_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

stdout
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

  1. Use a load balancer or DNS to switch traffic instead of a simple attribute.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Production deployment patterns

Related tutorials and quizzes for this topic.