Skills DirectorySkills Directory
SkillsLearnSecurityCategoriesDocsBlogPro
Sign InSubmit Skill
Skills Directory

Security-tested agent skills for Claude, coding agents, and AI workflows.

Directory

  • Browse Skills
  • All Skills A–Z
  • Claude Skills
  • Claude Code Skills
  • Agent Skills
  • Categories
  • Authors
  • Submit a Skill

Learn

  • Learn Hub
  • Install Claude Skills
  • Write SKILL.md
  • Skills vs MCP
  • Directories Compared

Security

  • Security
  • Methodology
  • Secure Claude Skills
  • Security Badges
  • Chrome Extension
  • Skill Manager

Company

  • About
  • Community
  • Blog
  • API Docs
  • Advertise

2026 Skills Directory. All rights reserved.

ProTermsPrivacyRefunds
Back to skills

Feature Flag Patterns

ASecurity

Gradual rollout strategies, kill switches, A/B testing integration, flag lifecycle management, and technical debt prevention.

530 stars
0 votes
0 copies
1 views
Added 5/29/2026
ai-agentstypescriptgonodenodejstesting

Works with

cli

Security Analysis

A100/100

Scanned 5/29/2026

$npx -y skills add vibeeval/vibecosystem --skill feature-flag-patterns --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Feature Flag Patterns?

Add the live security badge to your README — it updates automatically with every re-scan.

