当前位置: 首页 > Skill >

12 Factor Apps

12 Factor Apps

12 Factor Apps

对任意代码库进行 12-Factor App 合规性分析。适用于评估应用架构、审计 SaaS 应用或审查云原生...

1.0.0 2026.11.25 352
获取Skill文件查看使用说明
作 者:许禾 许可证: 更新时间:2026.11.25
本文目录展开

12-Factor App Compliance Analysis

Reference: The Twelve-Factor App

Overview

The 12-Factor App methodology is a set of best practices for building Software-as-a-Service applications that are:

  • Portable across execution environments
  • Scalable without architectural changes
  • Suitable for continuous deployment
  • Maintainable with minimal friction

Input Parameters

Parameter Description Required
codebase_path Root path of the codebase to analyze Required

Analysis Framework

Factor I: Codebase

Principle: One codebase tracked in revision control, many deploys.

Search Patterns:

# Check for version control
ls -la .git 2>/dev/null || ls -la .hg 2>/dev/null

# Check for multiple apps sharing codebase
find . -name "package.json" -o -name "pyproject.toml" -o -name "setup.py" | head -20

# Check for environment-specific code branches
grep -r "if.*production|if.*development|if.*staging" --include="*.py" --include="*.js" --include="*.ts"

File Patterns: .git/, package.json, pyproject.toml, deployment configs

Compliance Criteria:

Level Criteria
Strong Single Git repo, same codebase for all environments, no env-specific code branches
Partial Single repo but some environment-specific code paths
Weak Multiple repos for same app or significant code duplication across environments

Anti-patterns:

  • Multiple Git repositories for the same application
  • Environment-specific code branches (if production: ...)
  • Different source files for dev vs prod
  • Shared code not extracted to libraries

Factor II: Dependencies

Principle: Explicitly declare and isolate dependencies.

Search Patterns:

# Python dependency files
find . -name "requirements.txt" -o -name "pyproject.toml" -o -name "setup.py" -o -name "Pipfile" -o -name "uv.lock"

# JavaScript/TypeScript dependency files
find . -name "package.json" -o -name "package-lock.json" -o -name "yarn.lock" -o -name "pnpm-lock.yaml"

# Check for system tool assumptions
grep -r "subprocess.*curl|subprocess.*wget|os.system.*ffmpeg|shutil.which" --include="*.py"
grep -r "exec.*curl|child_process.*curl" --include="*.js" --include="*.ts"

# Docker/container isolation
find . -name "Dockerfile" -o -name "docker-compose*.yml"

File Patterns: **/requirements*.txt, **/package.json, **/*.lock, **/Dockerfile

Compliance Criteria:

Level Criteria
Strong Lock files present, dependency isolation (venv/Docker), no implicit system tools
Partial Dependencies declared but no lock files or isolation
Weak Dependencies in documentation only, relies on system-installed packages

Anti-patterns:

  • Missing lock files (non-deterministic builds)
  • Assuming system tools (curl, ImageMagick, ffmpeg) are available
  • Different dependency managers in dev vs production
  • No virtual environment or container isolation

Factor III: Config

Principle: Store config in the environment.

Search Patterns:

# Environment variable usage
grep -r "os.environ|os.getenv|process.env|ENV[" --include="*.py" --include="*.js" --include="*.ts" --include="*.rb"

# Hardcoded credentials (anti-pattern)
grep -r "password.*=.*['"]" --include="*.py" --include="*.js" --include="*.ts" | grep -v "test|spec|example"
grep -r "api_key.*=.*['"]" --include="*.py" --include="*.js" --include="*.ts" | grep -v "test|spec|example"
grep -r "secret.*=.*['"]" --include="*.py" --include="*.js" --include="*.ts" | grep -v "test|spec|example"

# Environment-specific config files (anti-pattern)
find . -name "config.dev.*" -o -name "config.prod.*" -o -name "settings.development.*" -o -name "settings.production.*"

# Database URLs in code
grep -r "postgresql://|mysql://|mongodb://|redis://" --include="*.py" --include="*.js" --include="*.ts" | grep -v ".env|test|example"

File Patterns: **/.env*, **/config/*.py, **/settings.py, environment files

Compliance Criteria:

Level Criteria
Strong All config via environment variables, no hardcoded secrets, could open-source without leaks
Partial Most config externalized but some hardcoded defaults
Weak Hardcoded credentials, environment-specific config files

Anti-patterns:

  • Hardcoded database URLs, API keys, passwords in source
  • Config files like config/production.yml vs config/development.yml
  • Environment grouping (if ENV == 'production': ...)
  • Secrets committed to version control

Factor IV: Backing Services

