1---2name: cloud-native3description: Cloud native application design principles based on the Twelve-Factor App methodology and CNCF patterns including codebase management, dependency isolation, config externalization, backing services, build-release-run separation, stateless processes, port binding, concurrency via process model, disposability, dev/prod parity, log streaming, and admin processes. Extends to 15-Factor with API-first design, telemetry, and security. Covers AWS/GCP/Azure Well-Architected frameworks. Use when designing cloud native applications, reviewing application architecture for cloud readiness, or applying twelve-factor principles to existing applications.4license: MIT5---67# Cloud Native / Twelve-Factor App Rules89## 1. Twelve-Factor App Principles1011The Twelve-Factor App methodology defines a set of principles for building modern, portable, and scalable applications. Each factor addresses a specific aspect of application design and deployment.1213### Factor Overview1415| # | Factor | Core Rule |16| -- | ----------------- | -------------------------------------------------- |17| 1 | Codebase | One codebase tracked in VCS, many deploys |18| 2 | Dependencies | Explicitly declare and isolate dependencies |19| 3 | Config | Store config in the environment |20| 4 | Backing Services | Treat backing services as attached resources |21| 5 | Build/Release/Run | Strictly separate build and run stages |22| 6 | Processes | Execute the app as one or more stateless processes |23| 7 | Port Binding | Export services via port binding |24| 8 | Concurrency | Scale out via the process model |25| 9 | Disposability | Maximize robustness with fast startup and shutdown |26| 10 | Dev/Prod Parity | Keep development, staging, and production similar |27| 11 | Logs | Treat logs as event streams |28| 12 | Admin Processes | Run admin/management tasks as one-off processes |2930> For detailed explanations, modern interpretations, and implementation examples of each factor, see `references/twelve-factor-details.md`.3132---3334### Factor 1: Codebase3536- One application = one codebase in version control37- Multiple deploys (staging, production, developer environments) come from the same codebase38- Shared code must be extracted into libraries included via dependency management39- Never maintain separate codebases for the same application across environments4041### Factor 2: Dependencies4243- Explicitly declare all dependencies using a manifest (e.g., `package.json`, `build.gradle`, `requirements.txt`, `go.mod`)44- Use dependency isolation tools (e.g., virtual environments, containers) to prevent implicit system-wide dependencies45- Never rely on system-level packages being pre-installed46- Pin dependency versions for reproducible builds4748### Factor 3: Config4950- Store all environment-specific configuration in environment variables51- Configuration includes: database URLs, credentials, per-deploy values, feature flags52- Configuration does NOT include: internal application wiring, routing, or compile-time constants53- Never commit credentials or environment-specific config to the codebase54- The codebase should be open-sourceable at any time without exposing secrets5556### Factor 4: Backing Services5758- Treat all backing services (databases, message queues, caches, SMTP, object storage) as attached resources59- Access via URL or locator stored in config -- no code change needed to swap a service60- A deploy should be able to switch from a local database to a managed cloud database by changing config alone61- No distinction between local and third-party services in the application code6263### Factor 5: Build, Release, Run6465- **Build**: Convert code into an executable artifact (compile, bundle assets, resolve dependencies)66- **Release**: Combine the build artifact with environment config67- **Run**: Launch the release in the execution environment68- Every release must have a unique identifier (timestamp, version number, commit hash)69- Builds must not depend on runtime config; runtime must not depend on build tools70- Never modify code at runtime -- changes go through the build pipeline7172### Factor 6: Processes7374- Application processes are stateless and share-nothing75- Any data that must persist is stored in a backing service (database, object storage)76- Never assume in-memory state (sessions, caches) survives across requests or process restarts77- Sticky sessions are a violation -- use a distributed session store if session state is needed7879### Factor 7: Port Binding8081- The application is self-contained and exports services by binding to a port82- The application does not rely on runtime injection of a web server (e.g., deploying a WAR into Tomcat)83- One application can become a backing service for another via its URL8485### Factor 8: Concurrency8687- Scale by running multiple processes, not by growing a single process (scale out, not up)88- Assign different process types for different workloads (web, worker, scheduler)89- Processes should never daemonize or manage their own PID files -- delegate to the platform9091### Factor 9: Disposability9293- Processes start quickly (seconds, not minutes)94- Processes shut down gracefully on SIGTERM95- Workers use reentrant, idempotent job designs so interrupted work can be safely retried96- Handle crash recovery without data corruption9798### Factor 10: Dev/Prod Parity99100- Minimize gaps between development and production:101102| Gap | Traditional App | Twelve-Factor App |103| --------- | ------------------------ | --------------------------------- |104| Time | Weeks between deploys | Hours between deploys |105| Personnel | Devs write, ops deploy | Same team writes and deploys |106| Tools | Different stacks per env | Same backing services in all envs |107108- Use the same type and version of backing services in all environments109- Avoid "lightweight" substitutes in development (e.g., SQLite in dev, PostgreSQL in prod)110111### Factor 11: Logs112113- Treat logs as unbuffered event streams written to stdout114- Never manage log files, rotation, or routing within the application115- The execution environment captures, aggregates, routes, and archives log streams116- Use structured logging (JSON) for machine-parseable output117118### Factor 12: Admin Processes119120- Run one-off tasks (database migrations, console REPL, data fixes) as processes in the same environment121- Admin code ships with the application code to prevent version drift122- Admin processes use the same config and dependency isolation as the application123- Prefer idempotent admin tasks that can be safely re-run124125---126127## 2. Beyond Twelve-Factor: 15-Factor Principles128129Modern cloud native applications extend the original twelve factors with three additional principles.130131### Factor 13: API First132133- Design APIs before writing implementation code134- APIs are the primary interface contract between services135- Use machine-readable API specifications (OpenAPI, AsyncAPI, gRPC proto files)136- API versioning strategy must be decided and documented upfront137- Internal and external APIs follow the same contract-first process138139### Factor 14: Telemetry140141- Every service must emit three pillars of observability:142143| Pillar | Purpose | Examples |144| -------------- | -------------------------------- | --------------------------------- |145| Metrics | Quantitative health indicators | Request rate, error rate, latency |146| Logs | Discrete event records | Structured JSON to stdout |147| Traces | Distributed request flow | OpenTelemetry spans |148149- Health check endpoints are mandatory (`/health`, `/ready`)150- Application performance monitoring (APM) must be built in, not bolted on151- Correlation IDs must propagate across all service boundaries152153### Factor 15: Security154155- Authentication and authorization are infrastructure concerns, not afterthoughts156- Apply zero-trust networking: verify every request regardless of source157- Encrypt data in transit (TLS) and at rest158- Manage secrets via secret management services, never in environment variables as plaintext files159- Dependencies must be regularly scanned for known vulnerabilities160- Apply principle of least privilege to all service accounts and IAM roles161162---163164## 3. Cloud Native Design Principles165166### CNCF Cloud Native Characteristics167168| Characteristic | Description |169| ---------------------- | -------------------------------------------------------------- |170| Container-Packaged | Applications are packaged as lightweight containers |171| Dynamically Managed | Orchestrated by a central scheduler (e.g., Kubernetes) |172| Microservices-Oriented | Composed of loosely coupled, independently deployable services |173| Automation-Centric | CI/CD, infrastructure as code, auto-scaling |174| Observable | Built-in metrics, logging, tracing |175| Resilient | Designed to handle failure gracefully |176177### Cloud Native Design Rules178179- Design for failure: assume any component can fail at any time180- Prefer horizontal scaling over vertical scaling181- Use service meshes for cross-cutting concerns (mTLS, retries, circuit breaking)182- Externalize state to managed services; compute layer must be stateless183- Automate everything: deployment, scaling, recovery, security patching184- Use declarative configuration over imperative scripts185- Treat infrastructure as cattle, not pets -- replace, never repair186187### Resilience Patterns188189| Pattern | Purpose | When to Apply |190| ---------------- | ------------------------------------------------------ | -------------------------------------- |191| Circuit Breaker | Prevent cascading failures | Remote service calls |192| Retry + Backoff | Handle transient failures | Network calls, external APIs |193| Bulkhead | Isolate failures to a subset of resources | Thread pools, connection pools |194| Timeout | Prevent indefinite blocking | All remote calls |195| Fallback | Provide degraded functionality when a service is down | Non-critical feature dependencies |196| Health Check | Detect unhealthy instances for replacement | Every service, every container |197198### Container Design Rules199200- One process per container (single concern)201- Build immutable images -- never patch running containers202- Use multi-stage builds to minimize image size and attack surface203- Include health check instructions in the container definition204- Run as non-root user205- Do not store data inside the container filesystem206207---208209## 4. Well-Architected Framework Alignment210211Cloud providers define Well-Architected frameworks that complement twelve-factor principles. The core pillars are consistent across providers.212213| Pillar | AWS | GCP | Azure |214| ---------------------- | ------------------------ | -------------------------- | ------------------------ |215| Operational Excellence | Automate operations, IaC | Automate operations | DevOps practices |216| Security | Defense in depth, IAM | BeyondCorp, IAM | Zero Trust, RBAC |217| Reliability | Auto-recovery, multi-AZ | Regional redundancy | Availability Zones, DR |218| Performance Efficiency | Right-sizing, caching | Right-sizing, CDN | Autoscale, CDN |219| Cost Optimization | Right-sizing, reserved | Committed use, preemptible | Reserved, spot instances |220| Sustainability | Resource efficiency | Carbon-aware scheduling | Carbon optimization |221222> For detailed comparisons and pillar-specific guidance, see `references/well-architected-frameworks.md`.223224---225226## 5. Anti-Patterns227228### Configuration Anti-Patterns229230- **Hardcoded config**: Database URLs, API keys, or feature flags embedded in source code231- **Config files per environment**: Maintaining `config.prod.json`, `config.dev.json` in the codebase instead of using environment variables232- **Secrets in environment variables as files committed to VCS**: `.env` files checked into version control233234### Statefulness Anti-Patterns235236- **Local disk state**: Writing user uploads, session data, or temp files to local disk and expecting persistence237- **In-memory session state**: Storing sessions in process memory without a distributed store238- **Sticky sessions**: Routing users to specific instances, preventing horizontal scaling239240### Deployment Anti-Patterns241242- **Snowflake servers**: Manually configured servers that cannot be reproduced243- **Mutable deployments**: Patching running instances instead of deploying new releases244- **Missing build/release separation**: Building artifacts on production servers245- **No rollback capability**: Releases that cannot be reverted to a previous version246247### Observability Anti-Patterns248249- **Log files on disk**: Writing logs to local files instead of stdout250- **No structured logging**: Freeform log messages that cannot be parsed or queried251- **Missing health checks**: Services without liveness or readiness probes252- **No distributed tracing**: Inability to follow a request across service boundaries253254### Dependency Anti-Patterns255256- **Implicit dependencies**: Relying on system packages or globally installed tools257- **Unpinned versions**: Using `latest` tags or version ranges that can break builds258- **Vendoring without lockfiles**: Copying dependencies without tracking exact versions259260---261262## 6. Implementation Checklist263264Use this checklist when reviewing an application for cloud native readiness.265266### Essential (Must Have)267268- [ ] Single codebase in version control with CI/CD pipeline269- [ ] All dependencies declared in a manifest with pinned versions270- [ ] Configuration stored in environment variables or external config service271- [ ] Backing services accessed via config-driven connection strings272- [ ] Stateless processes with external state storage273- [ ] Structured logging to stdout274- [ ] Health check endpoints (`/health`, `/ready`)275- [ ] Graceful shutdown on SIGTERM276- [ ] Container image with non-root user277- [ ] Secrets managed via secret manager (not in code or config files)278279### Recommended (Should Have)280281- [ ] API-first design with machine-readable specification282- [ ] Distributed tracing with correlation ID propagation283- [ ] Circuit breakers on all external service calls284- [ ] Dev/prod parity for backing services285- [ ] Immutable releases with unique identifiers286- [ ] Horizontal scaling via process model287- [ ] Automated rollback capability288289---290291## 7. Related Skills292293| Related Skill | When to Reference |294| ------------------------ | -------------------------------------------------------------------- |295| `microservices` skill | Service decomposition, communication patterns, saga, CQRS |296| `clean-architecture` | Layered architecture, ports and adapters, dependency inversion |297| `dockerfile` skill | Container image best practices, multi-stage builds |298| `k8s-workflow` skill | Kubernetes deployment, health checks, resource management |299| `helm-workflow` skill | Helm chart design for cloud native applications |300| `terraform-workflow` | Infrastructure as code for cloud resource provisioning |301| `gitops-argocd` skill | GitOps-based continuous deployment |302| `observability` skill | Metrics, alerting, dashboards, SLI/SLO |303| `logging` skill | Structured logging, log aggregation, log levels |304| `secrets-management` | Secret storage, rotation, access control |305| `security` skill | OWASP Top 10, secure coding, vulnerability scanning |306| `api-design` skill | API-first design, versioning, contract testing |307| `system-design` | CAP theorem, consistency patterns, distributed consensus |308| `ci-cd` skill | Build/release/run pipeline design and automation |309310---311312## Additional Resources313314- Adam Wiggins, "The Twelve-Factor App" (12factor.net, 2011)315- Kevin Hoffman, "Beyond the Twelve-Factor App" (O'Reilly, 2016)316- CNCF, "Cloud Native Definition v1.0" (github.com/cncf/toc)317- AWS Well-Architected Framework documentation318- Google Cloud Architecture Framework documentation319- Microsoft Azure Well-Architected Framework documentation320- Cornelia Davis, "Cloud Native Patterns" (Manning, 2019)321- Bilgin Ibryam & Roland Huss, "Kubernetes Patterns" (O'Reilly, 2019)