Back to Rules

🧠 Cursor Rule — Refactor Safely Without Breaking Public APIs

Official
CursorCode Navigation & Refactoring
cursorrefactoringapi-designbackward-compatibility

Goal

Refactor internal implementation while guaranteeing no breaking changes to public APIs, function signatures, or client contracts. Use automated checks and runtime validation to ensure backward compatibility.

Rule Behavior

1️⃣ Preserve Public Interfaces

  • Keep function signatures, public types, and endpoint contracts unchanged
  • Avoid renaming or removing exported symbols without a migration path
  • When signature changes are unavoidable, provide backward compatible overloads

2️⃣ Adopt a Clear Deprecation Strategy

  • Mark old APIs as deprecated with clear timelines and replacement guidance
  • Provide shims that route calls to new implementations while warning callers
  • Use deprecation logs to track usage before removal

3️⃣ Validate Contracts Programmatically

  • Add contract tests (OpenAPI/TypeScript type checks/JSON schema) to CI
  • Run integration tests that exercise public endpoints end to end
  • Use the Agent to generate test cases based on current contracts

4️⃣ Versioning and Feature Flags

  • Use semantic versioning for library packages and API version headers for services
  • Use feature flags to roll out internal refactors gradually
  • Ensure rollbacks are possible if runtime behavior deviates

5️⃣ Runtime Monitoring and Canary Deploys

  • Deploy refactored code to a canary subset and monitor error rates and latencies
  • Compare telemetry and logs before and after refactor for anomalies
  • Fail fast and roll back on contract regressions

6️⃣ Migration and Data Safety

  • Provide migration scripts with idempotent operations and dry run modes
  • Verify data shape and invariants in staging before production runs
  • Log migrations and provide rollback steps where feasible

7️⃣ Communicate Changes Clearly

  • Document internal refactors, public contract guarantees, and migration steps in PRs
  • Notify integrators and downstream teams before removing or changing APIs

Examples

  • "Refactor this module internals but keep exported function signatures unchanged."
  • "Add a compatibility shim that maps old options to the new API."
  • "Run contract tests against the refactored service and show any mismatches."

Tool Prompts

  • "List all public exports from this package and ensure none are removed."
  • "Generate contract tests for this OpenAPI spec and run them."
  • "Compare logs and metrics for endpoint /orders before and after the refactor."

Quick Implementation Wins

  • Add automated contract checks to CI for every PR
  • Introduce lightweight compatibility shims for high risk changes
  • Run a canary deployment and monitor a small traffic slice before full rollout
View Tool Page