Skip to main content

Your Prompt Change Is a Deploy: Shadow, Canary and Roll Back in Django (Part 9)

Updated 18 min readMarkdown
Your Prompt Change Is a Deploy: Shadow, Canary and Roll Back in Django (Part 9)

Here's a failure mode worth planning for. You change one thing about an LLM feature: a sentence in the prompt, a model id, the field the system prompt travels in. Tests pass. Deploy goes green. No exception, no 500, no alert. A week later someone notices the bill, or the hold queue, or a support ticket that says "why was my post hidden?"

That isn't hypothetical. On November 17, OpenAI updated its docs to say that from GPT-6.2 on, the Responses API instructions field is billed at the uncached rate on every request. LiteLLM, which put system prompts in that field, wrote it up two days later: "Requests still worked, but GPT-6.2 users paid full price for their system prompt on every call." And: "Nothing failed on our side, so none of our error alerts fired, and a customer reported the missing cache hits on November 18."

Model and prompt changes rarely fail loudly. They fail as a different distribution of outputs, and error monitoring doesn't watch that.

This is Part 9 of Shipping AI Agents in Django. Part 8 built a moderation pipeline whose overturned appeals become eval cases. Here we change that pipeline's prompt and model without betting the community on it: version the prompt in code, run the new one in shadow next to the live one, compare verdicts on real traffic, replay the eval set, then canary it behind a flag that rolls itself back.

Short version

  • A prompt version is code: id, pinned model id, prompt text and params, hashed into a fingerprint. Editing it means a new id. Moving aliases like *-latest are rejected at import.
  • Shadow mode: live serves, the candidate runs on a sample of the same requests, and its answer is stored and thrown away. A candidate crash never reaches the user.
  • Compare by direction, not just agreement. A candidate that allows what live hid needs a human to sign off on each case.
  • Replay the eval set before any user sees the candidate. Traffic doesn't contain your rare, expensive cases. Your appeal history does.
  • Canary a sticky slice (per user, fresh salt per rollout). A cron job compares canary against live and rolls back on error spikes or behaviour shifts. Every stage change is an append-only event.

The demo is a small Django 5.2 app with 25 passing pytest tests. The model is scripted, so nothing calls a network.

The calendar says you'll do this soon anyway

Even if you never touch your prompt, the model under it has an end date:

  • Anthropic retires claude-sonnet-4-5-20250929 on November 30, 2026, and says the retirement includes the dateless claude-sonnet-4-5 alias (model deprecations).
  • OpenAI shuts down gpt-5, gpt-5-mini, gpt-5-nano, o3 and o3-pro on December 11, 2026 (deprecations). The same page lists /v1/prompts and reusable prompt objects shutting down on November 30, with the replacement "Move prompt content into your application code."
  • Anthropic's same page notes that temperature, top_p and top_k were removed in API version 2026-10-21 and return a 400 error. A request body that worked yesterday can be rejected by a newer model or API version.

OpenAI's API overview says: "Model prompting behavior between snapshots is subject to change," and "The best way to ensure consistent prompting behavior and model output is to use pinned model versions, and to run evals for your applications."

Pinning and evals are the minimum. This post is about the gap between "evals pass" and "100% of traffic."

What can change underneath you

Each source needs a different defence:

  1. An alias moves. Google's Gemini models page says a latest alias "will get hot-swapped with every new release of a specific model variation," with two weeks' email notice before the version behind it changes. Stable names "usually don't change," and "most production apps should use a specific stable model."
  2. A snapshot retires. Pinning delays this. It doesn't stop it. OpenAI's minimum notice is at least 6 months for generally available models, 3 months for specialized variants, and possibly 2 weeks for preview models. Anthropic gives at least 60 days for publicly released models.
  3. Serving changes under a fixed id. Anthropic's model IDs page says it doesn't update an existing model id's weights or configuration, but the infrastructure around it (router, safety classifiers, sampling logic) can change, and "occasionally, infrastructure updates produce minor differences in observable behavior even when the model ID and weights have not changed."
  4. The API contract shifts. Rejected parameters, caching, billing.
  5. You edit the prompt. Usually the most frequent change and the least reviewed.