Security grade badge for Feature Flag Patterns
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/vibeeval-feature-flag-patterns/badge)](https://www.skillsdirectory.com/skills/vibeeval-feature-flag-patterns)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
Files
skill.md
---
name: feature-flag-patterns
description: Gradual rollout strategies, kill switches, A/B testing integration, flag lifecycle management, and technical debt prevention.
---

# Feature Flag Patterns

Feature flag strategies for safe deployments, experimentation, and operational control.

## Flag Types and Structure

```typescript
interface FeatureFlag {
  key: string
  type: 'boolean' | 'percentage' | 'variant' | 'segment'
  enabled: boolean
  description: string
  owner: string              // Team/person responsible
  createdAt: Date
  expiresAt?: Date           // Auto-cleanup reminder
  tags: string[]             // 'release', 'experiment', 'ops', 'permission'
}

// Flag categories by lifecycle
enum FlagCategory {
  RELEASE = 'release',       // Temporary: ship behind flag, remove after rollout
  EXPERIMENT = 'experiment', // Temporary: A/B test, remove after analysis
  OPS = 'ops',               // Long-lived: kill switches, circuit breakers
  PERMISSION = 'permission', // Long-lived: premium features, entitlements
}

// Flag configuration
const FLAGS: Record<string, FeatureFlag> = {
  'new-checkout-flow': {
    key: 'new-checkout-flow',
    type: 'percentage',
    enabled: true,
    description: 'Redesigned checkout with fewer steps',
    owner: 'checkout-team',
    createdAt: new Date('2025-01-15'),
    expiresAt: new Date('2025-04-15'),   // 3 month max
    tags: ['release'],
  },
  'emergency-read-only': {
    key: 'emergency-read-only',
    type: 'boolean',
    enabled: false,
    description: 'Kill switch: disable all write operations',
    owner: 'platform-team',
    createdAt: new Date('2024-06-01'),
    tags: ['ops'],
  },
}
```

## Gradual Rollout

```typescript
class FeatureFlagService {
  constructor(private store: FlagStore) {}

  // Percentage-based rollout using consistent hashing
  isEnabled(flagKey: string, userId: string): boolean {
    const flag = this.store.getFlag(flagKey)
    if (!flag || !flag.enabled) return false

    switch (flag.type) {
      case 'boolean':
        return flag.enabled

      case 'percentage': {
        // Consistent: same user always gets same result for same flag
        const hash = this.consistentHash(flagKey, userId)
        return hash < (flag.percentage ?? 0)
      }

      case 'segment':
        return this.isInSegment(userId, flag.segments ?? [])

      case 'variant':
        return true  // Use getVariant() instead
    }
  }

  // Deterministic hash: user always gets same bucket for same flag
  private consistentHash(flagKey: string, userId: string): number {
    const input = `${flagKey}:${userId}`
    let hash = 0
    for (let i = 0; i < input.length; i++) {
      const char = input.charCodeAt(i)
      hash = ((hash << 5) - hash) + char
      hash = hash & hash  // Convert to 32-bit integer
    }
    return Math.abs(hash) % 100  // 0-99
  }

  // Multi-variant for A/B/C testing
  getVariant(flagKey: string, userId: string): string {
    const flag = this.store.getFlag(flagKey)
    if (!flag?.enabled || !flag.variants) return 'control'

    const hash = this.consistentHash(flagKey, userId)
    let cumulative = 0
    for (const variant of flag.variants) {
      cumulative += variant.weight
      if (hash < cumulative) return variant.name
    }
    return 'control'
  }

  // Segment-based targeting
  private isInSegment(userId: string, segments: Segment[]): boolean {
    const user = this.store.getUser(userId)
    return segments.some(segment => {
      switch (segment.type) {
        case 'user_list': return segment.userIds.includes(userId)
        case 'attribute': return user?.[segment.attribute] === segment.value
        case 'percentage': return this.consistentHash(segment.id, userId) < segment.value
      }
    })
  }
}
```

## Kill Switch Pattern

```typescript
// Operational flags: immediately disable features under load
class KillSwitch {
  private cache = new Map<string, { value: boolean; expiry: number }>()
  private pollInterval: NodeJS.Timeout

  constructor(private store: FlagStore, pollMs: number = 5000) {
    // Poll every 5s for kill switch changes (fast response)
    this.pollInterval = setInterval(() => this.refresh(), pollMs)
  }

  isKilled(switchKey: string): boolean {
    const cached = this.cache.get(switchKey)
    if (cached && cached.expiry > Date.now()) {
      return cached.value
    }
    // Fallback: if cache miss, assume NOT killed (fail open)
    return false
  }

  private async refresh(): Promise<void> {
    try {
      const switches = await this.store.getKillSwitches()
      for (const [key, value] of Object.entries(switches)) {
        this.cache.set(key, { value, expiry: Date.now() + 10_000 })
      }
    } catch {
      // On error, extend existing cache TTL (don't flip switches on failure)
    }
  }

  destroy(): void {
    clearInterval(this.pollInterval)
  }
}

// Usage in request handler
async function handleCheckout(req: Request, res: Response) {
  if (killSwitch.isKilled('checkout-disabled')) {
    return res.status(503).json({
      error: 'Checkout temporarily unavailable',
      retryAfter: 300,
    })
  }
  // ... normal checkout logic
}
```

## A/B Testing Integration

```typescript
// Track experiment exposure and outcomes
interface ExperimentEvent {
  experimentKey: string
  variant: string
  userId: string
  timestamp: Date
  eventType: 'exposure' | 'conversion'
  metadata?: Record<string, unknown>
}

class ExperimentTracker {
  constructor(private analytics: AnalyticsClient) {}

  trackExposure(flagKey: string, variant: string, userId: string): void {
    this.analytics.track({
      experimentKey: flagKey,
      variant,
      userId,
      timestamp: new Date(),
      eventType: 'exposure',
    })
  }

  trackConversion(flagKey: string, userId: string, value?: number): void {
    this.analytics.track({
      experimentKey: flagKey,
      variant: featureFlags.getVariant(flagKey, userId),
      userId,
      timestamp: new Date(),
      eventType: 'conversion',
      metadata: { value },
    })
  }
}

// Usage: checkout experiment
function CheckoutPage({ user }: { user: User }) {
  const variant = featureFlags.getVariant('checkout-redesign', user.id)
  experimentTracker.trackExposure('checkout-redesign', variant, user.id)

  if (variant === 'new') {
    return <NewCheckout onComplete={() => {
      experimentTracker.trackConversion('checkout-redesign', user.id)
    }} />
  }
  return <OldCheckout onComplete={() => {
    experimentTracker.trackConversion('checkout-redesign', user.id)
  }} />
}
```

## Flag Lifecycle and Cleanup

```typescript
// Prevent flag debt: enforce expiration dates
async function auditFlags(): Promise<FlagAuditReport> {
  const flags = await flagStore.getAllFlags()
  const now = new Date()

  const report: FlagAuditReport = {
    total: flags.length,
    expired: [],
    noOwner: [],
    stale: [],
    permanent: [],
  }

  for (const flag of flags) {
    // Expired flags: should have been removed
    if (flag.expiresAt && flag.expiresAt < now) {
      report.expired.push(flag.key)
    }

    // No owner: nobody responsible for cleanup
    if (!flag.owner) {
      report.noOwner.push(flag.key)
    }

    // Stale: 100% rollout for > 2 weeks (just remove the flag)
    if (flag.type === 'percentage' && flag.percentage === 100) {
      const twoWeeksAgo = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000)
      if (flag.lastModified && flag.lastModified < twoWeeksAgo) {
        report.stale.push(flag.key)
      }
    }

    // Permanent flags without ops/permission tag
    if (!flag.expiresAt && !flag.tags.includes('ops') && !flag.tags.includes('permission')) {
      report.permanent.push(flag.key)
    }
  }

  return report
}

// Run weekly: flag cleanup report
// Slack alert for expired/stale flags
```

## Checklist

- [ ] Every release flag has an expiration date (max 3 months)
- [ ] Every flag has an owner (team or person)
- [ ] Consistent hashing for percentage rollout (same user, same result)
- [ ] Kill switches poll every 5-10 seconds (fast disable)
- [ ] A/B test exposure tracked before showing variant
- [ ] Flag audit runs weekly (detect expired, stale, ownerless flags)
- [ ] Remove flag code after full rollout (not just set to 100%)
- [ ] Default to safe value when flag service is unavailable (fail open/closed per flag)

## Anti-Patterns

- Flags without expiration dates: accumulate as permanent technical debt
- Nested flag checks: `if flagA && flagB && !flagC` becomes unmaintainable
- Flag evaluation in hot loops: cache the result per request
- Not tracking experiment exposure: biased results, no statistical power
- Removing flag from config but leaving dead code branches
- Using flags for authorization (use proper RBAC/permissions instead)

Attribution

vibeevalvibeeval
View sourceSee grades on GitHubMore from vibeeval →
SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

Comments (0)

No comments yet. Be the first to comment!

SSkills DirectorySkills Directory

Ship a skill? Prove it's safe.

Free 120-pattern security scan, letter grade, and an embeddable README badge.

Submit a skill

Related Skills

Caveman

Terse caveman voice: answer first, fluff gone, every technical fact kept. Use for /caveman, "caveman mode", "talk like caveman", "be brief", "less tokens". Stays on until "stop caveman" or "normal mode".

1100021 votes

Hyperplan

Adversarial multi-agent planning skill. Self-orchestrates 5 hostile category members (unspecified-low, unspecified-high, deep, ultrabrain, artistry) via team-mode for ruthless cross-critique debate, distills only the defensible insights, then MANDATORILY hands the distilled insight bundle to the `plan` agent for executable plan formalization. Use when planning needs maximum rigor and surfacing of weak assumptions, blind spots, and over-engineering. Triggers: 'hyperplan', 'hpp', '/hyperplan', ...

698621 votes

Writing Skills

Create and manage Claude Code skills in HASH repository following Anthropic best practices. Use when creating new skills, modifying skill-rules.json, understanding trigger patterns, working with hooks, debugging skill activation, or implementing progressive disclosure. Covers skill structure, YAML frontmatter, trigger types (keywords, intent patterns), UserPromptSubmit hook, and the 500-line rule. Includes validation and debugging with SKILL_DEBUG. Examples include rust-error-stack, cargo-dep...

3931 votes

Mcp Code Execution

Routes multi-tool workflows through MCP servers for large datasets and pipelines. Use when Bash tool overhead is limiting throughput on data-heavy tasks.

3421 votes

catchup

Recovers the conversation and failed tool calls of a previous Codex, Amp, Claude Code, Antigravity, Cline, Copilot CLI, Cursor, DeepSeek Harness, Grok Build, Kimi, OpenCode, Pi Agent, or ZCode session. Use when the user says "catch up", "what did the last session do", "get me up to speed", "I switched agents", asks to recover/summarize a previous session before continuing, or asks to diagnose or report a catchup failure. Do NOT use for the current conversation, git history, or any non-agent log.

741 votes
View all in ai-agents →