PromptBase
Upgrade
Close icon
General
Home
Marketplace
Create
Hire
Login
Chat
Sell
Explore

Prompt Details

Model
Chat - (gpt-6.1-sol)
Token size
3,074
Example input
[CODEBASE_AND_CURRENT_PROBLEMS]: A seven-year-old Node.js SaaS backend has grown into a large modular monolith. Business logic is mixed with controllers, some modules access the database directly, background jobs share application code, tests are inconsistent, and several packages are outdated. Developers are afraid to change billing and account-management code because regressions are common. [MODERNIZATION_GOALS_AND_CONSTRAINTS]: Upgrade the runtime and framework versions, improve testability, reduce coupling, and make billing safer to change. The product must remain operational throughout modernization. We do not want a full microservices rewrite.
Example output
1. EXECUTIVE MODERNIZATION DECISION **Decision: MODULAR RESTRUCTURE + TARGETED REFACTOR + STAGED UPGRADE** **{EVI}[CONF] / Confirmed** - The backend is a seven-year-old Node.js SaaS modular monolith. - Business logic is mixed with controllers. - Some modules access the database directly. - Background jobs share application code. - Tests are inconsistent. - Several packages are outdated. - Billing and account-management changes are regression-prone. - The system must remain operational during modernization. - A full microservices rewrite is explicitly out of scope. The correct direction is **not a rewrite**. The modernization strategy should preserve the monolith as the deployment unit initially, improve its internal boundaries, introduce test seams around high-risk business behavior, and upgrade runtime/framework dependencies separately from architectural restructuring wherever possible. This follows the supplied modernization rule to avoid rewrite-by-default and to modernize in reversible stages with explicit safety evidence. Pasted text **Primary modernization target:** billing. **Recommended modernization pattern:** `OBSERVE → CHARACTERIZE → ISOLATE → INTRODUCE SEAMS → MIGRATE BILLING LOGIC → VERIFY → UPGRADE DEPENDENCIES → CLEAN UP` **Status: READY WITH CONDITIONS** Conditions: 1. Billing behavior must be characterized before restructuring it. 2. Database ownership and transaction boundaries must be mapped. 3. Public/internal consumers of billing/account APIs must be identified. 4. Runtime/framework upgrade compatibility must be established from the actual dependency manifest. 5. Rollback-capable deployment must exist for each production-affecting stage. --- 2. CURRENT SYSTEM MAP | Area | Current State | Evidence | |---|---|---| | Entry points | Likely HTTP controllers plus background-job entry points | **Highly likely** | | Modules | Large modular monolith | **Confirmed** | | Domain logic | Mixed into controllers and shared application code | **Confirmed** | | Data access | Some modules access DB directly | **Confirmed** | | Billing | High-change/high-regression business area | **Confirmed** | | Account management | High-risk change area | **Confirmed** | | Background jobs | Share application code | **Confirmed** | | Shared utilities | Unknown | **Unknown** | | Database engine/schema | Not supplied | **Unknown** | | Framework | Node.js framework exists but not identified | **Unknown** | | Runtime version | Old enough to require upgrade, exact version unknown | **Confirmed / Unknown version** | | External integrations | Not supplied; billing likely has external dependencies | **Plausible only** | | Public contracts | Not supplied | **Unknown** | | Deployment topology | Application must remain continuously operational | **Confirmed constraint** | | Test boundaries | Inconsistent | **Confirmed** | Do not infer package names, framework versions, database engines, payment providers, or architecture paths without repository evidence. The supplied prompt explicitly prohibits inventing code paths, dependencies, runtime compatibility, production behavior, or migration effort. Pasted text --- 3. BEHAVIOR PRESERVATION CONTRACT | Behavior to preserve | Evidence | Regression consequence | Required test | |---|---|---|---| | Correct billing calculations | Billing regressions already occur | Incorrect charges/revenue loss/customer impact | Characterization + domain-rule tests | | Billing side effects occur exactly once | Financial subsystem | Duplicate charges or missed charges | Integration + side-effect/idempotency tests | | Account state transitions | Account management is regression-prone | Incorrect entitlement/access/account state | Characterization tests | | Existing API behavior | Operational continuity required | Client breakage | Contract tests | | Existing persistence semantics | DB access is spread across modules | Data corruption or inconsistent state | Data invariant tests | | Background-job behavior | Jobs share application code | Duplicate/missed processing | Job integration tests | | Authorization behavior | SaaS account/billing domain | Unauthorized account/billing actions | Negative authorization tests | | Failure and retry semantics | Background processing exists | Duplicate effects or silent failure | Retry/idempotency tests | | Production availability | Explicit modernization constraint | Downtime | Deployment health and rollback checks | **Unknown and therefore must be captured before refactoring:** - billing rounding rules; - proration rules; - entitlement activation timing; - cancellation semantics; - retry semantics; - transaction boundaries; - webhook/event ordering; - account lifecycle invariants; - historical edge cases. For poorly understood behavior, the source explicitly establishes the gate: **TEST FIRST — DO NOT REFACTOR YET.** Pasted text --- 4. TECHNICAL DEBT REGISTER | Debt | Type | Impact | Frequency | Change friction | Risk | Evidence | |---|---|---|---|---|---|---| | Business logic inside controllers | Structural / Testability | High | Frequent | High | High | Confirmed | | Direct DB access from modules | Data access / Structural | High | Frequent | High | High | Confirmed | | Shared application code used by jobs | Structural / State | Medium-High | Regular | High | High | Confirmed | | Inconsistent tests | Testability | Very High | Continuous | Very High | Very High | Confirmed | | Outdated packages | Dependency / Security | Potentially High | Upgrade-related | Medium-High | Unknown until audit | Confirmed | | Billing regressions | Structural / Testability / Domain | Very High | Recurrent | Very High | Critical | Confirmed | | Account-management regression fear | Structural / Testability | High | Recurrent | High | High | Confirmed | | Unknown module ownership | Structural | Potentially High | Unknown | High | High | Highly likely | | Unknown contract consumers | API / Contract | Potentially High | Unknown | High | High | Unknown | | Weak runtime observability | Observability | Unknown | Unknown | Unknown | Unknown | No evidence | Priority order should be based on operational and business risk, not code age or aesthetics, consistent with the supplied modernization criteria. Pasted text --- 5. CHANGE HOTSPOT MAP ### HOTSPOT 1 — Billing **Why it matters:** financial logic + recurrent regressions + developer avoidance. **Blast radius:** likely high. **Test deficit:** confirmed generally; billing-specific depth unknown. **Modernization value:** **Very High** **Decision:** REFACTOR + WRAP --- ### HOTSPOT 2 — Account Management **Why it matters:** core SaaS identity/account state and reported regression fear. **Blast radius:** high. **Test deficit:** likely material. **Modernization value:** **High** **Decision:** REFACTOR after billing seam exists. --- ### HOTSPOT 3 — Direct Database Access **Why it matters:** makes business logic, persistence, and transactions difficult to isolate. **Blast radius:** potentially system-wide. **Modernization value:** **High**, but migration should be incremental. **Decision:** WRAP behind repository/data-access boundaries. --- ### HOTSPOT 4 — Background Jobs **Why it matters:** jobs share application code, creating hidden coupling between synchronous and asynchronous execution. **Modernization value:** **Medium-High** **Decision:** isolate job orchestration from domain behavior. --- ### HOTSPOT 5 — Runtime and Dependencies **Why it matters:** modernization requires upgrades and outdated packages exist. **Modernization value:** High. **Risk:** unknown until dependency and compatibility inventory exists. **Decision:** UPGRADE in controlled groups, not one large dependency sweep. --- 6. DEPENDENCY & COUPLING MAP ### Confirmed coupling `Controllers → Business Logic` Current classification: **TIGHT COUPLING** --- `Modules → Database` Current classification: **TIGHT / HIDDEN COUPLING** Problem: persistence details leak into business modules. --- `Background Jobs → Shared Application Code` Current classification: **TIGHT COUPLING** Risk: changes intended for HTTP execution may alter asynchronous execution semantics. --- `Billing ↔ Account Management` Classification: **Likely coupled**, but exact direction and dependency graph are unknown. --- ### Discovery required Map before extraction: - controller → service calls; - service → module calls; - module → DB access; - job → shared logic; - billing → account dependencies; - billing → external integrations; - transaction boundaries; - shared configuration; - global/singleton state; - events; - scheduled jobs; - shared tables; - package dependency graph. No extraction should occur until ownership and dependencies are understood, which is an explicit constraint of the supplied modernization process. Pasted text --- 7. REFACTOR VS REWRITE DECISION ### Result: MODULAR RESTRUCTURE **Full rewrite: REJECT** Reason: - working production behavior already exists; - continuous operation is mandatory; - business rules are incompletely characterized; - billing regression risk is already high; - rewriting would multiply unknown behavioral assumptions; - the stated goal explicitly rejects a microservices rewrite. ### Strangler migration **Potentially useful internally**, but not as a service decomposition strategy initially. Use a strangler pattern around billing interfaces: `Legacy Controller` → `Billing Facade` → either `Legacy Billing Path` or `Refactored Billing Service` This enables side-by-side migration without changing the deployment architecture. ### Targeted replacement Use only where a dependency is demonstrably unsupported, insecure, or blocks the runtime upgrade. ### Full microservices extraction **DEFER** There is currently no evidence that deployment-level decomposition solves the dominant problem better than internal modularization. --- 8. MODERNIZATION TARGETS ### Target A — Billing Domain **Current responsibility:** mixed business/application behavior. **Target responsibility:** isolated domain/application service with stable contracts. **What moves:** - billing decision logic; - calculation rules; - billing state transitions; - billing orchestration. **What stays initially:** - deployment model; - database schema unless change becomes necessary; - public API surface. **Public contract:** preserve existing behavior. **Rollback boundary:** facade routes calls back to legacy implementation. --- ### Target B — Account Management Introduce an application-service boundary after billing behavior is protected. Do not combine billing and account refactors into one release. --- ### Target C — Data Access Move direct persistence calls behind repositories or explicit data-access interfaces incrementally. Do **not** begin with a system-wide repository rewrite. Prioritize: 1. billing; 2. account management; 3. modules touched frequently. --- ### Target D — Background Jobs Separate: `Job Trigger` → `Job Application Handler` → `Domain Service` → `Repository / External Adapter` Jobs and HTTP controllers may share domain services, but should not share transport/orchestration logic. --- ### Target E — Runtime / Framework Upgrade through an explicit compatibility matrix. Do not mix every dependency upgrade with billing restructuring. --- 9. SAFE SEAMS ### Seam 1 — Billing Facade **Why safe:** creates one entry point without requiring immediate behavior changes. **Isolates:** controllers/jobs from billing implementation. **Enables:** characterization tests, contract tests, legacy-vs-new comparison. **Unlocks:** progressive billing refactor. --- ### Seam 2 — Billing Repository Interface **Why safe:** allows DB interaction to be characterized before changing schema or queries. **Isolates:** business rules from persistence. **Enables:** deterministic service tests. --- ### Seam 3 — Account Service Wrap existing account operations behind a stable application-level interface. --- ### Seam 4 — Job Handler Boundary Replace direct shared-application invocation with explicit commands/use cases. --- ### Seam 5 — Feature Flag / Routing Gate Allow new billing implementation to be enabled selectively while legacy behavior remains available. This follows the source's recommended seam patterns: interfaces, adapters, facades, service boundaries, repository layers, feature flags, and data-access abstractions. Pasted text --- 10. TEST HARNESS PLAN ### Highest-value first test **Billing characterization test suite** Capture behavior from the current production-equivalent implementation before refactoring. Test classes: **1. Characterization tests** Protect existing calculations and transitions. **2. Contract tests** Verify controller/API input/output semantics remain stable. **3. Integration tests** Exercise billing + persistence + key integrations. **4. Data invariant tests** Examples to discover and encode: - no impossible subscription state; - no orphan billing record; - no invalid account/billing relationship. Actual invariants must come from code/data/domain evidence. **5. Negative authorization tests** Verify unauthorized users cannot alter billing/account state. **6. Side-effect tests** Protect against duplicate charges, duplicate events, duplicate messages, or repeated state mutation where applicable. **7. Regression fixtures** Convert every known billing regression into a permanent test. ### Test strategy Use a pyramid weighted toward: `Domain tests > application service tests > contract tests > selective end-to-end tests` Do not attempt to achieve arbitrary repository-wide coverage before beginning. Protect high-risk behavior first. --- 11. DEPENDENCY UPGRADE PLAN Exact versions cannot be recommended from the supplied evidence. ### Phase A — Inventory Capture: - current Node.js version; - target supported Node.js version; - framework/version; - ORM/database drivers; - authentication libraries; - billing/payment SDKs; - job framework; - test framework; - build tooling; - native dependencies. ### Phase B — Classify Each package becomes: - **INDEPENDENT UPGRADE** - **COUPLED UPGRADE** - **BREAKING CHANGE** - **UNKNOWN COMPATIBILITY** ### Phase C — Upgrade order 1. testing/tooling dependencies; 2. libraries with low runtime coupling; 3. runtime prerequisites; 4. Node.js runtime; 5. framework; 6. tightly coupled ecosystem packages; 7. billing-sensitive SDKs separately. ### Critical rule Do not combine: - Node runtime jump; - framework major version jump; - billing architecture refactor; - schema changes into the same deployment. The source explicitly says unrelated upgrades should not be bundled without justification. Pasted text --- 12. DATA & SCHEMA MIGRATION PLAN **Current schema:** UNKNOWN. Therefore no schema redesign is currently justified. Initial recommendation: **KEEP existing schema unless the billing/data-access refactor reveals a concrete blocker.** Introduce repository boundaries before altering storage structures. If schema change later becomes necessary: `Deploy compatible readers` → `Add backward-compatible schema` → `Backfill` → `Validate` → `Switch reads` → `Switch writes` → `Observe` → `Remove legacy schema only after cleanup gate` Never perform a destructive schema migration before compatible code exists. Pasted text ### Primary data risk Hidden assumptions caused by modules directly accessing the database. Examples requiring discovery: - duplicate query implementations; - shared-table ownership; - cross-module transactions; - implicit transaction ordering; - DB-side defaults/triggers; - jobs mutating the same state as request handlers. These are investigation targets, not confirmed facts. --- 13. API / CONTRACT MODERNIZATION Initial position: **KEEP external API behavior stable.** Modernize behind existing contracts first. For each billing/account endpoint or internal callable interface, capture: | Field | Requirement | |---|---| | Current contract | Request, response, status/error behavior | | Known consumers | UI, internal modules, jobs, integrations | | Target contract | Prefer unchanged initially | | Compatibility | Required | | Versioning | Only if semantic change becomes necessary | | Deprecation | Explicit period | | Observability | Usage/error measurement | | Removal condition | No remaining consumers + regression safety | Undocumented consumers must be treated as potential consumers until usage is observed. The source explicitly rejects breaking contracts merely because consumers were undocumented. Pasted text --- 14. MODERNIZATION SEQUENCE ### Step 1 — Observe **Change:** add/confirm observability around billing and account paths. **Validation:** establish baseline requests, failures, job failures, billing error classes. **Rollback:** no behavioral change. **Gate:** operational baseline exists. --- ### Step 2 — Characterize Billing **Dependency:** current system behavior. **Change:** build billing characterization + contract tests. **Validation:** tests reproduce current behavior. **Rollback:** tests only. **Gate:** critical billing cases captured. --- ### Step 3 — Introduce Billing Facade **Dependency:** characterization tests. **Change:** controllers/jobs call facade rather than internal implementation directly. **Validation:** regression suite passes. **Rollback:** restore direct legacy call. **Gate:** facade has no semantic differences. --- ### Step 4 — Isolate Billing Data Access **Dependency:** facade. **Change:** introduce billing repository/data gateway. **Validation:** DB integration and invariant tests. **Rollback:** facade can still invoke legacy path. --- ### Step 5 — Extract Billing Business Logic **Dependency:** facade + persistence seam + tests. **Change:** move business rules from controllers/modules into domain/application services. **Validation:** old-vs-new behavior comparison. **Rollback:** route facade to legacy implementation. --- ### Step 6 — Stabilize Account Boundary Repeat the same seam-first strategy for account management. --- ### Step 7 — Separate Job Orchestration Jobs call explicit application use cases instead of controller/shared transport logic. --- ### Step 8 — Runtime/Framework Upgrade Perform after sufficient behavior safety exists. Use isolated upgrade branches/releases. --- ### Step 9 — Dependency Cleanup Replace obsolete libraries only when needed for: - support; - security; - runtime compatibility; - maintainability; - removal of architectural blockers. --- ### Step 10 — Legacy Cleanup Only after: - new path is production-proven; - legacy traffic is zero; - rollback window is closed; - tests cover migrated behavior. This sequence directly follows the supplied preferred progression of observe → characterize → isolate → introduce seam → migrate → verify → shift usage → clean up. Pasted text --- 15. DO-NOT-TOUCH MAP Until stronger evidence exists: | Component | Decision | Reason | |---|---|---| | Stable low-change modules | KEEP | No evidence-supported modernization need | | Database schema | KEEP initially | No demonstrated schema problem | | Deployment architecture | KEEP | No need for microservices | | Public API shape | KEEP initially | Continuity requirement | | Working background jobs | WRAP before redesign | Behavior risk exceeds immediate redesign value | | Unrelated old code | DEFER | Age alone is not evidence of debt | | Low-risk libraries | DEFER unless runtime/security requires upgrade | Avoid unnecessary change | The modernization brief explicitly states that stable areas should not be rewritten merely because modernization is underway. Pasted text --- 16. FAILURE & REGRESSION MATRIX | Change | Breakage path | Impact | Detection | Rollback | |---|---|---|---|---| | Billing facade introduction | Routing/parameter mismatch | Billing failures | Contract + integration tests | Restore legacy call | | Billing logic extraction | Semantic drift | Incorrect charges | Characterization comparison | Route facade to legacy | | Repository introduction | Query/transaction change | Data inconsistency | DB integration + invariant tests | Legacy data path | | Account refactor | State-transition regression | Access/account corruption | State-transition tests | Legacy account implementation | | Job isolation | Retry/idempotency mismatch | Duplicate/missed work | Job integration metrics/tests | Previous job handler | | Node upgrade | Runtime incompatibility | Startup/runtime failure | CI + staging/runtime health | Previous runtime image | | Framework upgrade | Routing/middleware semantics | API failure | Contract tests | Previous release | | Library replacement | Changed hidden behavior | Runtime/business regression | Focused integration tests | Restore dependency | | Schema migration | incompatible reader/writer | Data corruption/outage | reconciliation/invariants | backward-compatible schema/code | | Feature rollout | unknown production edge case | customer-visible regression | metrics/error rates | flag off | Priority failure classes: 1. data loss; 2. authorization regression; 3. incorrect billing; 4. duplicate side effects; 5. state corruption; 6. API breakage; 7. deployment failure; 8. performance regression. These align with the failure categories explicitly prioritized in the supplied modernization framework. Pasted text --- 17. IMPLEMENTATION TASK GRAPH | Task ID | Target | Change | Dependency | Priority | Validation | Definition of Done | |---|---|---|---|---|---|---| | MOD-001 | Billing | Inventory billing entry points and side effects | None | P0 | Architecture review | All known billing paths documented | | MOD-002 | Billing | Create characterization test suite | MOD-001 | P0 | Existing behavior captured | Critical billing flows executable | | MOD-003 | Contracts | Capture billing/account API contracts | MOD-001 | P0 | Contract tests | Existing consumer behavior protected | | MOD-004 | Billing | Introduce BillingFacade | MOD-002/003 | P0 | Regression tests | Calls pass through facade without semantic change | | MOD-005 | Persistence | Map billing DB access and transactions | MOD-001 | P0 | Code/query review | Billing persistence dependencies known | | MOD-006 | Persistence | Introduce billing repository interface | MOD-004/005 | P1 | Integration tests | Billing domain no longer requires direct DB calls | | MOD-007 | Domain | Extract billing rules into service/domain layer | MOD-006 | P1 | Old-vs-new tests | Controller billing logic materially reduced | | MOD-008 | Deployment | Add billing feature-routing/rollback switch | MOD-004 | P1 | Deployment test | Legacy/new implementation switchable | | MOD-009 | Accounts | Characterize account lifecycle | MOD-002 | P1 | State-transition tests | High-risk account behavior protected | | MOD-010 | Accounts | Introduce AccountService boundary | MOD-009 | P1 | Contract/regression tests | Controller logic isolated | | MOD-011 | Jobs | Inventory job/application coupling | MOD-001 | P1 | Dependency map | Job call graph known | | MOD-012 | Jobs | Introduce explicit job handlers/use cases | MOD-011 | P2 | Job integration tests | Jobs no longer depend on transport logic | | MOD-013 | Dependencies | Build runtime/package compatibility matrix | Tests established | P1 | CI matrix | Upgrade blockers known | | MOD-014 | Runtime | Upgrade Node runtime | MOD-013 | P1 | CI/staging regression suite | Supported runtime passes defined gates | | MOD-015 | Framework | Upgrade framework separately | MOD-014 | P2 | Contract/integration tests | Target version stable | | MOD-016 | Cleanup | Remove obsolete billing path | Production evidence | P3 | zero legacy usage | rollback period completed | --- 18. MODERNIZATION EXECUTION PACK **MODERNIZATION DECISION** REFACTOR + WRAP + UPGRADE. Preserve the modular monolith as the initial deployment architecture. **PRIMARY PROBLEM** Billing is difficult and unsafe to change because business behavior, persistence, and application boundaries are insufficiently isolated and protected by tests. **PRESERVE** Existing billing semantics, account state transitions, API behavior, persistence invariants, authorization, asynchronous side effects, and operational availability. **DO NOT TOUCH** Stable low-change modules, schema, public interfaces, and deployment boundaries unless evidence shows they block the modernization. **FIRST SAFE SEAM** `BillingFacade` Controllers and jobs should call a single billing application boundary while the legacy implementation remains behind it. **FIRST TEST** Billing characterization tests covering the highest-risk existing business flows and known regression cases. **FIRST CHANGE** Introduce the billing facade with **no intended semantic change**. **DEPENDENCY RISK** Hidden coupling created by direct database access and shared application code between controllers/jobs/modules. **DATA RISK** Unknown cross-module ownership and transaction assumptions around directly accessed database state. **CONTRACT RISK** Undocumented internal or external consumers may depend on current billing/account behavior. **ROLLBACK POINT** Until the legacy billing implementation is deleted, the facade or feature-routing layer should allow immediate return to the legacy path. **NEXT 5 ENGINEERING TASKS** 1. Map all billing entry points, side effects, DB calls, jobs, and known consumers. 2. Build billing characterization and regression tests. 3. Capture billing/account API and application contracts. 4. Introduce `BillingFacade` without changing behavior. 5. Map and then wrap billing persistence behind a repository/data-access boundary. **CLEANUP CONDITION** Remove legacy billing code only after the replacement path has production evidence, contract/regression tests pass, legacy usage reaches zero, rollback is no longer required, and data reconciliation shows no semantic divergence. **STATUS** **READY WITH CONDITIONS** The architecture should be modernized internally before considering deployment-level decomposition. The highest-value intervention is not “make the code newer”; it is **make billing behavior observable, testable, isolated, reversible, and safe to change**. This is also consistent with the source requirement that modernization decisions be driven by preserved behavior, real coupling, value, risk, reversibility, and evidence—not code age. Pasted text
GPT

Legacy Code Modernization Refactor

Add to Cart
Instant accessInstant access
Usage rightsCommercial use
Money-back guaranteeMoney‑back
By purchasing this prompt, you agree to our terms of service
GPT-6.1-SOL
Tested icon
Guide icon
4 examples icon
Free credits icon
Turn a difficult legacy codebase into a safe, staged modernization plan. This prompt reconstructs system behavior, identifies fragile boundaries and technical debt, separates refactor opportunities from rewrite traps, maps dependencies and regression risks, and produces a file/module-level implementation sequence with preservation rules, migration gates, test requirements, rollback points, and a final REFACTOR / REPLACE / WRAP / DEFER decision.
...more
Added 4 days ago
Report
Browse Marketplace