Principle: Treat backing services as attached resources.

Search Patterns:

# Database connection via config
grep -r "DATABASE_URL|DB_HOST|REDIS_URL|CACHE_URL" --include="*.py" --include="*.js" --include="*.ts"

# Service initialization
grep -r "create_engine|MongoClient|Redis|Celery|boto3" --include="*.py"
grep -r "createPool|createClient|new Redis|S3Client" --include="*.js" --include="*.ts"

# Hardcoded service locations (anti-pattern)
grep -r "localhost:5432|localhost:6379|localhost:27017|127.0.0.1" --include="*.py" --include="*.js" --include="*.ts" | grep -v "test|spec|example|default"

File Patterns: **/database/*.py, **/services/*.py, **/db.py, connection configurations

Compliance Criteria:

Level Criteria
Strong All services via URL/connection string in config, swappable without code changes
Partial Most services configurable but some hardcoded defaults
Weak Hardcoded service locations, different code paths per environment

Anti-patterns:

  • Hardcoded localhost for services in production code
  • Conditional logic for local vs cloud services (if USE_S3: ... else: local_storage)
  • Service-specific code paths based on environment
  • Different drivers for dev vs prod

Factor V: Build, Release, Run

Principle: Strictly separate build and run stages.

Search Patterns:

# Build/deploy configuration
find . -name "Dockerfile" -o -name "Makefile" -o -name "build.sh" -o -name "deploy.sh"
find . -name ".github/workflows/*.yml" -o -name ".gitlab-ci.yml" -o -name "Jenkinsfile"

# Build scripts in package.json
grep -A5 '"scripts"' package.json 2>/dev/null | grep -E "build|start|deploy"

# Check for runtime compilation (anti-pattern)
grep -r "compile|transpile|webpack" --include="*.py" | grep -v "test|build"

File Patterns: **/Dockerfile, **/Makefile, **/.github/workflows/**, CI/CD configs

Compliance Criteria:

Level Criteria
Strong Immutable releases, clear build/release/run stages, unique release IDs
Partial Build and run separated but release not immutable
Weak Runtime code modifications, asset compilation at startup

Anti-patterns:

  • Runtime code modifications
  • Asset compilation during application startup
  • Configuration baked into build artifacts
  • No release versioning

Factor VI: Processes

Principle: Execute the app as one or more stateless processes.

Search Patterns:

# Session storage patterns
grep -r "session|Session" --include="*.py" --include="*.js" --include="*.ts" | head -20

# In-process state (anti-pattern)
grep -r "global.*cache|process_local|instance_cache" --include="*.py"
grep -r "global..*=|module.exports.cache" --include="*.js" --include="*.ts"

# External session stores (good pattern)
grep -r "redis.*session|memcached.*session|session.*redis" --include="*.py" --include="*.js" --include="*.ts"

# Sticky session configuration (anti-pattern)
grep -r "sticky.*session|session.*affinity" --include="*.yml" --include="*.yaml" --include="*.json"

File Patterns: **/middleware/*.py, **/session/*.py, server configurations

Compliance Criteria:

Level Criteria
Strong Stateless processes, all state in external datastores (Redis, DB)
Partial Mostly stateless but some in-process caching
Weak Sticky sessions, in-process session storage, shared memory state

Anti-patterns:

  • In-process session storage (user_sessions = {})
  • Sticky sessions or session affinity
  • File-based caching between requests
  • Global mutable state shared across requests

Factor VII: Port Binding

Principle: Export services via port binding.

Search Patterns:

# Self-contained port binding
grep -r "app.run|server.listen|serve|uvicorn" --include="*.py"
grep -r "app.listen|server.listen|createServer" --include="*.js" --include="*.ts"

# PORT environment variable
grep -r "PORT|port" --include="*.py" --include="*.js" --include="*.ts" | grep -i "environ|process.env"

# Webserver as dependency
grep -r "uvicorn|gunicorn|flask|fastapi|express|koa|hapi" package.json pyproject.toml requirements.txt 2>/dev/null

File Patterns: **/main.py, **/server.py, **/app.py, **/index.js

Compliance Criteria:

Level Criteria
Strong Self-contained app binds to PORT, webserver is a dependency
Partial Port binding but not configurable via environment
Weak Relies on external webserver container (Apache, Nginx) to provide HTTP

Anti-patterns:

  • Relying on Apache/Nginx/Tomcat to inject webserver functionality
  • Hardcoded port numbers
  • No PORT environment variable support
  • CGI scripts or server modules

Factor VIII: Concurrency

Principle: Scale out via the process model.

Search Patterns:

# Process definitions
find . -name "Procfile" -o -name "process.yml" -o -name ".foreman"

