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 |
|---|
| INLINECODE0 | Root path of the codebase to analyze | Required |
Analysis Framework
Factor I: Codebase
Principle: One codebase tracked in revision control, many deploys.
Search Patterns:
CODEBLOCK0
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:
CODEBLOCK1
File Patterns: **/requirements*.txt, **/package.json, **/*.lock, INLINECODE8
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:
CODEBLOCK2
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 INLINECODE13 - Environment grouping (
if ENV == 'production': ...) - Secrets committed to version control
Factor IV: Backing Services
Principle: Treat backing services as attached resources.
Search Patterns:
CODEBLOCK3
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:
CODEBLOCK4
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:
CODEBLOCK5
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:
CODEBLOCK6
File Patterns: **/main.py, **/server.py, **/app.py, INLINECODE29
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:
CODEBLOCK7
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:
CODEBLOCK8
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:
CODEBLOCK9
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:
CODEBLOCK10
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:
CODEBLOCK11
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
CODEBLOCK12
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
12-Factor应用合规性分析
参考:The Twelve-Factor App
概述
12-Factor应用方法论是一套构建软件即服务应用的最佳实践,这些应用应具备以下特性:
- - 可在不同执行环境间移植
- 无需架构变更即可扩展
- 适合持续部署
- 以最小摩擦进行维护
输入参数
| 参数 | 描述 | 是否必需 |
|---|
| codebase_path | 待分析代码库的根路径 | 必需 |
分析框架
因子I:代码库
原则: 一个代码库在版本控制中追踪,多次部署。
搜索模式:
bash
检查版本控制
ls -la .git 2>/dev/null || ls -la .hg 2>/dev/null
检查多个应用共享代码库
find . -name package.json -o -name pyproject.toml -o -name setup.py | head -20
检查环境特定代码分支
grep -r if.
production\|if.development\|if.
staging --include=.py --include=
.js --include=.ts
文件模式: .git/、package.json、pyproject.toml、部署配置
合规标准:
| 级别 | 标准 |
|---|
| 强 | 单个Git仓库,所有环境使用相同代码库,无环境特定代码分支 |
| 部分 |
单个仓库但存在一些环境特定代码路径 |
|
弱 | 同一应用有多个仓库,或跨环境存在显著代码重复 |
反模式:
- - 同一应用有多个Git仓库
- 环境特定代码分支(if production: ...)
- 开发和生产使用不同源文件
- 共享代码未提取为库
因子II:依赖
原则: 显式声明并隔离依赖。
搜索模式:
bash
Python依赖文件
find . -name requirements.txt -o -name pyproject.toml -o -name setup.py -o -name Pipfile -o -name uv.lock
JavaScript/TypeScript依赖文件
find . -name package.json -o -name package-lock.json -o -name yarn.lock -o -name pnpm-lock.yaml
检查系统工具假设
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/容器隔离
find . -name Dockerfile -o -name docker-compose*.yml
文件模式: /requirements.txt、/package.json、/.lock、/Dockerfile
合规标准:
| 级别 | 标准 |
|---|
| 强 | 存在锁文件,依赖隔离(venv/Docker),无隐式系统工具 |
| 部分 |
依赖已声明但无锁文件或隔离 |
|
弱 | 依赖仅在文档中,依赖系统安装的包 |
反模式:
- - 缺少锁文件(非确定性构建)
- 假设系统工具(curl、ImageMagick、ffmpeg)可用
- 开发和生产使用不同依赖管理器
- 无虚拟环境或容器隔离
因子III:配置
原则: 将配置存储在环境中。
搜索模式:
bash
环境变量使用
grep -r os.environ\|os.getenv\|process.env\|ENV\[ --include=
.py --include=.js --include=
.ts --include=.rb
硬编码凭据(反模式)
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
环境特定配置文件(反模式)
find . -name config.dev.
-o -name config.prod. -o -name settings.development.
-o -name settings.production.
代码中的数据库URL
grep -r postgresql://\|mysql://\|mongodb://\|redis:// --include=
.py --include=.js --include=*.ts | grep -v .env\|test\|example
文件模式: /.env、/config/.py、/settings.py、环境文件
合规标准:
| 级别 | 标准 |
|---|
| 强 | 所有配置通过环境变量,无硬编码密钥,可开源而不泄露 |
| 部分 |
大部分配置已外部化但存在一些硬编码默认值 |
|
弱 | 硬编码凭据,环境特定配置文件 |
反模式:
- - 源代码中硬编码数据库URL、API密钥、密码
- 配置文件如config/production.yml vs config/development.yml
- 环境分组(if ENV == production: ...)
- 密钥提交到版本控制
因子IV:后端服务
原则: 将后端服务视为附加资源。
搜索模式:
bash
通过配置的数据库连接
grep -r DATABASE
URL\|DBHOST\|REDIS
URL\|CACHEURL --include=
.py --include=.js --include=*.ts
服务初始化
grep -r create_engine\|MongoClient\|Redis\|Celery\|boto3 --include=*.py
grep -r createPool\|createClient\|new Redis\|S3Client --include=
.js --include=.ts
硬编码服务位置(反模式)
grep -r localhost:5432\|localhost:6379\|localhost:27017\|127.0.0.1 --include=
.py --include=.js --include=*.ts | grep -v test\|spec\|example\|default
文件模式: /database/.py、/services/.py、/db.py、连接配置
合规标准:
| 级别 | 标准 |
|---|
| 强 | 所有服务通过配置中的URL/连接字符串,无需代码更改即可切换 |
| 部分 |
大部分服务可配置但存在一些硬编码默认值 |
|
弱 | 硬编码服务位置,每个环境有不同代码路径 |
反模式:
- - 生产代码中硬编码localhost用于服务
- 本地与云服务的条件逻辑(if USES3: ... else: localstorage)
- 基于环境的服务特定代码路径
- 开发和生产使用不同驱动
因子V:构建、发布、运行
原则: 严格分离构建和运行阶段。
搜索模式:
bash
构建/部署配置
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
package.json中的构建脚本
grep -A5 scripts package.json 2>/dev/null | grep -E build|start|deploy
检查运行时编译(反模式)
grep -r compile\|transpile\|webpack --include=*.py | grep -v test\|build
文件模式: /Dockerfile、/Makefile、/.github/workflows/、CI/CD配置
合规标准:
| 级别 | 标准 |
|---|
| 强 | 不可变发布,清晰的构建/发布/运行阶段,唯一发布ID |
| 部分 |
构建和运行已分离但发布不可变 |
|
弱 | 运行时代码修改,启动时资产编译 |
反模式:
- - 运行时代码修改
- 应用启动期间资产编译
- 配置烘焙到构建产物中
- 无发布版本控制
因子VI:进程
原则: 将应用作为一个或多个无状态进程执行。
搜索模式: