--- name: twelve-factor description: Twelve-factor app methodology for cloud-native SaaS — codebase, config, backing services, stateless processes, port binding, disposability. Use when architecting new cloud applications, microservices, or container deployments. license: MIT --- ## What I do Guide twelve-factor app design. Use when architecting cloud-native applications. ## The Twelve Factors - I Codebase: One codebase, many deploys - II Dependencies: Explicitly declare and isolate - III Config: Store config in environment vars - IV Backing Services: Treat external services as resources - V Build/Release: Strictly separate stages - VI Processes: Stateless, share-nothing - VII Port Binding: Export services via port - VIII Concurrency: Scale via process model - IX Disposability: Fast startup, graceful shutdown - X Dev/Prod: Keep environments similar - XI Logs: Treat logs as event streams - XII Admin: Run admin as one-off processes --- ## I. Codebase One codebase tracked in version control, many deploys. - Single Git repository - Same codebase → dev, staging, production - Each deploy runs specific version --- ## II. Dependencies Explicitly declare and isolate. Never rely on implicit system packages. **Always use dependency manifest**: ```toml # Rust: Cargo.toml [dependencies] serde = "1.0" # Node: package.json { "dependencies": { "express": "^4.18" } } ``` **Never**: ```python import requests # Hopes it's installed globally ``` --- ## III. Config Store config in environment variables. Separate config from code. ```rust let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); let log_level = env::var("LOG_LEVEL").unwrap_or("info"); ``` **What goes in env vars**: Database URLs, API keys, feature flags, service endpoints. **Not in env vars**: Application logic, static config. --- ## IV. Backing Services Treat external services as attached resources—accessed via URL in config. ```bash # Swap services without code changes DATABASE_URL=postgres://localhost:5432/dev # dev DATABASE_URL=postgres://prod:5432/prod # prod ``` Resources: Database, Cache, Queue, Email, Storage, External APIs. --- ## V. Build, Release, Run Strictly separate stages: ``` BUILD (code → artifact) → RELEASE (artifact + config) → RUN (execute) ``` - CI/CD pipeline handles this - Releases are immutable - Rollback by deploying previous release --- ## VI. Processes Stateless, share-nothing. Any persistent state in backing service. ```rust // Bad: State in memory static mut CACHE: Option> = None; // Good: Stateless, state in Redis fn get_data(key: &str) -> Option> { redis_client.get(key).ok() } ``` - No sticky sessions - Filesystem only for temporary cache --- ## VII. Port Binding Self-contained app exports HTTP by binding to port. ```rust let port = env::var("PORT").unwrap_or("8080").parse()?; HttpServer::new(...).bind(("0.0.0.0", port))? ``` - Port from environment - Self-contained - Service accessible via HTTP --- ## VIII. Concurrency Scale via Unix process model. Different workloads = different process types. ```yaml services: web: command: ./bin/server replicas: 3 worker: command: ./bin/worker replicas: 5 ``` Scale by adding processes, not bigger processes. --- ## IX. Disposability Fast startup, graceful shutdown. **Fast startup**: Minimize startup time, lazy initialization. **Graceful shutdown** (SIGTERM): 1. Stop accepting new requests 2. Finish current requests 3. Close backing service connections 4. Exit **Crash-only**: State is in backing services, sudden death is safe. --- ## X. Dev/Prod Parity Keep development, staging, production similar. - Gap Time: Solution → Deploy hours after coding - Gap People: Solution → Developers deploy their code - Gap Tools: Solution → Same tools everywhere Use Docker/containers locally same as production. --- ## XI. Logs Treat logs as event streams. Write to stdout. ```rust println!(r#"{"timestamp":"{}","level":"INFO","msg":"Request"}"#, now()); ``` - Write to stdout - Environment handles routing (Docker, Kubernetes) - Include correlation IDs --- ## XII. Admin Processes Run admin tasks as one-off processes, same environment as regular. ```bash docker run myapp:v1.2.3 ./bin/migrate kubectl exec deployment/myapp -- ./bin/migrate ``` Examples: Migrations, REPL inspection, data cleanup. --- ## Quick Checklist - [ ] Single codebase - [ ] Dependencies explicit - [ ] Config in env vars - [ ] External services as resources - [ ] Build/Release/Run separated - [ ] Stateless processes - [ ] Port from environment - [ ] Horizontal scaling - [ ] Fast startup/shutdown - [ ] Dev/Prod parity - [ ] Logs to stdout - [ ] Admin same environment --- Use this skill when building cloud-native applications.