🎉 DevOps Interview Prep Bundle is live — 1000+ Q&A across 20 topicsGet it →
All Articles

Build an AI Blue-Green Deployment Risk Scorer with Claude API

Blue-green deployments cut traffic fully at cutover, unlike gradual canaries — which means the decision to cut over needs to be right the first time. Build a tool that scores cutover risk before you flip the switch, using Claude API to reason across the diff, test results, and deployment history.

Shubham4 min read
Share:Tweet

Blue-green deployments trade canary's gradual traffic-shift safety net for instant, clean rollback — but that means the cutover decision itself carries more weight, since you're not easing into it with 5% traffic first. This tool scores cutover risk beforehand by reasoning across everything that would normally require a human to mentally cross-reference: the code diff, test coverage of the changed areas, and how similar past deploys behaved.

Setup

bash
pip install anthropic PyGithub requests

Risk Signal Collection

python
import anthropic
from github import Github
 
client = anthropic.Anthropic()
 
 
def gather_risk_signals(repo_name: str, pr_number: int, github_token: str) -> dict:
    gh = Github(github_token)
    repo = gh.get_repo(repo_name)
    pr = repo.get_pull(pr_number)
 
    changed_files = list(pr.get_files())
 
    return {
        "files_changed": len(changed_files),
        "lines_changed": sum(f.additions + f.deletions for f in changed_files),
        "touches_database_migration": any("migrations/" in f.filename for f in changed_files),
        "touches_critical_path": any(f.filename in CRITICAL_FILES for f in changed_files),
        "test_coverage_delta": get_coverage_delta(pr),
        "ci_status": get_ci_check_results(repo, pr),
        "similar_past_deploys": find_similar_past_deploys(changed_files),
    }
 
 
CRITICAL_FILES = ["src/payments/", "src/auth/", "src/checkout/"]
 
 
def find_similar_past_deploys(changed_files: list) -> list[dict]:
    """Look at deploy history for past changes to these same files —
    did previous deploys touching this code cause incidents?"""
    touched_paths = [f.filename for f in changed_files]
    return query_deploy_history_for_paths(touched_paths, months=6)

Risk Scoring With Claude

python
import json
 
SCORE_PROMPT = """Score the cutover risk for this blue-green deployment.
 
PR summary: {pr_title}
Files changed: {files_changed}, Lines changed: {lines_changed}
Touches database migration: {touches_migration}
Touches critical path (payments/auth/checkout): {touches_critical}
Test coverage delta: {coverage_delta}
CI status: {ci_status}
 
Historical context — past deploys touching similar files:
{similar_deploys}
 
Unlike a canary, blue-green cutover shifts 100% of traffic at once — there
is no gradual traffic-based warning before full exposure. Score risk
accordingly, weighing:
1. Blast radius if this deploy has a bug (critical path = high blast radius)
2. Whether a database migration is involved (harder/riskier to instant-rollback
   if the new schema is already being written to)
3. Whether test coverage genuinely covers the changed code, not just exists somewhere in the repo
4. Whether similar past changes to this code caused incidents
 
Respond with ONLY valid JSON:
{{"risk_score": "low"|"medium"|"high", "reasoning": "...",
  "recommended_action": "proceed_with_cutover" | "recommend_canary_instead" | "recommend_additional_testing_first"}}"""
 
 
def score_deployment_risk(signals: dict, pr_title: str) -> dict:
    response = client.messages.create(
        model="claude-sonnet-5",
        max_tokens=800,
        messages=[{
            "role": "user",
            "content": SCORE_PROMPT.format(
                pr_title=pr_title, files_changed=signals["files_changed"],
                lines_changed=signals["lines_changed"],
                touches_migration=signals["touches_database_migration"],
                touches_critical=signals["touches_critical_path"],
                coverage_delta=signals["test_coverage_delta"],
                ci_status=signals["ci_status"],
                similar_deploys=signals["similar_past_deploys"],
            )
        }]
    )
    text = response.content[0].text.strip()
    if text.startswith("```"):
        text = text.split("```")[1].replace("json", "", 1).strip()
    return json.loads(text)

Example Output

Blue-Green Cutover Risk Assessment: PR #482 "Refactor checkout payment
validation logic"

Risk score: HIGH

Reasoning: This PR touches src/checkout/payment_validator.py (critical
path) with a 40% net increase in cyclomatic complexity in the changed
function. Test coverage delta shows +2 new test cases, but they only
cover the happy path — the diff removes a null-check branch that had
no corresponding test being added for its replacement logic. Historical
context: the last 3 deploys touching this same file over the past 6
months, 1 caused a production incident (payment validation false-negative,
resolved via rollback). No database migration involved, so instant
rollback is at least clean if something goes wrong.

Recommended action: recommend_additional_testing_first — specifically,
add test coverage for the removed null-check's replacement logic before
cutover. Given blue-green's all-at-once traffic exposure and this file's
incident history, the current test coverage doesn't give enough confidence
for an instant 100% cutover.

Why This Complements Rather Than Replaces Canary Analysis

Blue-green and canary aren't competing strategies you pick once — many teams use blue-green specifically for its instant, clean rollback property (useful when database schema compatibility makes gradual traffic-shifting awkward) while still wanting a pre-cutover risk gate that canary analysis would normally provide through gradual traffic observation. This tool's "recommend_canary_instead" output is a real signal worth listening to — if the risk assessment can't get confident from static analysis alone, that's often a sign the deployment strategy itself, not just the code, needs reconsidering for this specific change.


More AI deployment safety tooling? Read our Build an autonomous deployment rollback agent with Claude API and AI agents making progressive delivery decisions.

🔧

Today I Fixed

Short real fixes from production — posted daily

Browse fixes
Newsletter

Stay ahead of the curve

Get the latest DevOps, Kubernetes, AWS, and AI/ML guides delivered straight to your inbox. No spam — just practical engineering content.

Related Articles

Comments