# Multiple entry points
find . -name "worker.py" -o -name "scheduler.py" -o -name "web.py"

# Background job systems
grep -r "celery|rq|sidekiq|bull|agenda" --include="*.py" --include="*.js" --include="*.ts"
grep -r "Celery|Worker|BackgroundJob" --include="*.py" --include="*.js" --include="*.ts"

File Patterns: **/Procfile, **/worker.py, **/scheduler.py, queue configurations

Compliance Criteria:

Level Criteria
Strong Explicit process types (web, worker, scheduler), horizontal scaling
Partial Multiple process types but not easily scalable
Weak Single monolithic process, no separation of concerns

Anti-patterns:

  • Single process handling all workloads
  • Hard-coded worker counts in code
  • No separation between web and background processes
  • Vertical scaling only (bigger server, not more processes)

Factor IX: Disposability

Principle: Maximize robustness with fast startup and graceful shutdown.

Search Patterns:

# Signal handlers
grep -r "signal.signal|SIGTERM|SIGINT|atexit" --include="*.py"
grep -r "process.on.*SIGTERM|process.on.*SIGINT" --include="*.js" --include="*.ts"

# Graceful shutdown
grep -r "graceful.*shutdown|shutdown_handler|cleanup" --include="*.py" --include="*.js" --include="*.ts"

# Startup time
grep -r "startup|initialize|bootstrap" --include="*.py" --include="*.js" --include="*.ts" | head -20

File Patterns: **/main.py, **/server.py, lifecycle management code

Compliance Criteria:

Level Criteria
Strong Fast startup (<10s), SIGTERM handling, graceful shutdown, jobs returnable to queue
Partial Graceful shutdown but slow startup
Weak No signal handling, jobs lost on process death, slow startup

Anti-patterns:

  • No SIGTERM/SIGINT handlers
  • Slow startup (>30 seconds)
  • Jobs lost if process crashes
  • No cleanup on shutdown

Factor X: Dev/Prod Parity

Principle: Keep development, staging, and production as similar as possible.

Search Patterns:

# Different services per environment (anti-pattern)
grep -r "if.*development.*sqlite|if.*production.*postgres" --include="*.py" --include="*.js" --include="*.ts"
grep -r "development.*SQLite|production.*PostgreSQL" --include="*.py" --include="*.js" --include="*.ts"

# Docker for parity
find . -name "docker-compose*.yml" -o -name "Dockerfile"

# Environment-specific backends
grep -r "USE_LOCAL_|LOCAL_STORAGE|MOCK_" --include="*.py" --include="*.js" --include="*.ts"

File Patterns: **/docker-compose*.yml, environment configurations

Compliance Criteria:

Level Criteria
Strong Same services everywhere (PostgreSQL in dev and prod), containerized
Partial Mostly same but some lightweight dev alternatives
Weak SQLite in dev, PostgreSQL in prod; different backing services

Anti-patterns:

  • SQLite for development, PostgreSQL for production
  • In-memory cache in dev, Redis in prod
  • Different service versions across environments
  • "It works on my machine" issues

Factor XI: Logs

Principle: Treat logs as event streams.

Search Patterns:

# Stdout logging
grep -r "print(|logging.info|logger.info|console.log" --include="*.py" --include="*.js" --include="*.ts" | head -20

# File-based logging (anti-pattern)
grep -r "FileHandler|open.*.log|writeFile.*log|fs.appendFile.*log" --include="*.py" --include="*.js" --include="*.ts"
grep -r "/var/log|/tmp/.*.log|logs/" --include="*.py" --include="*.js" --include="*.ts" | grep -v "test|example"

# Structured logging
grep -r "structlog|json_logger|pino|winston" --include="*.py" --include="*.js" --include="*.ts"

File Patterns: **/logging.py, **/logger.py, logging configurations

Compliance Criteria:

Level Criteria
Strong Unbuffered stdout only, structured logging (JSON), no file management
Partial Stdout logging but with some file handlers
Weak Application writes to log files, manages rotation

Anti-patterns:

  • Writing logs to files (FileHandler, open('/var/log/app.log'))
  • Log rotation logic in application code
  • Log archival managed by application
  • Buffered logging

Factor XII: Admin Processes

Principle: Run admin/management tasks as one-off processes.

Search Patterns:

# Management commands
find . -name "manage.py" -o -name "Rakefile" -o -name "artisan"
grep -r "@cli.command|@click.command|typer.command" --include="*.py"

# Migration scripts
find . -name "migrations" -type d
find . -name "*migration*.py" -o -name "*migrate*.py"

# Admin scripts with proper isolation
grep -r "bundle exec|source.*venv|uv run" --include="*.sh" --include="Makefile"

