Systematically refactor a monolithic or legacy application to follow the 12-factor app methodology for cloud-native deployment with containerization, config externalization, and stateless design.
## ROLE You are a cloud-native application modernization architect who has led dozens of legacy-to-cloud migration projects. You have deep expertise in the 12-factor app methodology, containerization strategies, microservices decomposition, and incremental refactoring techniques that minimize business disruption. You understand the real-world trade-offs of refactoring — when to go cloud-native, when to lift-and-shift, and when to rewrite — and you always prioritize delivering business value over architectural purity. ## OBJECTIVE Create a systematic refactoring plan to transform [APPLICATION: monolithic web app / legacy enterprise application / tightly-coupled microservices / desktop-to-cloud migration / custom description] built with [TECH STACK: Java Spring Boot / .NET Framework / PHP Laravel / Python Django / Node.js Express / Ruby on Rails / custom] into a cloud-native application following the 12-factor methodology. The application currently has [PAIN POINTS: slow deployments / scaling issues / environment drift / configuration hardcoded / session state problems / database coupling / log management chaos / long startup times]. Target deployment platform is [PLATFORM: Kubernetes / ECS / Cloud Run / Azure Container Apps / Heroku / custom]. ## TASK: 12-FACTOR REFACTORING PLAN ### Factor I — Codebase: One Codebase, Many Deploys Audit the current source control situation for [APPLICATION]. Address these common anti-patterns: **Anti-Pattern:** Multiple copies of the codebase deployed with environment-specific modifications (config files committed with production secrets, environment-specific code branches). **Refactoring:** Establish a single repository (or well-defined monorepo structure for [TEAM SIZE: small / medium / large]) where every environment (development, staging, production) deploys the exact same build artifact. Remove all environment-specific branches. Implement [BRANCHING STRATEGY: trunk-based development / GitHub Flow / GitFlow simplified] with feature flags replacing long-lived branches. Set up [CI TOOL: GitHub Actions / GitLab CI / Jenkins / CircleCI] pipeline that produces a single immutable container image tagged with [STRATEGY: git SHA / SemVer / both] and promotes that same image through environments. ### Factor II — Dependencies: Explicitly Declare and Isolate Audit all dependencies for [TECH STACK]: **Dependency Declaration:** Ensure every dependency is explicitly declared in [MANIFEST: package.json / pom.xml / requirements.txt / Gemfile / go.mod / .csproj]. Eliminate implicit system-level dependencies: no relying on system-installed tools (ImageMagick, wkhtmltopdf, ffmpeg) without declaring them in the Dockerfile or dependency manifest. Pin all dependency versions (no floating ranges like ^1.0.0 in production) and use [LOCK FILE: package-lock.json / poetry.lock / Pipfile.lock / go.sum] committed to the repository. **Dependency Isolation:** Containerize the application with a multi-stage Dockerfile that builds in a full SDK image and runs in a minimal runtime image ([BASE: alpine / distroless / slim / custom]). Document every system dependency in the Dockerfile. Provide the complete multi-stage Dockerfile for [TECH STACK] with layer caching optimization, non-root user configuration, and health check instruction. ### Factor III — Config: Store Config in the Environment This is typically the highest-impact refactoring. Audit all configuration in [APPLICATION] and categorize: **Configuration Extraction:** Identify every hardcoded value that changes between environments: database connection strings, API keys and secrets, feature flags, service URLs, cache TTLs, log levels, and application-specific settings. For [TECH STACK], implement config loading from environment variables using [LIBRARY: dotenv / Spring Cloud Config / Viper / python-decouple / custom] with this precedence: environment variable > config file > default value. **Secrets Management:** Migrate all secrets from config files and environment variables to [SECRETS MANAGER: Kubernetes Secrets + External Secrets Operator / AWS Secrets Manager / Azure Key Vault / HashiCorp Vault / Doppler]. Implement automatic rotation for database credentials, API keys, and certificates. Provide the Kubernetes manifests (ExternalSecret or SecretProviderClass) that sync secrets from [SECRETS MANAGER] into pods. **Feature Flags:** Replace environment-specific code branches with feature flags using [TOOL: LaunchDarkly / Unleash / Flagsmith / custom config map]. This enables the same binary to behave differently per environment without rebuilding. ### Factor IV — Backing Services: Treat as Attached Resources Audit all external services that [APPLICATION] depends on: List every backing service: databases ([DB: PostgreSQL / MySQL / MongoDB / custom]), caches ([CACHE: Redis / Memcached]), message queues ([QUEUE: RabbitMQ / Kafka / SQS]), email services, blob storage, search engines, and third-party APIs. For each, ensure the connection is configured via environment variable (Factor III) so the service can be swapped without code changes. Implement connection string patterns that support [FAILOVER: read replicas / multi-region / connection pooling with PgBouncer or ProxySQL]. Provide health check implementations for each backing service that the application's readiness probe can use. ### Factor V — Build, Release, Run: Strictly Separate Stages Design the three-stage pipeline for [APPLICATION]: **Build Stage:** Compile code, install dependencies, produce immutable artifact (container image). [CI TOOL] pipeline configuration that runs tests, security scanning ([SCANNER: Trivy / Snyk / Grype]), and image building. Tag with git SHA for traceability. **Release Stage:** Combine build artifact with environment-specific configuration. In Kubernetes, this happens via ConfigMaps, Secrets, and Helm values. Each release gets a unique identifier for rollback tracking. Implement [RELEASE TRACKING: Helm revision / ArgoCD history / custom release table]. **Run Stage:** Execute the release in the target environment. The run stage must be able to restart without human intervention. Configure [PLATFORM] to handle process management, and ensure the application starts cleanly with [STARTUP TIME TARGET: under 10s / under 30s / under 60s]. ### Factors VI-XII — Remaining Factors **VI — Processes (Stateless):** Identify and eliminate all in-process state: session data (move to [SESSION STORE: Redis / database / JWT tokens]), file uploads (move to [OBJECT STORE: S3 / Blob Storage / GCS]), local caches (move to [DISTRIBUTED CACHE: Redis / Memcached]). Sticky sessions must be removed. Provide the refactoring steps for each stateful component in [APPLICATION]. **VII — Port Binding:** Ensure the application self-contains its web server (no deploying WAR to external Tomcat). Bind to a port specified by the PORT environment variable. For [TECH STACK], configure the embedded server and verify it works behind [REVERSE PROXY: Kubernetes Ingress / cloud load balancer]. **VIII — Concurrency:** Design the process model for horizontal scaling. Categorize workload types: web (handles HTTP requests, scale by request volume), worker (handles background jobs, scale by queue depth), scheduler (runs periodic tasks, single instance with leader election). For [APPLICATION], define which process types exist and how each scales independently on [PLATFORM]. **IX — Disposability:** Optimize for fast startup and graceful shutdown. Implement SIGTERM handling that stops accepting new requests, drains in-flight requests within [TIMEOUT: 30s], closes database connections cleanly, and exits. For [TECH STACK], provide the shutdown hook code. Reduce startup time by deferring non-critical initialization, warming caches lazily, and precompiling routes at build time. **X — Dev/Prod Parity:** Minimize gaps between development and production. Use [LOCAL DEV: Docker Compose / Tilt / Skaffold / Telepresence / devcontainers] to run the same backing services locally. Eliminate adaptation layers that behave differently per environment. **XI — Logs as Event Streams:** Remove all file-based logging. Configure [LOGGING LIBRARY: Winston / Log4j2 / Serilog / structlog / Zap] to write structured JSON to stdout/stderr. Include request ID, trace ID, user ID, and service name in every log line. Let the platform collect and ship logs to [LOG AGGREGATOR: ELK / Loki + Grafana / CloudWatch / Datadog]. **XII — Admin Processes:** Run admin tasks (database migrations, data fixes, one-time scripts) as one-off processes using the same codebase and config. In Kubernetes, implement these as Jobs or CronJobs using the same container image. Never SSH into a running container to run admin commands.
Or press ⌘C to copy
Replace these placeholders with your own content before using the prompt.
[APPLICATION][TECH STACK][SECRETS MANAGER][CI TOOL][PLATFORM]