We are building a release rehearsal guild that includes feature flag guardrails, dry runs, risk dashboards, and drills.
The system will help teams practice and validate their release processes in a safe environment.
Let's break down the requirements:
-
Feature Flag Guardrails:
- Define and enforce policies around feature flags (e.g., flags must be toggleable, have an owner, expiration, etc.)
- Validation of feature flag configurations (e.g., no flags in production without a rollout plan, etc.)
-
Dry Runs:
- Simulate a release in a staging environment that mirrors production as closely as possible.
- Run automated tests and checks without affecting real users.
-
Risk Dashboards:
- Visualize the risks associated with a release (e.g., number of feature flags, complexity, past incidents, etc.)
- Provide a risk score and breakdown.
-
Drills:
- Conduct controlled experiments (like chaos engineering) to test the resilience of the system during a release.
- Simulate failures and observe system behavior.
We'll design a modular system with the following components:
- Feature Flag Guardrails Service: Validates feature flag configurations against defined policies.
- Dry Run orchestrator: Sets up a dry run environment, runs tests, and reports results.
- Risk Dashboard: Aggregates data from various sources (feature flags, past incidents, code changes, etc.) to calculate and display risk.
- Drill Manager: Schedules and runs drills, and collects results.
We assume we are building this as a set of microservices and a frontend dashboard.
Let's define the core models and APIs:
-
Feature Flag Guardrails:
Policy rules might include:
- All flags must have an owner and an expiration date.
- Flags in production must have a rollout plan (e.g., canary, gradual rollout).
- No flags should be left on after the intended experiment.
We can have a FeatureFlag model and a Policy model.
API endpoints (for the guardrails service):
- POST /policies: create a new policy (admin only)
- GET /policies: list policies
- POST /feature-flags/validate: validate a set of feature flags against active policies.
The validation endpoint would take a list of feature flags (with their current state) and return:
- A list of violations (if any)
- A pass/fail overall status.
-
Dry Run:
We need to:
- Clone the current production environment (or a subset) to a staging area.
- Deploy the candidate release (with feature flags set to the desired state for the dry run).
- Run a suite of tests (smoke, integration, performance, etc.)
- Collect metrics and logs.
We can have a DryRun model that tracks:
- id, status (queued, running, completed, failed), environment, start_time, end_time, results.
API endpoints:
- POST /dry-runs: create a new dry run (triggered by a release candidate)
- GET /dry-runs/{id}: get status and results.
The dry run orchestrator will:
- Provision a temporary environment (or use a pre-provisioned one).
- Deploy the release candidate (with feature flags set to the dry run configuration).
- Run tests and collect results.
- Tear down the environment.
-
Risk Dashboard:
This is a read-only service that aggregates data and calculates a risk score for a given release.
Factors for risk score might be:
- Number of feature flags changed.
- Complexity of changes (lines of code, number of services, etc.)
- Past failure rate of the services involved.
- Current system load (if available).
- Results from dry runs (if any).
We'll need to pull data from:
- Source control (code changes)
- Feature flag service (to know which flags are changing)
- Incident management system (past failures)
- Monitoring system (current load, error rates, etc.)
- Dry run results (if available)
The risk dashboard will have:
- An overall risk score (e.g., 0-100)
- Breakdown by factor.
API endpoints:
- GET /risk-scores?release_id={release_id}: get the risk score for a release.
-
Drills:
Drills are scheduled and run by the Drill Manager.
Types of drills might be:
- Chaos: randomly kill containers, increase latency, etc.
- Load: simulate high traffic.
- Feature flag failure: turn off a critical feature flag during the release.
We'll have a Drill model:
- id, type, target (service or infrastructure), schedule (cron or one-off), status (scheduled, running, completed, failed), results.
API endpoints:
- POST /drills: schedule a new drill (or run immediately)
- GET /drills: list drills
- GET /drills/{id}: get drill details and results.
The drill manager will:
- At the scheduled time, or on demand, run the drill in a controlled environment (could be the dry run environment or a separate one).
- Monitor the system and collect data on how it behaves.
- Report the results.
Integration:
The guild would be used as part of the release process:
- Before a release, the team creates a release candidate and triggers a dry run.
- The risk dashboard is consulted to see if the release is low risk enough.
- The team may run drills to test resilience.
- The feature flag guardrails are checked to ensure compliance.
All these steps can be gated in a CI/CD pipeline.
Implementation considerations:
We are going to build these as separate services, but they will need to communicate.
Let's define the data models more concretely.
Feature Flag Guardrails:
Policy:
- id (string)
- name (string)
- description (string)
- rule (string, e.g., "expiration_date must be within 30 days", "owner must be set")
- severity (low, medium, high)
FeatureFlag:
- id (string)
- name (string)
- description (string)
- owner (string)
- expiration_date (date)
- rollout_percentage (integer, 0-100)
- environment (string, e.g., production, staging)
ValidationResult:
- policy_id
- feature_flag_id
- passed (boolean)
- message (string)
Dry Run:
DryRun:
- id (string)
- release_candidate_id (string, e.g., git commit or build number)
- environment (string, e.g., "dry-run-123")
- status (enum: queued, provisioning, deploying, testing, analyzing, completed, failed)
- started_at (datetime)
- completed_at (datetime)
- results (json, could include test results, metrics, logs location, etc.)
Risk Dashboard:
RiskScore:
- release_id (string)
- overall_score (integer)
- factors (list of { factor: string, score: integer, weight: integer })
We'll need to collect:
Factor 1: Feature Flag Changes
- Count of feature flags changed in this release.
- Weight: 30% (example)
Factor 2: Code Complexity
- Lines of code changed, number of files, number of services.
- Weight: 20%
Factor 3: Past Incidents
- Number of incidents in the last 30 days for the services involved.
- Weight: 20%
Factor 4: Dry Run Results
- If dry run passed, lower risk; if failed, higher.
- Weight: 30%
The weights can be configurable.
Drills:
Drill:
- id (string)
- name (string)
- type (string)
- target (string, e.g., service name or infrastructure component)
- schedule (cron expression or one-off)
- last_run (datetime)
- status (enum: scheduled, running, completed, failed)
- results (json, including what happened, metrics, etc.)
We'll also need a way to tie these together for a release.
Let's introduce a Release model that represents a release candidate:
Release:
- id (string)
- version (string)
- commit_sha (string)
- created_at (datetime)
- status (enum: draft, in_review, rehearsing, approved, rejected, deployed)
- feature_flags (list of feature flag ids that are changed in this release)
- dry_run_id (string, nullable)
- risk_score_id (string, nullable)
- drills (list of drill ids that were run for this release)
Now, the workflow:
Step 1: Create a release (from CI/CD or manually). This records the commit and the feature flags that are being changed.
Step 2: Run feature flag guardrails validation on the release's feature flags.
Step 3: Create a dry run for the release. The dry run orchestrator will set up the environment and run tests.
Step 4: Calculate the risk score for the release, which will include the dry run results (if available) and other factors.
Step 5: Run drills (optional, but recommended for high-risk releases). The drill manager will run the drill and update the release.
Step 6: Based on the risk score and drill results, the release can be approved or rejected.
We'll build a frontend dashboard that shows:
- List of releases and their status.
- For a selected release:
* Feature flag validation results.
* Dry run status and results.
* Risk score and breakdown.
* Drill results (if any).
We'll also need an admin interface for managing policies, drill types, etc.
Technology stack:
We can use a common stack for all services (e.g., Python with FastAPI, or Node.js with Express) but they can be independent.
However, given the complexity, we might want to start with a monolith and then split.
Let's design the APIs in more detail.
We'll have the following services:
- Release Service (manages releases)
- Feature Flag Guardrails Service
- Dry Run Service
- Risk Service
- Drill Service
But note that the Release Service might be the central orchestrator, or each service might be independent and the Release Service aggregates.
Alternatively, we can have an event-driven architecture:
When a release is created, event: `release.created`
-> Feature Flag Guardrails Service listens and validates the flags, then publishes `feature_flags.validated`
-> Dry Run Service listens and starts a dry run, then publishes `dry_run.completed`
-> Risk Service listens to all events and recalculates risk, then publishes `risk.updated`
-> Drill Service can be triggered by a manual action or by risk score, then publishes `drill.completed`
Then the Release Service can update the release status based on these events.
This decouples the services and allows for scalability.
Let's define the events:
release.created: { release_id, version, commit_sha, feature_flags: [flag_id, ...] }
feature_flags.validated: { release_id, valid: boolean, violations: [ {policy_id, flag_id, message} ] }
dry_run.created: { release_id, dry_run_id }
dry_run.completed: { dry_run_id, release_id, passed: boolean, results: {...} }
drill.scheduled: { release_id, drill_id }
drill.completed: { drill_id, release_id, passed: boolean, results: {...} }
risk.updated: { release_id, risk_score: integer, factors: [...] }
The Release Service can then update the release:
On release.created: set status to "in_review" (or "rehearsing" if we want to start the process automatically)
On feature_flags.validated: if not valid, set status to "rejected" and note the violations.
On dry_run.completed: if the dry run failed, set status to "rejected" or keep in "rehearsing" for retry?
On risk.updated: if risk score is above a threshold, set status to "rejected", else if all checks passed, set to "approved".
Also, we can have a manual approval step.
However, note that the requirement says "release rehearsal guild", so it's about rehearsing and getting feedback, not necessarily automatic approval.
So maybe the release status is set to "rehearsal_complete" when all the steps (guardrails, dry run, risk, drills) are done, and then a human decides.
We can have:
release.rehearsal_complete event when all the required steps are done.
Then a human can review the dashboard and set the release to approved or rejected.
So the Release Service would have:
status: draft -> in_rehearsal -> rehearsal_complete -> approved -> deployed
Or we can have:
draft -> in_rehearsal -> (approved or rejected) -> deployed
And the rehearsal steps are required to get to approved.
Let's decide:
When a release is created, it's in "draft".
Then, when the release is submitted for rehearsal, we set to "in_rehearsal" and trigger the events.
The services do their work and publish events.
The Release Service updates the release and when all required steps are done (and passed), it sets status to "rehearsal_complete".
Then a human can approve or reject.
But note: the requirement says "drills", which might be optional? We can make them required for high-risk releases.
So the Release Service might have a rule:
If risk_score > threshold, then drills are required.
How to know if drills are required? Maybe the Drill Service can be triggered by the risk score.
Alternatively, the Release Service, upon receiving the risk.updated event, can check if drills are needed and then schedule them.
But then we are mixing responsibilities.
Let's keep the Release Service as the state machine and let it decide what steps are required.
Steps:
Step 1: feature flag guardrails (required for all releases with feature flags)
Step 2: dry run (required for all releases? maybe optional for very low risk, but let's say required)
Step 3: risk calculation (required)
Step 4: drills (if risk score above threshold, then required)
The Release Service can have a configuration:
required_steps = ['guardrails', 'dry_run', 'risk_calc']
conditional_steps = {
'drills': { condition: 'risk_score > 50' }
}
Then, when the release enters "in_rehearsal", the Release Service will:
- Send release.created event (with release details) to trigger guardrails and dry run and risk calc.
Then, when risk.updated comes, it checks if the condition for drills is met.
If risk_score > 50 and drills not yet run, then schedule a drill (by calling Drill Service? or publish an event?).
We don't want the Release Service to know about the Drill Service's API. So we can have:
The Release Service, upon seeing the risk score, publishes an event: `drill.required` with release_id and risk_score.
Then the Drill Service listens to that and schedules an appropriate drill.
But then how does the Release Service know when the drill is done? It will listen to drill.completed.
So the flow:
release.created
-> guardrails service validates -> feature_flags.validated
-> dry run service creates dry run -> dry_run.created, then dry_run.completed
-> risk service calculates risk (listening to feature_flags.validated and dry_run.completed) -> risk.updated
Release Service:
On release.created: set status to "in_rehearsal", and wait for events.
On feature_flags.validated: if invalid, set status to "rejected".
On dry_run.completed: if failed, set status to "rejected".
On risk.updated:
if risk_score > threshold and we haven't scheduled a drill, publish `drill.required`.
else if all required steps are done and risk_score is acceptable, set status to "rehearsal_complete".
On drill.completed: if drill failed, set status to "rejected", else if this was the last required step, set status to "rehearsal_complete".
But note: the risk service might need to wait for the drill to complete to include drill results in the risk score?
Actually, the risk score might be calculated before the drill, and then the drill is an additional step that can fail the release.
Alternatively, the risk score could be recalculated after the drill? But then we have a loop.
Let's keep it simple:
The risk score is calculated without drill results (since drills are run after the risk score is known to decide if we need them).
Then, if a drill is run and it fails, we reject the release.
So the risk score is one factor, but the drill is an independent test.
Now, let's design the services:
Release Service:
Models:
Release:
id: string (uuid)
version: string
commit_sha: string
created_at: datetime
status: string (draft, in_rehearsal, rehearsal_complete, approved, rejected, deployed)
feature_flags: [string] (list of feature flag ids)
dry_run_id: string (nullable)
risk_score: integer (nullable)
drill_ids: [string] (nullable)
Endpoints:
POST /releases: create a new release (draft status)
GET /releases: list releases
GET /releases/{id}: get release details
PATCH /releases/{id}: update release (e.g., set to "approved" or "rejected" by human)
Also, internal endpoints for events? Or we can use a message broker.
We'll use a message broker (like RabbitMQ or Kafka) for events.
Each service will have:
- Its own database (if needed)
- An event consumer and producer.
Let's define the event schema (using JSON):
event_type: string
event_id: string (uuid)
timestamp: datetime
payload: object (specific to the event)
Example events:
release.created:
payload: { release_id, version, commit_sha, feature_flags: [flag_id] }
feature_flags.validated:
payload: { release_id, valid: boolean, violations: [ {policy_id, flag_id, message} ] }
dry_run.created:
payload: { release_id, dry_run_id }
dry_run.completed:
payload: { dry_run_id, release_id, passed: boolean, results: { ... } }
risk.updated:
payload: { release_id, risk_score: integer, factors: [ {factor: string, score: integer, weight: integer} ] }
drill.required:
payload: { release_id, risk_score: integer, reason: string }
drill.completed:
payload: { drill_id, release_id, passed: boolean, results: { ... } }
The Release Service will consume all events and update the release accordingly.
Now, let's outline each service's responsibilities:
Feature Flag Guardrails Service:
- Stores policies.
- Listens to release.created (or maybe we validate on demand? but better to listen and then validate and publish result).
How does it get the feature flag details? It might need to call the feature flag management system (like LaunchDarkly) to get the current state of the flags.
We can have:
On release.created event, the Release Service includes the list of feature flag ids that are changed.
The Guardrails Service will fetch the details of those flags from the feature flag system (or the release might include the details? but that might be too much).
Alternatively, the release might not need to include the flag details. The Guardrails Service can get the current state of the flags in the target environment (e.g., production) and the intended changes (which might be in the release's feature_flags list?).
Actually, the release's feature_flags list might just be the ids of flags that are being changed. But the Guardrails Service needs to know the intended state? Or just the current state?
We want to validate that the release's changes are safe. So we need to know the intended state of the flags (after the release) and the current state.
How about:
The release includes the intended state of the feature flags? That might be too heavy.
Alternatively, the Guardrails Service can compare the current state (from the feature flag system) and the intended state (which might be in the release's configuration, e.g., the deployment plan).
But note: the release might change the flag's rollout percentage, owner, etc.
So we need the intended state.
We can have the release include:
feature_flags: [
{ id: "flag1", intended_rollout_percentage: 50, intended_owner: "team1", ... }
]
Then the Guardrails Service can validate the intended state against the policies.
Also, the Guardrails Service might need to know the environment (production, staging, etc.) but the release is for production?
We assume the release is for production.
So:
The Guardrails Service, on release.created, will:
1. For each flag in release.feature_flags, fetch the current state from the feature flag system (or use the current state provided? but we want to validate the change).
2. Check the policies against the intended state (from the release) and also maybe the change (e.g., if the flag is being turned on for the first time, that might be high risk).
3. Publish feature_flags.validated with the results.
But note: the Guardrails Service might not have access to the feature flag system? We assume it does.
Dry Run Service:
- Listens to release.created.
- Sets up a dry run environment (maybe using a template or cloning production).
- Deploys the release candidate (with the intended feature flag states? or just the code?).
Actually, the dry run should simulate the release as it would be in production, including feature flag states.
So the release should include the feature flag states (or the dry run service can get them from the Guardrails Service?).
We have a chicken-and-egg: we want to dry run with the same feature flag states that we are releasing.
So the release should include the intended feature flag states.
The Guardrails Service already has the intended states (from the release) and validates them.
The Dry Run Service will use the same intended states.
How does the Dry Run Service get the intended states? It can get from the release event? Or from the Guardrails Service?
We can have the release event include the intended states.
Or, the Dry Run Service can subscribe to release.created and get the release details (which include the intended states).
Then:
Dry Run Service:
On release.created:
1. Create a dry run record (status: queued).
2. Provision an environment (maybe using Terraform or Kubernetes).
3. Deploy the release candidate (using the same deployment process as production, but to the dry run environment) and set the feature flags to the intended states (how? maybe via the feature flag API, or via configuration).
4. Run tests (we need a test suite defined for the application).
5. Collect metrics (response times, error rates, etc.)
6. Publish dry_run.completed with the results.
The Dry Run Service might need to know:
- How to deploy the release candidate (e.g., docker image, kubernetes manifests, etc.)
- How to set the feature flags (we can use the feature flag API to set the flags in the dry run environment? but note: the dry run environment might be isolated and have its own feature flag system? or we use the same?).
We need to isolate the dry run environment. So we should have a separate feature flag system for the dry run? Or we can use the same but with a different environment key.
Let's assume the feature flag system supports multiple environments (like production, staging, dry-run-<id>).
Then:
- The Dry Run Service creates a new environment in the feature flag system (or uses an existing one) and sets the flags accordingly.
Alternatively, the Dry Run Service can mock the feature flags? But we want to test the real integration.
So we need to set the flags in the dry run environment.
Risk Service:
- Listens to feature_flags.validated and dry_run.completed.
- Also listens to other events? Like code changes? We might need to get the code change data from the release (which might have the commit_sha).
The Risk Service can:
On release.created, it can fetch the code changes (from git) and calculate the complexity factor.
But then it would need to wait for the other events.
Alternatively, the Risk Service can recalculate the risk when it receives any of the events.
We can have:
The Risk Service listens to:
release.created: initial risk calculation (without dry run and without validation? but we have the feature flags list, so we can calculate the flag change factor and code complexity, but we don't have the validation results yet).
feature_flags.validated: update the risk factor for feature flags (if there are violations, increase risk).
dry_run.completed: update the risk factor for dry run (if passed, decrease risk; if failed, increase).
Then, after each event, recalculate the overall risk and publish risk.updated.
But note: the risk score might change multiple times.
We can store the current risk score for the release and update it.
How to get code complexity? We need to analyze the commit (diff). We can do that on release.created.
Steps for Risk Service on release.created:
1. Fetch the commit (using commit_sha) and calculate:
- Lines of code changed.
- Number of files changed.
- Number of services affected (maybe from the repository structure or from the deployment manifest).
2. Calculate the feature flag change factor (count of flags changed).
3. Set initial risk score (without validation and dry run).
Then, when feature_flags.validated comes:
4. Increase risk score for each violation (by severity).
Then, when dry_run.completed comes:
5. If passed, reduce risk by a factor; if failed, increase risk.
Then, we can also factor in past incidents (from an incident management system) for the services involved.
We might need to fetch that data on release.created and cache it.
So the Risk Service will have to call external APIs (like git, incident management, monitoring) to get the data.
This might be heavy, but we can do it asynchronously.
Drill Service:
- Listens to drill.required events.
- Schedules a drill (immediately or for a later time? the event might be time-sensitive, so we run immediately).
The drill.required event includes the release_id and risk_score.
The Drill Service will:
1. Choose a drill type based on the risk factors (e.g., if the release changes a database, run a database chaos drill).
2. Schedule the drill to run in the dry run environment? Or in a separate environment?
We want to run the drill in an environment that is as close to production as possible, but we don't want to disrupt the dry run.
We can have a separate environment for drills? Or run the drill after the dry run in the same environment? But then the dry run might have already torn down.
Alternatively, we can run the drill during the dry run? But the dry run is already running tests.
We might want to run the drill as an additional test in the dry run environment.
So:
The Dry Run Service could be extended to support running drills? But that would mix responsibilities.
Let's keep the Drill Service independent.
The Drill Service will:
- Provision a drill environment (or use the dry run environment if it's still available?).
But the dry run environment might be torn down after the dry run.
So we need a persistent environment for drills? Or we can run the drill in production? That's too risky.
We can have:
The Drill Service uses the same environment that the Dry Run Service used? But the Dry Run Service might not keep it.
Alternatively, we can have a long-running staging environment that is a clone of production, and we run drills there.
Let's assume we have a "staging" environment that is always available and mirrors production.
Then:
The Drill Service will run the drill in the staging environment.
But note: the release candidate might not be deployed in staging? The dry run might have been done in a temporary environment.
We can have:
The Dry Run Service deploys to a temporary environment, runs tests, and then tears down.
Then the Drill Service deploys the same release candidate to the staging environment (which is persistent) and runs the drill.
But then we are deploying twice.
Alternatively, we can have the Dry Run Service not tear down the environment, and then the Drill Service uses that same environment.
But then we need coordination.
Let's change the dry run:
The Dry Run Service will:
- Provision a temporary environment.
- Deploy the release candidate and run tests.
- Then, instead of tearing down, it marks the environment as "available for drills" and publishes an event: dry_run.environment_ready with the environment details.
Then the Drill Service can listen to that and run the drill in that environment.
After the drill, the Dry Run Service can tear down.
But then the Dry Run Service is responsible for the environment's lifecycle until the drill is done?
Alternatively, we can have a separate service for environment management.
Given the complexity, let's simplify:
We'll have a "Rehearsal Environment" that is long-running and always available (like a staging environment that is kept up-to-date with production).
Then:
The Dry Run Service will deploy the release candidate to this rehearsal environment (overwriting the current state) and run tests.
Then, the Drill Service will run drills in the same rehearsal environment (without redeploying).
But then the dry run might have changed the state (like database) and the drill might be affected.
We need to reset the environment after each dry run?
This is getting complex.
Given the time, let's assume:
We have a temporary environment for each release (dry run) that is torn down after the release is approved or rejected.
The drill will be run in that same temporary environment, but after the dry run tests.
So:
Dry Run Service:
1. Provision environment.
2. Deploy release candidate and set feature flags.
3. Run tests (dry run tests).
4. Publish dry_run.completed (with passed/failed) but does not tear down yet.
5. Waits for a signal to tear down (maybe after the drill?).
Then, the Release Service, upon receiving dry_run.completed and if the release is still in rehearsal and requires a drill, will publish drill.required.
The Drill Service will then run the drill in the same environment (using the environment id from the dry_run.completed event?).
Then, after the drill, the Drill Service publishes drill.completed.
Then, the Release Service can signal the Dry Run Service to tear down the environment.
We need an event for tear down? Or the Dry Run Service can tear down after a timeout?
Alternatively, the Dry Run Service can tear down when it receives an event from the Release Service: release.rehearsal_complete or release.rejected.
But then the Dry Run Service must track which environment belongs to which release.
We can have:
The Dry Run Service, when it creates a dry run, stores the environment id with the dry run.
Then, when the Release Service decides the release is done (either approved and deployed, or rejected), it can tell the Dry Run Service to tear down.
But the Release Service doesn't know about the Dry Run Service's API.
We can have:
The Release Service publishes an event: release.rehearsal_complete (or release.rejected) and the Dry Run Service listens to that and tears down the environment for that release.
So:
Dry Run Service:
On release.created:
- create dry run record (status: provisioning)
- provision environment, store environment_id in dry_run record.
- deploy and run tests.
- when tests are done, set dry_run status to completed and publish dry_run.completed.
On release.rehearsal_complete or release.rejected:
- tear down the environment for that release (if it exists).
Then the Drill Service can use the environment from the dry run? But the dry run might have completed and the environment is still up until the release is done.
So the Drill Service can:
On drill.required:
- Get the release's dry_run (from the Release Service? or from the dry_run.completed event we stored the dry_run_id in the release?).
We can have the Release Service store the dry_run_id in the release record.
Then the Drill Service, on drill.required, can:
1. Get the release from the Release Service (or from its own event) to get the dry_run_id.
2. Then get the dry run from the Dry Run Service (by dry_run_id) to get the environment_id.
3. Run the drill in that environment.
But then the Drill Service needs to call the Dry Run Service's API to get the environment.
Alternatively, the Dry Run Service can publish the environment_id in the dry_run.completed event, and the Release Service can store that in the release.
Then the Drill Service, on drill.required, can get the release (from the event) and then get the environment_id from the release.
So:
In the Release Service, when it receives dry_run.completed, it updates the release with the dry_run_id and maybe the environment_id? Or just the dry_run_id.
Then, when the Drill Service gets drill.required, it can get the release (by release_id) and then get the dry_run_id, and then call Dry Run Service to get the environment_id? Or we can store the environment_id in the release?
Let's store the environment_id in the release? But the release might have multiple dry runs? We assume one dry run per release.
So:
Release model:
dry_run_id: string (nullable)
Then, the Drill Service, to get the environment_id, must call Dry Run Service: GET /dry-runs/{dry_run_id} to get the environment_id.
That's an extra call.
Alternatively, we can have the dry_run.completed event include the environment_id, and the Release Service stores that in the release as well.
Then the Drill Service can get the release (by release_id) and get the environment_id directly.
So:
Release model:
dry_run_id: string
environment_id: string (nullable)
Then, when the Release Service receives dry_run.completed, it sets both.
Then the Drill Service can:
On drill.required:
1. Get the release (by release_id from the event) from the Release Service.
2. Get the environment_id from the release.
3. Run the drill in that environment.
This seems reasonable.
However, note that the dry run might fail, and we might not have an environment? But if the dry run failed, we might not want to run a drill?
We can decide: only run drills if the dry run passed? Or run drills regardless?
The drill is to test the release's resilience, so even if the dry run passed, we might want to run a drill to see how it handles failures.
But if the dry run failed, we probably don't want to run a drill? Because the release is already bad.
So:
The Release Service, when it gets dry_run.completed and it failed, sets the release to rejected and doesn't schedule a drill.
If the dry run passed, then we calculate risk and then decide on drill.
So the drill.required event will only be published if the dry run passed and the risk score is high.
Now, let's summarize the events and state transitions:
Release status: draft -> in_rehearsal -> rehearsal_complete -> approved -> deployed
or in_rehearsal -> rejected
Events and actions:
release.created (from Release Service when a release is submitted for rehearsal)
Guardrails Service:
- validates feature flags (using the intended states from the release.event)
- publishes feature_flags.validated
Dry Run Service:
- creates dry run and provisions environment, deploys, runs tests.
- publishes dry_run.completed (with passed/failed)
Risk Service:
- on release.created: calculates initial risk (code complexity, flag changes) and publishes risk.updated.
- on feature_flags.validated: recalculates risk (with violations) and publishes risk.updated.
- on dry_run.completed: recalculates risk (with dry run result) and publishes risk.updated.
Release Service (event consumers):
On feature_flags.validated:
if not valid -> set release status to rejected.
On dry_run.completed:
if not passed -> set release status to rejected.
else -> update release with dry_run_id and environment_id.
On risk.updated:
store the risk score in the release.
if risk_score > threshold and no drill has been scheduled for this release, then publish drill.required.
On drill.completed:
if not passed -> set release status to rejected.
else -> if all required steps are done (and passed) and no pending conditions, set release status to rehearsal_complete.
Also, on drill.required, the Release Service might need to track that a drill was scheduled? We can store a list of drill_ids in the release.
But the Drill Service will publish drill.completed, so we know when it's done.
Drill Service:
On drill.required:
- get the release (by release_id) to get the environment_id.
- run the drill in that environment.
- publish drill.completed.
This seems like a lot of events and state to manage.
Given the complexity, we might want to start with a simpler version:
Only have:
1. Feature flag guardrails (with validation)
2. Dry run (with tests)
3. Risk dashboard (that aggregates data but doesn't automatically reject)
4. Drills (manual, not triggered automatically)
And then let the human decide based on the risk dashboard and drill results.
But the requirement says "guardrails", which implies automatic rejection if policies are violated.
So we keep the automatic rejection for guardrails and dry run failures.
For risk and drills, we can just provide the information and let the human decide.
Alternatively, we can have a configurable threshold for risk and drills.
Let's adjust:
The Release Service will:
- Automatically reject if:
* Feature flag validation fails.
* Dry run fails.
- For risk: if the risk score is above a threshold (configurable, maybe by team), then require a drill? Or just warn?
We can have:
The risk service publishes risk.updated, and the Release Service stores the risk score.
Then, if the risk score is above a threshold, the Release Service can set a flag: high_risk = true.
Then, if high_risk and no drill has been run, then the Release Service can require a drill?
But how does the Release Service know if a drill has been run? We can store drill_ids in the release.
We can have:
The Release Service, on risk.updated, if risk_score > threshold and no drill scheduled, then:
- Set a field in the release: requires_drill = true.
Then, when a human tries to approve the release, we check: if requires_drill and no drill completed, then block approval.
Alternatively, we can automatically schedule a drill? But the drill might take time.
Let's have:
The Release Service, when risk_score > threshold, automatically publishes drill.required.
Then, the drill is required to pass for the release to be approved.
So:
The release status can be:
in_rehearsal -> (if all required steps passed) -> rehearsal_complete
And the required steps are:
- feature_flags.validated (passed)
- dry_run.completed (passed)
- if risk_score > threshold: drill.completed (passed)
Then, when all required steps are done and passed, the release status becomes rehearsal_complete.
Then a human can approve.
So the Release Service will track:
release.feature_flags_passed: boolean (from feature_flags.validated)
release.dry_run_passed: boolean (from dry_run.completed)
release.drill_passed: boolean (from drill.completed) [if required]
And then, when all are true, set status to rehearsal_complete.
But note: the feature_flags.validated might have multiple violations? We set passed to false if any violation.
So:
On feature_flags.validated:
if valid -> set release.feature_flags_passed = true
else -> set release.feature_flags_passed = false and status = rejected.
On dry_run.completed:
if passed -> set release.dry_run_passed = true
else -> set release.dry_run_passed = false and status = rejected.
On drill.completed (if required):
if passed -> set release.drill_passed = true
else -> set release.drill_passed = false and status = rejected.
Then, if all required steps are passed, set status to rehearsal_complete.
How does the Release Service know if a drill is required? It can check the risk score (which it stores) and a threshold.
We can have a config for the threshold.
So:
When risk.updated comes, store the risk_score.
Then, if risk_score > threshold, set release.requires_drill = true.
Then, when we are checking if all required steps are done, we check:
required_steps = ['feature_flags_passed', 'dry_run_passed']
if release.requires_drill:
required_steps.append('drill_passed')
if all required_steps are true -> rehearsal_complete.
But note: the drill might not have been scheduled yet when we get the risk.updated. So we need to schedule it.
We can have:
On risk.updated:
if risk_score > threshold and not release.requires_drill:
set release.requires_drill = true
publish drill.required
Then, the drill will run and publish drill.completed, which will set release.drill_passed.
Then, when all required steps are true, set to rehearsal_complete.
This seems workable.
Now, let's design the database schema for the Release Service:
Table: releases
id (uuid, primary key)
version (string)
commit_sha (string)
created_at (datetime)
status (string)
feature_flags (json array of flag objects? or just ids? We'll store the intended states as json)
But note: the feature flags might change between the time of release creation and the guardrails validation?
We want to validate the intended state at the time of release creation.
So we store the intended state in the release.
feature_flags: [
{ "id": "flag1", "rollout_percentage": 50, "owner": "team1", ... }
]
dry_run_id (string, nullable)
environment_id (string, nullable) # from dry_run.completed
risk_score (integer, nullable)
requires_drill (boolean, default false)
drill_passed (boolean, nullable) # null if not required or not run
feature_flags_passed (boolean, nullable)
dry_run_passed (boolean, nullable)
We also need to store the drill_id? We can store a list of drill_ids if multiple drills? But one release one drill? Let's assume one drill per release.
drill_id (string, nullable)
Then, the Release Service will update these fields based on events.
Now, the other services:
Feature Flag Guardrails Service:
Table: policies
id (uuid)
name (string)
description (string)
rule (string) # we can store as a string that we evaluate, or we can have a fixed set of rules? For simplicity, let's have a fixed set of rule types and parameters.
We can have:
rule_type: string (e.g., "expiration_within_days", "owner_required")
parameters: json (e.g., { "days": 30 })
Then the validation logic for each rule type.
Table: validation_results (if we want to store history)
id, release_id, policy_id, flag_id, passed, message
But we might not need to store if we just publish events.
We can store the validation results for auditing.
Dry Run Service:
Table: dry_runs
id (uuid)
release_id (uuid, foreign key to releases? but we don't have a direct link? We can store release_id)
environment (string)
status (string)
started_at (datetime)
completed_at (datetime)
results (json)
Risk Service:
We can store the risk score history?
Table: risk_scores
id
release_id
score
factors (json)
calculated_at
But we might just calculate on the fly and publish events. We can store the latest for the dashboard.
Drill Service:
Table: drills
id
release_id
type
environment (string? or we can get from release's environment_id)
status
started_at
completed_at
results (json)
Now, the frontend dashboard:
We need to show:
- List of releases with status, risk score, and whether they passed the rehearsal steps.
- For a release, show:
* Feature flag validation results (list of violations).
* Dry run results (logs, test results, metrics).
* Risk score breakdown.
* Drill results (if any).
We can build a simple React app that calls the Release Service API to get the release details, and then calls the other services for details.
Or we can have the Release Service aggregate all the data for a release and provide a single endpoint.
Since the Release Service is the state machine, it can have:
GET /releases/{id}/details
that returns:
{
release: { ... },
feature_flags: [ { flag_id, intended_state, validation: { passed, violations } } ],
dry_run: { ... },
risk_score: { score, factors },
drill: { ... }
}
The Release Service would have to fetch from the other services (or have the data pushed to it).
Given the event-driven design, the Release Service might not have all the details. We can have it store the necessary data (like validation results, dry run results, etc.) when it receives the events.
So:
On feature_flags.validated, store the validation results in the release? Or in a separate table? We can store in the release as:
release.feature_flags_validation: json (array of violations)
On dry_run.completed, store the dry run results in the release? Or just the dry_run_id? We can store the summary:
release.dry_run_passed: boolean
release.dry_run_results: json (maybe just the summary, not the full logs)
Similarly for drill.
Then the Release Service can provide all in one endpoint.
But then we are duplicating data. However, for the dashboard, we want a quick view.
Alternatively, the dashboard can call each service separately.
Since we are building a guild, we might want to have a separate dashboard service that aggregates data from all services.
Let's create a Dashboard Service that:
- Listens to all events and builds a read model for releases and their details.
- Provides an API for the frontend.
This is a common pattern: write model (the services) and read model (the dashboard).
So:
Each service publishes events.
The Dashboard Service consumes all events and updates its own database (denormalized) for quick queries.
Then the frontend calls the Dashboard Service.
This way, the Release Service doesn't have to aggregate.
We'll have:
Dashboard Service:
Table: release_details
release_id (primary key)
release_version
commit_sha
status
feature_flags_validation (json)
dry_run (json)
risk_score (json)
drill (json)
And it updates this table on every event.
Then the frontend:
GET /dashboard/releases -> list of releases (with summary)
GET /dashboard/releases/{id} -> full details.
This is more scalable for the dashboard.
Given the complexity, we might want to start with the event-driven architecture and the Dashboard Service.
Now, let's write the code for one of the services? But the question is to design, not to code.
However, the instruction says "Build", so we might need to provide some code.
Since this is a design, we'll outline the services and their main components.
But the user might expect some code.
Given the time, we can write a skeleton for the Release Service and the event handling.
Let's write the Release Service in Python with FastAPI and use RabbitMQ for events.
We'll assume we have a common event bus.
Steps:
1. Set up FastAPI app.
2. Define the Release model (using SQLAlchemy).
3. Define endpoints for creating a release and getting releases.
4. Set up a RabbitMQ consumer for the events we care about.
5. In the event handlers, update the release state accordingly.
But note: the Release Service also publishes events?
- It publishes release.created when a release is created (if we are using the event-driven flow, the creation of a release might be done via an endpoint, and then we publish the event).
- It also publishes release.rehearsal_complete and release.rejected?
We can have:
When the release status changes to rehearsal_complete or rejected, we publish an event.
Then other services might listen? But in our design, only the Dashboard Service and maybe the user-facing system need to know.
We can publish:
release.rehearsal_complete: { release_id }
release.rejected: { release_id, reason }
Let's code the Release Service:
We'll use:
FastAPI, SQLAlchemy, aio-pika (for RabbitMQ)
But note: the code will be long, so we'll just outline.
Alternatively, we can write a simpler version without the event bus, but that would not be the intended design.
Given the complexity, we might just write the design and not the full code.
But the user said "Build", so we should provide some code.
Let's write the Release Service with event handling in a simplified manner.
We'll create:
models.py (SQLAlchemy models)
main.py (FastAPI app and event consumers)
We'll assume we have a RabbitMQ connection.
Steps:
- On startup, connect to RabbitMQ and start consuming events.
- We'll have queues for each event type? Or one queue and filter by event_type?
We can have one queue for the Release Service and bind to multiple exchanges by event_type.
But to keep it simple, we'll have one queue and consume all events, then route by event_type.
Let's code:
main.py:
We'll have:
app = FastAPI()
# Database setup
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# RabbitMQ setup
connection = ...
# After startup, we start consuming events.
@app.on_event("startup")
async def startup_event():
# Start consuming events in a background task.
asyncio.create_task(consume_events())
async def consume_events():
# Connect to RabbitMQ and start consuming.
Then, we define event handlers.
But note: we are using async, so we need to be careful with database sessions.
Given the complexity, we might just write the synchronous version? But FastAPI is async.
Alternatively, we can use a separate thread for the event consumer.
Let's do:
We'll run the event consumer in a separate thread, and use a thread-safe database session? Or we can use an async database driver?
We'll use aiosqlite for SQLite for simplicity, or asyncpg for PostgreSQL.
But to keep it simple, let's assume we use SQLite and the database operations are fast, so we can do in the async event loop.
However, the event consumer will run in a separate task (asyncio) and we can use the same async database session.
We'll use databases library for async database access.
But to avoid adding too many dependencies, let's use SQLAlchemy with async:
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
We'll do:
engine = create_async_engine(DATABASE_URL, echo=True)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
Then in the event handler:
async with AsyncSessionLocal() as session:
# do database work
Now, the event types we care about:
"feature_flags.validated"
"dry_run.completed"
"risk.updated"
"drill.completed"
We'll create a function for each.
We'll also handle "release.created" but that one we publish ourselves? Actually, the Release Service might not publish release.created?
In our design, the Release Service publishes release.created when a release is created via the API.
So:
@app.post("/releases")
async def create_release(release: ReleaseCreate):
# create release in database with status "draft"
# then set status to "in_rehearsal" and publish release.created event.
But note: the release might be created by a user and then submitted for rehearsal? Or automatically?
We can have:
POST /releases -> creates a draft.
POST /releases/{id}/submit -> sets status to in_rehearsal and publishes release.created.
Or we can have:
When creating a release, we can have a flag: `submit_for_rehearsal: boolean` and if true, then set to in_rehearsal and publish.
Let's do:
POST /releases
body: { version, commit_sha, feature_flags: [...] }
if query param ?submit=true or body has "submit": true, then set status to in_rehearsal and publish event.
else, status = draft.
Then, we can have:
PATCH /releases/{id}/status to change status manually.
Now, the event handlers:
async def handle_feature_flags_validated(event):
release_id = event["release_id"]
valid = event["valid"]
violations = event["violations"]
async with AsyncSessionLocal() as session:
release = await session.get(Release, release_id)
if not release:
return
if not valid:
release.status = "rejected"
# store the violations? we can store in release.feature_flags_validation
release.feature_flags_validation = violations
else:
release.feature_flags_passed = True
await session.commit()
Similarly for dry_run.completed:
if not passed:
release.status = "rejected"
release.dry_run_passed = False
else:
release.dry_run_passed = True
release.dry_run_id = event["dry_run_id"]
release.environment_id = event.get("environment_id") # if we have it
For risk.updated:
release.risk_score = event["risk_score"]
# store the factors?
release.risk_factors = event["factors"]
# Check if we need to schedule a drill:
threshold = 50 # from config
if release.risk_score > threshold and not release.requires_drill:
release.requires_drill = True
# publish drill.required event
await publish_event("drill.required", {"release_id": release_id, "risk_score": release.risk_score})
# Then check if we can set to rehearsal_complete:
await check_and_set_rehearsal_complete(release)
For drill.completed:
release.drill_passed = event["passed"]
release.drill_id = event["drill_id"]
release.drill_results = event["results"]
if not event["passed"]:
release.status = "rejected"
else:
await check_and_set_rehearsal_complete(release)
The function check_and_set_rehearsal_complete:
required = ['feature_flags_passed', 'dry_run_passed']
if release.requires_drill:
required.append('drill_passed')
if all(getattr(release, field) for field in required):
release.status = "rehearsal_complete"
# publish release.rehearsal_complete event
This is the core logic.
We also need to handle the case when the release is already rejected or completed.
Now, the code for the Release Service would be long, but this is the gist.
Given the time, we'll stop the design here.
We have:
- Event-driven architecture with multiple services.
- Release Service as the state machine.
- Dashboard Service for read model.
We haven't designed the other services in code, but they would have similar event consumers.
For the Feature Flag Guardrails Service:
It would have:
- Policies CRUD.
- On release.created, it would:
- Fetch the feature flags from the release (the intended states) and also fetch the current state from the feature flag system.
- For each policy, check the intended state (and maybe the change) and collect violations.
- Publish feature_flags.validated.
For the Dry Run Service:
- On release.created:
- Create a dry run record (status: provisioning).
- Provision environment (using some infrastructure code).
- Deploy the release candidate (how? we need to know the deployment method. We can assume it's a Kubernetes deployment and we have a chart or manifest for the release candidate).
- Set the feature flags in the environment (using the feature flag API for that environment).
- Run tests (we need a test suite defined. We can have a configuration for each service that says how to test it).
- When tests are done, update dry run record and publish dry_run.completed.
- On release.rehearsal_complete or release.rejected, tear down the environment.
For the Risk Service:
- On release.created:
- Fetch the commit (using the commit_sha) and calculate:
lines_changed, files_changed, services_affected.
- Calculate initial risk score (using a formula that weights these factors).
- Publish risk.updated.
- On feature_flags.validated:
- Adjust risk score for violations (by severity).
- Publish risk.updated.
- On dry_run.completed:
- Adjust risk score for dry run result (if passed, reduce by X, if failed, increase by Y).
- Publish risk.updated.
We might also want to factor in past incidents and current system load. We can fetch from external APIs on release.created and cache.
For the Drill Service:
- On drill.required:
- Get the release (to get the environment_id).
- Choose a drill type based on the risk factors (e.g., if the release changes a database, run a database drill).
- Run the drill in the environment (e.g., kill a pod, increase latency, etc.)
- Monitor the system and determine if the drill passed (based on SLOs, like error rate, latency, etc.)
- Publish drill.completed.
The Dashboard Service:
- Consumes all events and builds a denormalized view of each release.
- Provides API for the frontend.
Frontend:
- Simple dashboard showing releases and their status, with links to details.
This is a high-level design.
Given the complexity, we might want to start with a minimal viable product:
- Only feature flag guardrails and dry run, and a simple dashboard that shows the status and results.
Then add risk and drills later.
But the requirement includes all four.
We have designed an event-driven system that can be implemented in pieces.
Now, we should provide some code for the Release Service as an example.
Let's write a simplified version of the Release Service with the event handling for the state machine.
We'll use SQLite for simplicity.
We'll create:
release_service.py
We'll not implement the RabbitMQ part fully, but outline the event handling.
We'll use aio-pika for RabbitMQ.
But note: the user might not want to run RabbitMQ? We can use an in-memory event bus for example.
Given the time, we'll write the state machine logic and assume we have an async event bus.
Alternatively, we can write a synchronous version with Flask and a simple in-memory event bus? But the design is async.
Let's write the Release Service with FastAPI and async, and assume we have a function publish_event and consume_events.
We'll write the database models with SQLAlchemy async.
Steps:
1. Create the Release model.
2. Create the FastAPI app.
3. Define the endpoint to create a release.
4. Define the event handlers.
We'll skip the RabbitMQ connection code and just write the handlers.
Here is a skeleton:
release_service.py:
import asyncio
from fastapi import FastAPI, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from sqlalchemy import Column, String, Boolean, Integer, JSON, DateTime
from datetime import datetime
import json
Base = declarative_base()
class Release(Base):
__tablename__ = "releases"
id = Column(String, primary_key=True, index=True)
version = Column(String)
commit_sha = Column(String)
created_at = Column(DateTime, default=datetime.utcnow)
status = Column(String, default="draft") # draft, in_rehearsal, rehearsal_complete, approved, rejected, deployed
feature_flags = Column(JSON) # list of intended feature flag states
dry_run_id = Column(String, nullable=True)
environment_id = Column(String, nullable=True)
risk_score = Column(Integer, nullable=True)
requires_drill = Column(Boolean, default=False)
drill_passed = Column(Boolean, nullable=True)
feature_flags_passed = Column(Boolean, nullable=True)
dry_run_passed = Column(Boolean, nullable=True)
# We can also store the validation results, dry run results, etc. but we might not need to if we have a dashboard service.
DATABASE_URL = "sqlite+aiosqlite:///./release_service.db"
engine = create_async_engine(DATABASE_URL, echo=True)
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
app = FastAPI()
@app.on_event("startup")
async def startup():
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
# Start the event consumer in the background.
asyncio.create_task(event_consumer())
@app.post("/releases")
async def create_release(version: str, commit_sha: str, feature_flags: list, submit: bool = False):
release_id = ... generate uuid ...
async with AsyncSessionLocal() as session:
release = Release(
id=release_id,
version=version,
commit_sha=commit_sha,
feature_flags=feature_flags,
status="in_rehearsal" if submit else "draft"
)
session.add(release)
await session.commit()
await session.refresh(release)
if submit:
# Publish release.created event
await publish_event("release.created", {
"release_id": release_id,
"version": version,
"commit_sha": commit_sha,
"feature_flags": feature_flags
})
return {"release_id": release_id, "status": release.status}
# We assume we have a function publish_event that sends to RabbitMQ.
async def event_consumer():
# Connect to RabbitMQ and consume events.
# For each event, call the appropriate handler.
pass
async def handle_feature_flags_validated(event):
release_id = event["release_id"]
valid = event["valid"]
violations = event.get("violations", [])
async with AsyncSessionLocal() as session:
release = await session.get(Release, release_id)
if not release:
return
if not valid:
release.status = "rejected"
# We can store the violations in the release? or in a separate table? For simplicity, we don't store.
else:
release.feature_flags_passed = True
await session.commit()
# Check if we can set to rehearsal_complete?
await check_and_set_rehearsal_complete(release)
async def handle_dry_run_completed(event):
release_id = event["release_id"]
passed = event["passed"]
dry_run_id = event.get("dry_run_id")
environment_id = event.get("environment_id")
async with AsyncSessionLocal() as session:
release = await session.get(Release, release_id)
if not release:
return
if not passed:
release.status = "rejected"
release.dry_run_passed = False
else:
release.dry_run_passed = True
release.dry_run_id = dry_run_id
release.environment_id = environment_id
await session.commit()
await check_and_set_rehearsal_complete(release)
async def handle_risk_updated(event):
release_id = event["release_id"]
risk_score = event["risk_score"]
factors = event.get("factors")
async with AsyncSessionLocal() as session:
release = await session.get(Release, release_id)
if not release:
return
release.risk_score = risk_score
# Store factors? maybe not necessary.
# Check if we need to schedule a drill.
threshold = 50 # from config
if risk_score > threshold and not release.requires_drill:
release.requires_drill = True
await session.commit()
# Publish drill.required event
await publish_event("drill.required", {
"release_id": release_id,
"risk_score": risk_score
})
await check_and_set_rehearsal_complete(release)
async def handle_drill_completed(event):
release_id = event["release_id"]
passed = event["passed"]
drill_id = event.get("drill_id")
results = event.get("results")
async with AsyncSessionLocal() as session:
release = await session.get(Release, release_id)
if not release:
return
release.drill_passed = passed
release.drill_id = drill_id
if not passed:
release.status = "rejected"
else:
await check_and_set_rehearsal_complete(release)
await session.commit()
async def check_and_set_rehearsal_complete(release: Release):
# This function checks if all required steps are passed and sets the status to rehearsal_complete.
required = ['feature_flags_passed', 'dry_run_passed']
if release.requires_drill:
required.append('drill_passed')
if all(getattr(release, field) for field in required):
release.status = "rehearsal_complete"
# Publish event?
await publish_event("release.rehearsal_complete", {"release_id": release.id})
This is a simplified version.
We are not handling:
- The case when the release is already rejected or completed.
- The case when the event arrives and the release doesn't exist (maybe it was deleted).
- Error handling.
But it gives the idea.
We also need to implement the event consumer that routes events to handlers.
We'll assume we have a function publish_event that sends to RabbitMQ.
For the event consumer:
async def event_consumer():
connection = await aio_pika.connect_robust("amqp://guest:guest@rabbitmq/")
channel = await connection.channel()
queue = await channel.declare_queue("release_service_queue", durable=True)
async with queue.iterator() as queue_iter:
async for message in queue_iter:
async with message.process():
event = json.loads(message.body)
event_type = event.get("event_type")
payload = event.get("payload", {})
if event_type == "feature_flags.validated":
await handle_feature_flags_validated(payload)
elif event_type == "dry_run.completed":
await handle_dry_run_completed(payload)
elif event_type == "risk.updated":
await handle_risk_updated(payload)
elif event_type == "drill.completed":
await handle_drill_completed(payload)
This is a basic consumer.
We also need to handle the release.created event? Actually, the Release Service publishes release.created, so it doesn't consume it.
We are only consuming events from other services.
Now, we have a basic Release Service.
We would need to implement the other services similarly.
Given the time, we'll stop here.
This design and code skeleton should give a good starting point.
Note: This is a complex system and would require a lot of work to implement fully.
We have designed an event-driven system with multiple services and a state machine for releases.
The key points:
- Release Service is the state machine.
- Other services perform their tasks and publish events.
- Dashboard Service aggregates for the frontend.
We provided code for the Release Service's state machine.
Now, the user can build upon this.
I'll design a comprehensive Release Rehearsal Guild system that provides structured, safe environments for practicing releases with multiple layers of guardrails. This is a sophisticated system for enterprises with complex release processes.
Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ Release Rehearsal Guild │
├─────────────────┬─────────────────┬─────────────────────────┤
│ GUARDRAILS │ DRY RUNS │ DASHBOARD │
│ • Policy │ • Environment │ • Risk Visualization │
│ • Validation │ • Deployment │ • Metrics Aggregation│
│ • Enforcement │ • Test Suite │ • Historical Trends │
├─────────────────┴─────────────────┴─────────────────────────┤
│ DRILLS & SIMULATIONS │
│ • Chaos Engineering • Failure Injection • Load Testing │
└─────────────────────────────────────────────────────────────┘
1. Feature Flag Guardrails
Policy Engine
policies:
- name: "flag-expiration"
rule: "flags.created > 30 days ago must have expiration_date set"
severity: "high"
action: "block_merge"
- name: "gradual-rollout-required"
rule: "any flag targeting >10% of production users requires gradual rollout plan"
severity: "medium"
action: "require_approval"
- name: "owner-accountability"
rule: "all flags must have valid owner (team/email) with on-call rotation"
severity: "high"
action: "block_deploy"
- name: "kill-switch-ready"
rule: "flags changing core functionality must have emergency rollback procedure documented"
severity: "critical"
action: "require_signoff"
Implementation
class FlagGuardrails:
def validate_release(self, release_plan):
violations = []
for flag in release_plan.feature_flags:
# Check expiration
if flag.age_days > 30 and not flag.expiration_date:
violations.append(f"Flag {flag.name} expired without removal plan")
# Check rollout percentage
if flag.target_percentage > 10 and not flag.rollout_strategy:
violations.append(f"Flag {flag.name} needs gradual rollout plan")
# Check ownership
if not flag.owner or not self.oncall_team_exists(flag.owner):
violations.append(f"Flag {flag.name} has invalid owner")
return ValidationResult(
passed=len(violations) == 0,
violations=violations,
risk_score=self.calculate_risk(violations)
)
2. Dry Run Environment
Isolated Rehearsal Clusters
environments:
dry-run:
- name: "rehearsal-${RELEASE_ID}"
cluster_config:
nodes: 3 # 1/3 of production scale
network: isolated_vpc
data: production_snapshot_ anonymized
deployment:
strategy: blue_green
traffic: 0% # No real users
services:
- match_production_topology: true
- config_overrides:
logging: DEBUG
metrics: detailed
circuit_breakers: aggressive
Automated Dry Run Workflow
# 1. Spin up rehearsal environment
rehearsal-cli create \
--release-tag=v2.3.0-rc1 \
--scale-factor=0.3 \
--data-source=prod-snapshot-$(date +%Y%m%d)
# 2. Deploy with feature flags in "rehearsal mode"
kubectl apply -f release-manifest.yaml \
--namespace=rehearsal-abc123 \
--set featureFlags.mode=REHEARSAL
# 3. Run automated test suite
rehearsal-tests run \
--suite=smoke,integration,performance \
--thresholds=strict \
--report-format=json
# 4. Simulate user traffic (synthetic)
rehearsal-traffic generate \
--pattern=diurnal \
--volume=production-10% \
--duration=30m
# 5. Tear down
rehearsal-cli destroy --id=abc123 --preserve-logs
3. Risk Dashboard
Risk Scoring Algorithm
class RiskCalculator:
WEIGHTS = {
'flag_complexity': 0.25, # Number/touch points of flags
'code_churn': 0.20, # Lines changed, file count
'infrastructure_change': 0.20, # DB schema, config changes
'team_experience': 0.15, # First time for team?
'incident_history': 0.10, # Past issues with similar changes
'dry_run_results': 0.10 # Test pass/fail rate
}
def calculate_score(self, release_metadata):
factors = {}
# Factor 1: Feature Flag Complexity
factors['flag_complexity'] = min(
len(release_metadata.flags) * 10, # Max 50 points
50
)
# Factor 2: Code Change Volume
code_stats = self.get_code_stats(release_metadata.commit)
factors['code_churn'] = min(
(code_stats.lines_changed / 1000) * 30, # 30pts per KLOC
30
)
# Factor 3: Infrastructure Impact
factors['infrastructure_change'] = self.assess_infra_changes(
release_metadata.infra_diff
) * 20
# ... calculate other factors
weighted_sum = sum(
factors[factor] * self.WEIGHTS[factor]
for factor in factors
)
return {
'score': min(weighted_sum, 100),
'factors': factors,
'category': self.categorize_risk(weighted_sum) # low/medium/high/critical
}
Dashboard Views
// React component structure
<RiskDashboard>
<RiskGauge score={overallRisk.score} category={overallRisk.category} />
<RiskFactors>
<FactorBar
name="Feature Flags"
value={factors.flag_complexity}
max={50}
details={flagsBreakdown}
/>
<FactorBar
name="Code Changes"
value={factors.code_churn}
max={30}
details={codeStats}
/>
<!-- Other factors -->
</RiskFactors>
<RecentReleases>
<ReleaseTable
releases={pastReleases}
highlightSimilar={currentRelease}
/>
</RecentReleases>
<ActionableInsights>
<InsightCard
type="warning"
title="High flag complexity"
action="Review flag interactions"
/>
</ActionableInsights>
</RiskDashboard>
4. Drills & Chaos Engineering
Drill Types
drills:
- name: "flag-failure-cascade"
type: "feature_flag"
scenario: "Simulate flag service outage during rollout"
steps:
- pre: "Deploy to rehearsal environment with 10% rollout"
- action: "Block flag evaluation API for 30 seconds"
- observe:
- "Monitor fallback behavior"
- "Check error rates"
- "Verify no data corruption"
- post: "Restore flag service, complete rollout"
- name: "dependency-latency"
type: "infrastructure"
scenario: "Downstream service responds slowly"
steps:
- pre: "Warm cache with typical load"
- action: "Add 2s latency to payment service"
- observe:
- "Circuit breaker activation"
- "Queue buildup"
- "User experience degradation"
- name: "config-rollback"
type: "operational"
scenario: "Emergency rollback under load"
steps:
- pre: "Release at 50% with synthetic traffic"
- action: "Execute rollback procedure"
- measure:
- "Rollback completion time"
- "User impact duration"
- "Data consistency after rollback"
Drill Orchestrator
class DrillOrchestrator:
async def run_drill(self, release_id, drill_type):
"""Execute a controlled drill against rehearsal environment"""
# 1. Get rehearsal environment for release
env = await self.get_rehearsal_env(release_id)
# 2. Prepare monitoring
drill_id = f"drill-{uuid.uuid4().hex[:8]}"
monitor = DrillMonitor(drill_id, env)
await monitor.start()
try:
# 3. Execute drill based on type
if drill_type == "flag_outage":
await self.simulate_flag_outage(env)
elif drill_type == "db_failure":
await self.inject_db_latency(env)
elif drill_type == "node_loss":
await self.terminate_random_pods(env)
# 4. Wait for observation period
await asyncio.sleep(DRILL_DURATION)
# 5. Collect results
results = await monitor.collect_results()
# 6. Generate report
report = DrillReport(
drill_id=drill_id,
release_id=release_id,
type=drill_type,
passed=results.slo_met,
metrics=results.metrics,
incidents=results.incidents,
recommendations=self.generate_recommendations(results)
)
await self.store_report(report)
return report
finally:
# 7. Cleanup (restore services)
await self.restore_environment(env)
5. Integration Workflow
graph LR
A[Create Release Candidate] --> B{Guardrails Check}
B -- PASS --> C[Spin Up Dry Run]
B -- FAIL --> Z[Block Merge/Deploy]
C --> D[Run Automated Tests]
D --> E[Calculate Risk Score]
E --> F{Risk Level}
F -- LOW --> G[Auto-Approve]
F -- MEDIUM --> H[Manual Review Required]
F -- HIGH --> I[Run Drills]
I --> J{Drill Passed?}
J -- YES --> K[Approve with Conditions]
J -- NO --> L[Require Fixes]
K --> M[Schedule Production Rollout]
H --> M
L --> A
CLI Interface
# Full rehearsal workflow
$ rehearse release create \
--tag=v2.3.0-rc1 \
--branch=release/2.3 \
--flags='{"new-checkout": 10, "dark-mode": 100}'
# Check guardrails
$ rehearse guardrails check --release=v2.3.0-rc1
✅ Flag expiration: OK
⚠️ Gradual rollout: Missing plan for 'new-checkout' (10% → 100%)
❌ Owner: 'dark-mode' has no on-call rotation
# Run dry run
$ rehearse dry-run execute --release=v2.3.0-rc1 --scale=0.3
🔄 Creating rehearsal environment...
✅ Environment ready: rehearsal-abc123
🚀 Deploying release...
🧪 Running test suite...
• Smoke tests: 12/12 passed
• Integration: 45/45 passed
• Performance: P95 < 200ms ✅
📊 Risk score: 42/100 (MEDIUM)
# Run mandatory drill for high-risk
$ rehearse drill run --release=v2.3.0-rc1 --type=flag-outage
🎯 Running drill: flag-outage
⏱️ Duration: 5m
📉 Simulated outage at T+30s
🔁 Circuit breaker activated in 2.1s ✅
⚠️ 0.3% error rate during outage (threshold: <1%) ✅
✅ Drill PASSED - system resilient
# Generate report
$ rehearse report generate --release=v2.3.0-rc1
📄 Report: https://rehearsal.company.com/reports/v2.3.0-rc1
✓ All guardrails passed
✓ Dry run successful
✓ Drill passed
🎯 RISK: MEDIUM (42/100) - APPROVED WITH CONDITIONS
→ Condition: Monitor error rates for 2h post-deploy
6. Technology Stack
Backend Services
- ** Policy Engine**: Open Policy Agent (OPA) for guardrail rules
- Orchestration: Kubernetes + ArgoCD for dry-run environments
- Event Bus: Apache Kafka for state transitions
- Metrics: Prometheus + Thanos for long-term storage
- Dashboard: Grafana + custom React frontend
- Drill Execution: Chaos Mesh or Gremlin for fault injection
Data Models
-- Releases table
CREATE TABLE releases (
id UUID PRIMARY KEY,
version VARCHAR(50),
commit_sha CHAR(40),
created_at TIMESTAMP,
status ENUM('draft','rehearsing','approved','rejected','deployed'),
risk_score INTEGER,
risk_category VARCHAR(20)
);
-- Feature flags in release
CREATE TABLE release_flags (
release_id UUID REFERENCES releases(id),
flag_name VARCHAR(100),
intended_percentage INTEGER,
rollout_strategy VARCHAR(50),
owner VARCHAR(100)
);
-- Drill results
CREATE TABLE drill_results (
id UUID PRIMARY KEY,
release_id UUID,
drill_type VARCHAR(50),
passed BOOLEAN,
metrics JSONB,
incidents INT,
completed_at TIMESTAMP
);
7. Guardrail Policies as Code
# OPA policy for feature flag validation
package release_guardrails
default deny = true
# Flag must have expiration if older than 30 days
denary[msg] {
input.release.flags[_].flag
age_days := input.release.flags[_].age_days
age_days > 30
not input.release.flags[_].expiration_date
msg := sprintf("Flag '%s' is %d days old with no expiration",
[input.release.flags[_].name, age_days])
}
# Gradual rollout required for >10% production traffic
denary[msg] {
flag := input.release.flags[_]
flag.target_percentage > 10
not flag.rollout_strategy
msg := sprintf("Flag '%s' targets %d%% but has no gradual rollout plan",
[flag.name, flag.target_percentage])
}
# All flags must have valid on-call owner
denary[msg] {
flag := input.release.flags[_]
not oncall_team(flag.owner)
msg := sprintf("Flag '%s' owner '%s' has no active on-call rotation",
[flag.name, flag.owner])
}
# Production-deployable flags must have kill switch
denary[msg] {
flag := input.release.flags[_]
flag.impact = "core"
not flag.emergency_rollback_procedure
msg := sprintf("Core flag '%s' missing emergency rollback procedure",
[flag.name])
}
8. Success Metrics
Track these KPIs for continuous improvement:
| Metric | Target | Measurement |
|---|
| Rehearsal Success Rate | >95% | % of releases passing all guardrails |
| Mean Time to Detect (MTTD) | <5min | From deployment to incident detection |
| Rollback Efficiency | <2min | Time to complete emergency rollback |
| False Positive Rate | <5% | Rehearsal failures that would succeed in prod |
| Drill Participation | 100% | High-risk releases include drills |
| Risk Score Correlation | r>0.7 | Rehearsal risk vs actual production incidents |
9. Implementation Roadmap
Phase 1 (Weeks 1-4): Foundation
- Set up basic guardrails with OPA
- Create dry-run environment templates
- Build simple dashboard with risk scoring
Phase 2 (Weeks 5-8): Automation
- Integrate with CI/CD pipelines
- Automate environment provisioning
- Implement basic drill scenarios
Phase 3 (Weeks 9-12): Advanced
- Add chaos engineering integration
- Historical trend analysis
- Predictive risk modeling
- Self-healing guardrails
Phase 4 (Weeks 13+): Optimization
- AI/ML for risk prediction
- Automatic drill scheduling based on risk
- Integration with incident management
- Cross-team guild collaboration features
Key Benefits
- Shift-Left Safety: Catch issues before they reach production
- Team Confidence: Practice releases in safe environments
- Continuous Improvement: Learn from every rehearsal
- Risk Quantification: Data-driven release decisions
- Compliance: Audit trail of all rehearsals and decisions
- Reduced Toil: Automation of repetitive checks
This guild system transforms release practices from "hope it works" to "proven to work" through disciplined rehearsal, measurable guardrails, and continuous practice via drills.