File Patterns: **/manage.py, **/cli.py, **/migrations/**, admin scripts

Compliance Criteria:

Level Criteria
Strong Admin tasks use same dependencies/config, proper isolation, idempotent
Partial Admin tasks exist but different setup from app
Weak Manual database manipulation, scripts without isolation

Anti-patterns:

  • Admin scripts not using app's dependency manager
  • Direct SQL manipulation outside of migrations
  • Admin scripts with hardcoded credentials
  • Non-idempotent migrations

Output Format

Executive Summary Table

| Factor | Status | Notes |
|--------|--------|-------|
| I. Codebase | **Strong/Partial/Weak** | [Key finding] |
| II. Dependencies | **Strong/Partial/Weak** | [Key finding] |
| III. Config | **Strong/Partial/Weak** | [Key finding] |
| IV. Backing Services | **Strong/Partial/Weak** | [Key finding] |
| V. Build/Release/Run | **Strong/Partial/Weak** | [Key finding] |
| VI. Processes | **Strong/Partial/Weak** | [Key finding] |
| VII. Port Binding | **Strong/Partial/Weak** | [Key finding] |
| VIII. Concurrency | **Strong/Partial/Weak** | [Key finding] |
| IX. Disposability | **Strong/Partial/Weak** | [Key finding] |
| X. Dev/Prod Parity | **Strong/Partial/Weak** | [Key finding] |
| XI. Logs | **Strong/Partial/Weak** | [Key finding] |
| XII. Admin Processes | **Strong/Partial/Weak** | [Key finding] |

**Overall**: X Strong, Y Partial, Z Weak

Per-Factor Analysis

For each factor, provide:

  1. Current Implementation

    • Evidence with file:line references
    • Code snippets showing patterns
  2. Compliance Level

    • Strong/Partial/Weak with justification
  3. Gaps

    • What's missing vs. 12-Factor ideal
  4. Recommendations

    • Actionable improvements with code examples

Analysis Workflow

  1. Initial Scan

    • Run search patterns for all factors
    • Identify key files for each factor
    • Note any existing compliance documentation
  2. Deep Dive (per factor)

    • Read identified files
    • Evaluate against compliance criteria
    • Document evidence with file paths
  3. Gap Analysis

    • Compare current vs. 12-Factor ideal
    • Identify anti-patterns present
    • Prioritize by impact
  4. Recommendations

    • Provide actionable improvements
    • Include before/after code examples
    • Reference best practices
  5. Summary

    • Compile executive summary table
    • Highlight strengths and critical gaps
    • Suggest priority order for improvements

Quick Reference: Compliance Scoring

Score Meaning Action
Strong Fully implements principle Maintain, minor optimizations
Partial Some implementation, significant gaps Planned improvements
Weak Minimal or no implementation High priority for roadmap

When to Use This Skill

  • Evaluating new SaaS applications
  • Reviewing cloud-native architecture decisions
  • Auditing production applications for scalability
  • Planning migration to cloud platforms
  • Comparing application architectures
  • Preparing for containerization/Kubernetes deployment

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,037
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,020
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,019
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,016
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,015
Skill 文件
  • SKILL.md
    • 12-Factor App Compliance Analysis
    • Overview
    • Input Parameters
    • Analysis Framework
      • Factor I: Codebase
      • Factor II: Dependencies
      • Factor III: Config
      • Factor IV: Backing Services
      • Factor V: Build, Release, Run
      • Factor VI: Processes
      • Factor VII: Port Binding
      • Factor VIII: Concurrency
      • Factor IX: Disposability
      • Factor X: Dev/Prod Parity
      • Factor XI: Logs
      • Factor XII: Admin Processes
    • Output Format
      • Executive Summary Table
      • Per-Factor Analysis
    • Analysis Workflow
    • Quick Reference: Compliance Scoring
    • When to Use This Skill
  • 项目或源文件

相关 Skill

更多
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...
音频混音工具 音频混音工具 名称:Sound Mixing Tool(标识 sound-mixing-tool) 短简介(≤60字):音乐/音效响度精确对齐 + 融合混音工作流:用 ffmpeg 两段式 loudnorm 把多组素材 LUFS 偏差压到 <0.10,再最小干预融合、导出可进引擎的独立分轨。 标签/关键词:音频混音 响度匹配 LUFS ffmpeg 游戏音频 音效设计 Wwise FMOD 分轨导出 后期处理 触发词:混音 · 响度匹配 · LUFS 对齐 · MIX 版本 · 音乐音效分轨 · 融合 · 不打架 · 不能盖住 适用场景 :游戏音频集成、影视短视频配乐、播客后期