Pinning handles 1 and makes 2 a planned event. Nothing in your code prevents 3 or 4. So you need a way to ship changes you make (2 and 5) carefully, and to see changes you didn't make (3 and 4) in production data.

Step 1: a prompt version is code, and it has a fingerprint

MOVING_ALIASES = re.compile(r"(^|-)latest$")


@dataclass(frozen=True)
class PromptVersion:
    id: str                     # "moderation@4"
    model: str                  # pinned model id, never a moving alias
    system: str
    params: tuple = field(default=())   # (("max_output_tokens", 300),)
    schema: str = "verdict.v1"

    @property
    def fingerprint(self) -> str:
        blob = json.dumps([self.model, self.system, list(self.params), self.schema])
        return hashlib.sha256(blob.encode()).hexdigest()[:12]


def register(pv: PromptVersion) -> PromptVersion:
    if MOVING_ALIASES.search(pv.model):
        raise ValueError(f"{pv.id}: '{pv.model}' is a moving alias; pin a snapshot id")
    old = REGISTRY.get(pv.id)
    if old and old.fingerprint != pv.fingerprint:
        raise ValueError(f"{pv.id} already exists with different content; register a new id")
    REGISTRY[pv.id] = pv
    return pv

Three rules come out of that:

  • The model id is part of the prompt version. A prompt tuned for one model is a different artifact on another. Changing either one means a new version.
  • Ids are immutable. Re-registering moderation@3 with an extra sentence raises at import time, so "I just tweaked the wording" can't silently change what @3 means in last month's logs.
  • The fingerprint goes everywhere. Every model call writes a row with the prompt version and fingerprint. The view sets an X-Prompt-Version header, and the same value belongs on your trace spans (Part 6). When the hold rate moves on Tuesday, the first question is "which version answered?"

