The user wants a "feature lifecycle service" that handles proposals, RFCs (Request for Comments), rollout phases, and cleanup.
1. Deconstruct the Request:
- Core Concept: A system to manage the lifecycle of a software feature from idea to removal.
- Key Stages:
- Proposal: Initial idea.
- RFC: Detailed design and discussion.
- Rollout: Phased deployment ( Canary -> Beta -> GA).
- Cleanup: Deprecation and removal.
- Deliverable: Code or architectural design for this service.
2. Determine the Scope and Tech Stack:
- Language: Python (FastAPI) is standard, readable, and good for services.
- Database: PostgreSQL (SQL is good for state machines and relational data like stages/comments).
- State Machine: This is the heart of the logic. Transitions must be validated (e.g., you can't go from
Proposal to GA without passing RFC).
3. Design the Data Model (Schema):
Feature: ID, name, description, owner, current_status, timestamps.
Document: ID, feature_id, type (Proposal, RFC), content (Markdown), version.
RolloutConfig: ID, feature_id, phase (Internal, Beta, GA), percentage, config_flags.
AuditLog: To track state changes (who moved it, when, why).
4. Define the State Machine (The Lifecycle):
PROPOSED: Raw idea.
RFC_DRAFTING: Writing the technical spec.
RFC_REVIEW: Stakeholders are looking at it.
APPROVED: Ready to build.
ROLLING_OUT: Development done, releasing to users.
- Sub-states:
Internal -> Beta -> GeneralAvailability
LIVE: Fully rolled out.
DEPRECATED: End of life warning.
REMOVED: Deleted/Cleaned up.
5. Draft the API Endpoints:
POST /features: Create a proposal.
POST /features/{id}/docs: Attach an RFC.
PATCH /features/{id}/status: Advance the state.
POST /features/{id}/rollout: Update rollout phases (e.g., "increase traffic to 50%").
GET /features/{id}: View status.
6. Refine the Implementation (Self-Correction/Optimization):
- Constraint: Writing a full GUI is too much for a single prompt. I should focus on the Backend Service logic, specifically the state machine and data models.
- Refinement: Add a "Cleanup" aspect. When a feature is marked
REMOVED, a cleanup job should trigger (simulated).
- Code Structure:
models.py: Pydantic/SQLAlchemy schemas.
lifecycle.py: The state machine logic (the core business logic).
main.py: The FastAPI app.
7. Writing the Code (Mental Draft):
- Imports: FastAPI, Pydantic, Enum.
- Enums: Define
FeatureStatus.
- Pydantic Models:
FeatureCreate: Title, Description.
Feature: ID, Status, etc.
RolloutUpdate: Phase, Percentage.
- In-Memory DB: Use a dictionary for simplicity so the code is runnable without setting up Postgres.
- Business Logic (The "Service"):
- Function
transition_feature(feature_id, next_status). Needs to check if the transition is allowed.
8. Adding Specific "Flavor":
- RFC Handling: Explicitly mention markdown storage or versioning.
- Cleanup: Add a specific method
trigger_cleanup_tasks that runs when status becomes REMOVED.
9. Final Polish:
- Structure the response:
- Architecture Overview: Explain the stages.
- The Code: Python (FastAPI) implementation.
- Usage Example:
curl commands showing the flow.
- Extension Ideas: Database, Auth, CI/CD integration.
(Self-Correction during coding):
I need to ensure the transition logic is strict. You shouldn't be able to jump from PROPOSED to LIVE.
- Allowed Transitions map:
- PROPOSED -> RFC_DRAFTING
- RFC_DRAFTING -> RFC_REVIEW
- RFC_REVIEW -> APPROVED (or back to DRAFTING)
- APPROVED -> ROLLING_OUT
- ROLLING_OUT -> LIVE
- LIVE -> DEPRECATED
- DEPRECATED -> REMOVED
Let's stick to a slightly simplified flow for the demo code to keep it readable but robust enough to demonstrate the concept.
10. Output Generation: (Proceeding to generate the response based on these steps.)
Building a Feature Lifecycle Service (FLS) requires managing state transitions, document versioning (RFCs), and safety mechanisms like rollouts and cleanups.
Below is a comprehensive design and implementation using Python (FastAPI) for the backend service and a State Machine pattern to enforce the lifecycle logic.
1. Architecture Overview
The service acts as the "Source of Truth" for a feature's existence. It integrates with:
- Version Control (Git): To store RFC documents and config changes.
- Feature Flag System (LaunchDarkly/Unleash): To execute the rollout phases.
- Observability (Datadog/Prometheus): To validate rollout health.
The Lifecycle States
- PROPOSED: Idea submitted.
- RFC_DRAFTING: Writing the technical specification.
- RFC_APPROVED: Stakeholders sign off.
- ROLLOUT_A/B: Phased deployment (Canary -> Beta -> GA).
- LIVE: 100% traffic.
- CLEANUP: Removing old code paths.
- RETIRED: Feature archived.
2. Data Model
We need to track the feature metadata, its current state, and links to artifacts (RFCs, PRs).
from datetime import datetime
from enum import Enum
from pydantic import BaseModel, Field
from typing import Optional, List
class FeatureState(str, Enum):
PROPOSED = "proposed"
RFC_DRAFTING = "rfc_drafting"
RFC_APPROVED = "rfc_approved"
ROLLOUT_CANARY = "rollout_canary" # 5% Traffic
ROLLOUT_BETA = "rollout_beta" # 25% Traffic
ROLLOUT_GA = "rollout_ga" # 100% Traffic
LIVE = "live"
CLEANUP = "cleanup" # Removing Flag/Dead Code
RETIRED = "retired"
class Artifact(BaseModel):
type: str # e.g., "RFC", "PR", "MONITOR_DASHBOARD"
url: str
version: Optional[str] = None
class Feature(BaseModel):
id: str
name: str
owner: str
state: FeatureState = FeatureState.PROPOSED
artifacts: List[Artifact] = []
created_at: datetime = Field(default_factory=datetime.utcnow)
updated_at: datetime = Field(default_factory=datetime.utcnow)
3. Implementation (FastAPI Service)
This service enforces valid transitions. For example, you cannot jump from PROPOSED directly to ROLLOUT_GA.
from fastapi import FastAPI, HTTPException, BackgroundTasks
from typing import Dict
app = FastAPI(title="Feature Lifecycle Service")
# In-memory DB for demonstration
fake_db: Dict[str, Feature] = {}
# --- Business Logic: The State Machine ---
VALID_TRANSITIONS = {
FeatureState.PROPOSED: [FeatureState.RFC_DRAFTING],
FeatureState.RFC_DRAFTING: [FeatureState.RFC_APPROVED, FeatureState.PROPOSED], # Allow rejection
FeatureState.RFC_APPROVED: [FeatureState.ROLLOUT_CANARY],
FeatureState.ROLLOUT_CANARY: [FeatureState.ROLLOUT_BETA, FeatureState.RFC_APPROVED], # Allow Rollback
FeatureState.ROLLOUT_BETA: [FeatureState.ROLLOUT_GA, FeatureState.ROLLOUT_CANARY],
FeatureState.ROLLOUT_GA: [FeatureState.LIVE],
FeatureState.LIVE: [FeatureState.CLEANUP],
FeatureState.CLEANUP: [FeatureState.RETIRED],
FeatureState.RETIRED: []
}
def trigger_rollout_webhook(feature: Feature):
"""Mock function to interact with Feature Flag system (e.g., LaunchDarkly)"""
print(f">>> WEBHOOK: Updating Flag for {feature.name} to state {feature.state}")
def trigger_cleanup_job(feature: Feature):
"""Mock function to create a JIRA ticket for code removal"""
print(f">>> JIRA: Created 'Remove Feature Flag' ticket for {feature.name}")
# --- API Endpoints ---
@app.post("/features/", response_model=Feature)
def create_feature(feature: Feature):
"""Step 1: Proposal"""
if feature.id in fake_db:
raise HTTPException(status_code=400, detail="Feature ID already exists")
fake_db[feature.id] = feature
return feature
@app.patch("/features/{feature_id}/transition", response_model=Feature)
def transition_state(feature_id: str, new_state: FeatureState, background_tasks: BackgroundTasks):
"""Move feature through lifecycle"""
feature = fake_db.get(feature_id)
if not feature:
raise HTTPException(status_code=404, detail="Feature not found")
# Validate Transition
if new_state not in VALID_TRANSITIONS[feature.state]:
raise HTTPException(
status_code=400,
detail=f"Invalid transition from {feature.state} to {new_state}"
)
# Update State
feature.state = new_state
feature.updated_at = datetime.utcnow()
# Side Effects
if "rollout" in new_state:
background_tasks.add_task(trigger_rollout_webhook, feature)
elif new_state == FeatureState.CLEANUP:
background_tasks.add_task(trigger_cleanup_job, feature)
fake_db[feature_id] = feature
return feature
@app.post("/features/{feature_id}/artifacts", response_model=Feature)
def add_artifact(feature_id: str, artifact: Artifact):
"""Attach RFC links, PR links, or Dashboards"""
feature = fake_db.get(feature_id)
if not feature:
raise HTTPException(status_code=404, detail="Feature not found")
feature.artifacts.append(artifact)
feature.updated_at = datetime.utcnow()
return feature
4. Detailed Phase Breakdown
Here is how the service handles specific lifecycle stages:
Phase 1: Proposal & RFC
When a user creates a feature, it enters PROPOSED.
- Action: The user adds an artifact of type
RFC pointing to a Google Doc or Markdown file in Git.
- Transition: The user moves it to
RFC_DRAFTING. Once reviewed, an admin moves it to RFC_APPROVED.
- Gate: The service should require an artifact of type
RFC before allowing the move to RFC_APPROVED.
Phase 2: Rollout (Safety First)
The service manages the ramp-up.
- Canary (5%): The service calls the Feature Flag API to enable the flag for internal users or a small percentage of traffic.
- Observability Check: Ideally, the endpoint
/transition should query Prometheus/Datadog before accepting the state change. If Error Rate > 1%, reject the transition.
- Rollback: If metrics fail, the system transitions back to
RFC_APPROVED automatically (not implemented in simple code above but is the production standard).
Phase 3: Cleanup (The "Finish Line")
Many teams forget this step, leading to "Feature Flag Debt."
- Trigger: Once the feature is
LIVE for a set period (e.g., 30 days), the service schedules a transition to CLEANUP.
- Task: The
trigger_cleanup_job creates a ticket for engineers to remove the if/else flag logic from the codebase.
- Completion: Once the code is merged, the feature is moved to
RETIRED.
5. Example Usage Flow
1. Create Proposal:
curl -X POST "http://localhost:8000/features/" -H "Content-Type: application/json" \
-d '{"id": "feat-123", "name": "Dark Mode", "owner": "dev-team"}'
2. Add RFC Document:
curl -X POST "http://localhost:8000/features/feat-123/artifacts" \
-d '{"type": "RFC", "url": "https://github.com/org/rfcs/pull/42"}'
3. Advance States (Simulating the flow):
# Draft -> Approved
curl -X PATCH "http://localhost:8000/features/feat-123/transition?new_state=rfc_approved"
# Approved -> Canary Rollout
curl -X PATCH "http://localhost:8000/features/feat-123/transition?new_state=rollout_canary"
# (Server triggers Webhook to Flag system)
6. Production Enhancements
To make this enterprise-ready, you would add:
- Approval Mechanisms: Require specific users (e.g., Tech Leads) to digitally sign off on the transition from
RFC_DRAFTING to RFC_APPROVED.
- Guardian Checks: Integrate with CI/CD. Before transitioning to
ROLLOUT_GA, query Datadog. If latency spiked in the last hour, block the transition.
- Expiration Dates: Add a
cleanup_date field. If a feature stays in LIVE for > 30 days, automatically email the owner to initiate CLEANUP.