Versions live in the repo, so a prompt change gets code review like any other diff. (OpenAI's own replacement for its reusable prompt objects is to move the prompt into your code.)

The regex only catches names ending in latest. Bare family names can also be aliases (Anthropic's claude-sonnet-4-5 points at a dated snapshot), so keep a short allowlist of ids you've checked against each provider's docs.

Step 2: shadow mode, or answer with the old prompt and log the new one

The rollout state is one row per feature:

class Rollout(models.Model):
    class Mode(models.TextChoices):
        OFF = "off"          # live only
        SHADOW = "shadow"    # live serves, candidate runs on a sample, result discarded
        CANARY = "canary"    # a sticky slice of requests is served by the candidate

    feature = models.CharField(max_length=50, unique=True)
    live_version = models.CharField(max_length=50)
    candidate_version = models.CharField(max_length=50, blank=True)
    mode = models.CharField(max_length=10, choices=Mode.choices, default=Mode.OFF)
    shadow_percent = models.PositiveSmallIntegerField(default=0)
    canary_percent = models.PositiveSmallIntegerField(default=0)
    salt = models.CharField(max_length=16, default="")
    stage_started_at = models.DateTimeField(null=True)

And the service that every request goes through:

def moderate(feature, text, key, unit=None, call=None) -> Result:
    call = call or import_string(settings.LLM_CALL)
    ro = Rollout.objects.get(feature=feature)
    unit = unit or key
    canary = routing.in_canary(ro, unit)
    pv = registry.get(ro.candidate_version if canary else ro.live_version)
    try:
        verdict, status = classify(call, pv, text)
    except Exception:
        log.exception("classifier call failed")
        verdict, status = None, "error"
    _record(ro, key, Inference.Role.SERVE, "canary" if canary else "live", pv, verdict, status)
    result = Result(verdict.action if verdict else "hold", pv.id)

    if routing.in_shadow(ro, unit):
        # Demo runs this inline. In production, enqueue it after commit so the
        # candidate's latency and failures never touch the user's request.
        cand = registry.get(ro.candidate_version)
        try:
            v2, s2 = classify(call, cand, text)
        except Exception:
            v2, s2 = None, "error"
        _record(ro, key, Inference.Role.SHADOW, "", cand, v2, s2)
    return result

Google's SRE workbook chapter on canarying releases calls this traffic teeing: "the production system serves the actual traffic and delivers responses to users, the canary deployment serves the copy and discards the responses. You might even compare the canary responses to the actual responses." That fits an LLM classifier well: it's a pure function of the input, so you can run it twice and discard one answer.

The rules that keep shadow mode safe:

  • The shadow answer is never served. In the tests, the candidate says hide, the user gets live's allow, and both rows are stored with their fingerprints.
  • Shadow failures are swallowed and recorded. A candidate that times out or returns "Sure! Here is the JSON you asked for" gets error or invalid in its row. The user's request doesn't notice.
  • No side effects. If your "prompt" is an agent with tools, shadowing it means running tools twice. Give the shadow run read-only tool stubs, or don't shadow that path. The workbook warns that teeing "doesn't adequately identify risk in stateful systems," and gives a shared cache inflating the canary's hit rate as its example.
  • Sample it. shadow_percent caps the extra spend. Shadowing 100% doubles classifier cost. Part 5's cost-per-successful-workflow math tells you what that costs.
  • Don't store the text twice. Inference rows hold a request_key like post:123, not the post body. Reviewers follow the key back to the source row, which keeps its own retention and deletion rules.

Step 3: compare verdicts by direction, not just agreement

"97% agreement" sounds good until you ask which 3%. A stricter candidate costs reviewer time. A looser one can leave harassment up. So the report splits them:

STRICTNESS = {"allow": 0, "hold": 1, "hide": 2}


def shadow_report(ro) -> ShadowReport:
    rows = Inference.objects.filter(feature=ro.feature, created_at__gte=ro.stage_started_at)
    live = {r.request_key: r for r in rows.filter(role="serve", cohort="live")}
    rep = ShadowReport()
    for s in rows.filter(role="shadow", prompt_version=ro.candidate_version):
        l = live.get(s.request_key)
        if l is None:
            continue
        rep.pairs += 1
        if s.status != "ok":
            rep.candidate_failures += 1
            continue
        rep.flips[(l.action, s.action)] += 1
        if l.action == s.action:
            rep.agreed += 1
        elif STRICTNESS[s.action] < STRICTNESS[l.action]:
            rep.loosened.append(s.request_key)
        else:
            rep.tightened.append(s.request_key)
    return rep

flips is a confusion matrix between two prompts, keyed by (live_action, candidate_action). In the demo, the change under test applies a Part 8 rule: self-harm posts go to a human (hold) instead of being hidden. On 24 shadowed requests the report shows 20 agreements and 4 flips, all ("hide", "hold"). That's exactly the intended change, and it still counts as loosened, because the candidate is less restrictive than live on those posts.

That's why the canary gate doesn't require zero loosened decisions. It requires zero unreviewed ones:

unreviewed = [k for k in rep.loosened if k not in reviewed]

A person looks at each loosened request key, confirms the candidate is right, and passes the reviewed keys to start_canary. If you have thousands of loosened flips, you don't have a prompt tweak. You have a policy change, and it should be reviewed as one.

Step 4: replay the eval set, because traffic doesn't contain your edge cases

Shadow traffic shows how the candidate handles what users sent this week, not the rare case that cost you an appeal last month. In Part 8 every overturned appeal became an EvalCase. Here those cases gate the rollout:

def replay(call, pv, cases=None) -> EvalResult:
    res = EvalResult(pv.id)
    for case in cases if cases is not None else EvalCase.objects.all():
        verdict, _ = classify(call, pv, case.text)
        if verdict and verdict.action == case.expected_action:
            res.passed += 1
            continue
        res.failed.append(case.id)
        if case.must_pass:
            res.must_pass_failed.append(case.id)
    return res

The gate runs it for both versions and adds two checks: every must_pass case passes, and the candidate's pass rate isn't below live's. One test sets this up on purpose. The eval set holds a film review quoting "you idiot," an appeal that was overturned and must stay allowed. Live traffic never contains a quoted insult, so shadow agreement is a perfect 100%. The candidate still hides the review, and the gate refuses:

must-pass eval cases failed: [1]
eval pass rate 0% < live 100%

High agreement on traffic and a regression on the cases you care about can both be true. The evals-in-CI post covers running the same replay as a merge gate, so a bad prompt usually fails before it's deployed at all.

Step 5: canary a sticky slice

When the gate passes, the candidate starts serving a small slice. Two details matter.

Buckets are stable and salted per rollout:

def bucket(salt: str, key: str) -> int:
    return int(hashlib.sha256(f"{salt}:{key}".encode()).hexdigest()[:8], 16) % 100


def in_canary(ro, key: str) -> bool:
    return ro.mode == ro.Mode.CANARY and bucket(ro.salt, key) < ro.canary_percent

The router hashes the unit (a user id), not the post id, so one person's posts aren't handled by two policies on alternate days. A fresh salt per rollout means the same 5% of users aren't the canary for every experiment.

Compare canary against live at the same time, not against last week. The SRE workbook is blunt: "Because time is one of the biggest sources of change in observed metrics, it is difficult to assess degradation of performance with before/after evaluation." With a concurrent slice, both cohorts see the same week, the same news cycle and roughly the same mix of users.

Step 6: automatic rollback that a cron job can run

def check_canary(feature, gates=Gates()) -> str:
    """Run from cron or a periodic task. Returns 'waiting', 'healthy' or 'rolled_back'."""
    ro = _locked(feature)
    if ro.mode != Rollout.Mode.CANARY:
        return "idle"
    n, err, restrictive = _cohort_stats(ro, "canary")
    _, _, live_restrictive = _cohort_stats(ro, "live")
    if n >= gates.canary_min_for_errors and err > gates.max_canary_error_rate:
        return _rollback(ro, "auto", f"canary error rate {err:.1%} over {n} requests")
    if n < gates.canary_min_for_rates:
        return "waiting"
    delta = restrictive - live_restrictive
    if abs(delta) > gates.max_restrictive_rate_delta:
        return _rollback(ro, "auto", f"hold/hide rate {restrictive:.1%} vs live "
                                     f"{live_restrictive:.1%} over {n} requests")
    return "healthy"

A management command loops over every canary and calls this. Schedule it every minute.

  • Two minimums. Errors (refusals, truncation, invalid JSON) are unambiguous, so a smaller sample is enough to act on them. A shift in the hold/hide rate is noisy at small n, so it waits for more data. Below that, the answer is waiting, not healthy. One test sends ten requests while the candidate returns garbage and checks the canary is still running.
  • Both directions. A candidate that suddenly hides much more is as suspicious as one that hides much less. The demo uses one absolute threshold. Real setups should also track per-label and appeal rates.
  • Rollback is boring on purpose. Mode goes to off, the candidate is cleared, live_version is never touched, and the next request is served by live. Nothing is redeployed.

The SRE chapter has one more warning that applies here: "make sure the intervals of your metrics are either the same as or less than your canary duration." An hourly hold-rate chart can't judge a 20-minute canary.

The bug the tests caught

The first version of start_canary was a single @transaction.atomic function. It wrote a gate_failed event explaining why it refused, then raised. The raise rolled back the transaction, and the event with it. Every refusal left no trace. The fix keeps the stage switch in the transaction and writes the refusal after it closes:

    with transaction.atomic():
        ro = _locked(feature)
        ...
        reasons, summary = _canary_gate(ro, gates, call, reviewed)
        if not reasons:
            ...
            return ro
    # Outside the transaction: the raise must not roll back the record of why we refused.
    _event(ro, "gate_failed", actor, stage="canary", reasons=reasons, **summary)
    raise GateFailed(reasons)

promote() has the same shape. It runs check_canary (which may roll back) outside the transaction that swaps versions. Otherwise a failed promotion would undo the automatic rollback that caused it. If your audit log is written inside the same transaction as the action it records, test the failure path explicitly.

Promote, and keep the way back open

promote() only works when the canary is healthy on enough traffic. It moves the candidate to live_version and writes a promoted event that records the previous version. Because old versions stay in the registry, revert_last_promotion() is a one-row update. That only works until the provider retires the old model id, which is one more reason to keep the deprecation dates from earlier on your calendar.

The event log reads like a changelog: shadow_started, canary_started, promoted, or rolled_back with the reason and sample size. RolloutEvent refuses updates and deletes, like Part 8's audit log.

This isn't only a moderation concern. Lyne, one of our showcase apps, is a short-post social app, and its AI helpers walkthrough describes an AI check that looks at a post's text and image for spam, harassment or graphic content before it goes out, then shows "Review before posting?" so the author can edit or post anyway. None of the code above comes from Lyne. But any pre-post check like that has a prompt and a model behind it, and both will change, so it needs this kind of rollout path.

Trade-offs I'd flag in review

  • Shadow mode costs money and days. You pay for every sampled call and wait for enough pairs. Overkill for a typo fix, cheap insurance for a model migration.
  • Agreement thresholds hide the base rate. If 98% of posts are clean, a candidate that allows everything still agrees 98% of the time. That's why the direction-of-flip check exists, and why it should be per label once you have volume.
  • Shadow can't see what users do next. It compares decisions, not outcomes. Appeals, reports, and edits after "Review before posting?" only show up once the candidate actually serves, which is what the canary is for.
  • LLM output isn't deterministic. Some disagreement is the live prompt disagreeing with itself. Shadow a copy of the live version for a day first (an A/A run) and you'll know how much of that 3% is noise.
  • Sticky per user is a fairness choice. It keeps one person's experience consistent, and it means a bad candidate hits the same 5% of people repeatedly until rollback. Keep the canary short and the slice small.

What the tests prove

pytest -q: 25 passed (Python 3.13.5, Django 5.2.19, pydantic 2.14.3, pytest 9.2.0, pytest-django 4.14.0). They cover: moving aliases (-latest, chat-latest) rejected; prompt version ids immutable; the fingerprint changing with model, prompt text and params; buckets stable, roughly proportional, and reshuffled by a new salt; mode off never calling the candidate; shadow verdicts recorded but never served; a crashing or garbled candidate not affecting the user; shadow_percent capping candidate calls; a live failure falling back to hold; a candidate identical to live rejected; the shadow report's agreement, flip matrix and loosened keys; the canary gate refusing too few pairs (with the refusal event kept), unreviewed loosened decisions, and a must-pass eval regression despite 100% traffic agreement; the canary staying sticky per user; waiting below the sample minimum; automatic rollback on an error spike and on a hold/hide-rate shift, with live untouched; promotion only from a healthy canary, plus revert; the check_rollouts command rolling back a bad canary; append-only events; and the view's X-Prompt-Version header. The provider is scripted. The tests prove the plumbing. They don't measure any real model.

Open question for readers

The one I'd like opinions on: who should be allowed to promote a prompt? This demo lets anyone who can call promote() do it once the gates pass. That's fine for wording changes. But a prompt change can be a policy change (the self-harm hide → hold flip above is exactly that), and in some teams policy belongs to trust and safety, legal or product, not to whoever opened the pull request.

Do you gate prompt changes by what they change (policy text vs wording vs model id), by how big the flip matrix is, or not at all? And if you've run shadow mode on an LLM feature, how long did you shadow before you trusted the numbers? I'd like to hear what worked.

The series so far

  1. Human-in-the-loop AI agents in Django: approval gates
  2. Least-privilege agent identity in Django
  3. Your MCP server is a second API
  4. Permission-aware RAG without post-filters
  5. Cost per successful workflow
  6. Tracing agent runs with OpenTelemetry
  7. Structured outputs that don't break
  8. AI moderation helpers with appeals
  9. Shipping prompt and model changes safely (this post)

Next, Part 10: provider fallbacks without surprises. When the primary model times out or refuses, fail over to a second provider whose prompt version was shadowed and evaluated too, not one nobody tested.

The demo is a plain Django 5.2 app: rollout/ (registry, schemas, classifier, models, routing, service, compare, evals, gates, views, a check_rollouts command) and one test file.

About the author

  • Custom software & AI development company. We build production-ready AI integrations, mobile apps, and web platforms for businesses that want real results. lycore.com

No comments yet. Be the first to comment.

More from this blog