Legacy System Refactoring: From Technical Debt Cleanup to Smooth Service Migration

    This article presents a phased practice for refactoring legacy systems: establish baselines and non-goals, inventory dependencies and unowned services, use the strangler pattern for incremental replacement, migrate data with dual writes and validation, decouple synchronous calls with message queues, add end-to-end tracing and alerting, and validate results against a shared baseline. It focuses on rollback paths, measurable metrics, and clear ownership so teams can reduce technical debt without disrupting business continuity.

    1. Define Refactoring Goals and Non-Goals First

    Before refactoring, the team should record current baseline metrics, including P95 and P99 latency of core APIs, average daily call volume, monthly incident count, deployment frequency, and duration of a single release. These numbers are the baseline for judging whether the refactoring is effective. Without a baseline, it is difficult for the team to prove that the changes brought benefits.

    Goals should be specific. For example, “reduce the P99 latency of the order query API to less than half of the pre-refactoring value” is easier to validate than “improve performance.” Non-goals should also be stated clearly, for example, “this phase will not modify the table schema of the payment module.” Non-goals prevent scope from expanding without limit.

    A technical debt list is recommended to be organized in three columns: problem description, impact scope, and fix cost. Each item should have an assigned owner and a planned completion date.

    2. Inventory Dependencies and Unowned Services

    Unowned services are often the most easily overlooked risk in refactoring. The team can identify interfaces and scheduled tasks that are still in use through the following methods:

    1. Aggregate gateway access logs and count the call sources and volume of each interface over the past 90 days.
    2. Check the scheduled task scheduling platform and confirm the creator, execution records, and output destinations of each task.
    3. Add owner, purpose description, and upstream/downstream dependency list for each service.
    4. For processes with no access records for a long time, first stop traffic access and observe for a complete business cycle instead of deleting them directly.

    Before decommissioning, retain recoverable deployment packages, configuration files, and database snapshots. Clean up resources only after confirmation.

    3. Replace the Legacy System Incrementally with the Strangler Pattern

    The core of the strangler pattern is to place a gateway in front of the legacy system. New features are implemented directly as new services, and old features are gradually moved out. The order of gateway routing decisions is critical. The pseudocode below only illustrates the decision order and is not directly runnable:

    1. // Pseudocode: gateway routing, illustrating decision order only
    2. public class GatewayRouter {
    3. private final GrayConfig grayConfig; // Canary configuration with hot updates
    4. public RouteDefinition route(Request request, long userId) {
    5. // 1. Kill switch has the highest priority; on failure, switch back to the legacy system with one click
    6. if (grayConfig.isKillSwitchOn("order")) {
    7. return new RouteDefinition("legacy-monolith-system");
    8. }
    9. // 2. Exact path rules take precedence over prefix rules
    10. if (request.getPath().startsWith("/api/v2/order")) {
    11. // 3. Use user ID modulo for stable canary; the same user always hits the same side
    12. int bucket = (int) (userId % 100);
    13. if (bucket < grayConfig.getNewRatio("order")) {
    14. return new RouteDefinition("order-service-cluster");
    15. }
    16. return new RouteDefinition("legacy-monolith-system");
    17. }
    18. if (request.getPath().startsWith("/api/v1/order")) {
    19. return new RouteDefinition("legacy-monolith-system");
    20. }
    21. return new RouteDefinition("default-service");
    22. }
    23. }

    The canary ratio should start at 1%. Observe each stage for a period, then gradually increase it based on error rate and latency. Rollback only requires setting the ratio back to 0 or enabling the kill switch.

    Using user ID modulo ensures that requests from the same user consistently land on the same system. If requests for the same order switch back and forth between the two systems, data state can easily diverge.

    Each route destination needs independent monitoring of request volume, error rate, and P99 latency. Comparison of metrics between the old and new sides is the primary basis for judging whether the canary is safe.

    4. Migrate Data: Dual Writes, Validation, and Traffic Cutover

    The difficulty of service migration lies in data. The recommended order is as follows:

    1. Dual-write stage: write to both old and new databases; reads still use the old database as the source of truth.
    2. Validation stage: use offline scripts every day to sample and compare old and new data by primary key, record differing entries, and analyze the causes.
    3. Canary read stage: read from the new database by ratio; pause immediately if the difference rate exceeds a preset threshold.
    4. Primary cutover stage: after consistency is confirmed, switch the read/write source; keep the old database read-only until the observation period ends.
    5. Decommission stage: delete old tables only after the observation period ends and there is no need for rollback.

    During dual writes, a write failure on either side will cause data inconsistency. The team needs compensation tasks and retry queues, persist failed records, and reconcile them regularly. A full backup must be completed before executing migration scripts, and the rollback plan should be rehearsed once in advance.

    5. Use Message Queues to Reduce Synchronous Coupling

    When background tasks are tightly coupled with the main business flow, synchronous calls can be changed to event publishing. Downstream services such as points and notifications consume events asynchronously, and the response time of the main flow is shortened accordingly. The code below is also pseudocode; the dependent client API needs to be adjusted according to the actual SDK:

    1. # Pseudocode: for illustration only, not directly runnable
    2. import json
    3. import time
    4. import uuid
    5. from message_queue_client import MQProducer
    6. producer = MQProducer(brokers=["mq-cluster-node1:9092"], acks="all", retries=5)
    7. def get_current_timestamp() -> int:
    8. # Millisecond timestamp for downstream ordering and deduplication
    9. return int(time.time() * 1000)
    10. def publish_order_completed(order_id: str, user_id: str) -> None:
    11. event_id = str(uuid.uuid4()) # Idempotency key; downstream uses it to determine whether the event was processed
    12. payload = {
    13. "event_id": event_id,
    14. "event_type": "ORDER_COMPLETED",
    15. "order_id": order_id,
    16. "user_id": user_id,
    17. "timestamp": get_current_timestamp(),
    18. }
    19. # Use the order ID as the partition key; events for the same order remain ordered within the partition
    20. producer.send(topic="order-events", key=order_id, value=json.dumps(payload))

    Delivery semantics need to be chosen explicitly:

    • At least once: producer retries may create duplicate messages, so the consumer must implement idempotency. This is the most common choice.
    • At most once: messages may be lost, so it is only suitable for notification scenarios where loss is acceptable.
    • Exactly once: relies on the transactional capabilities of the middleware, has a higher implementation cost, and requires confirming whether the selected middleware supports it.

    On consumption failure, retry with exponential backoff. Messages that exceed the maximum retry count enter the dead-letter queue and are handled by humans or scheduled tasks. Ordering is guaranteed only within the same partition; event order across orders should not be relied upon.

    6. End-to-End Tracing and Alerting

    The foundation of end-to-end tracing is the Trace ID. The gateway generates a Trace ID for each request and passes it between services through HTTP headers. Message events also need to carry a trace_id field; otherwise, asynchronous chains cannot be connected.

    The sampling strategy is recommended as follows: in production, start with 1% sampling, and sample all error requests and slow requests. This controls storage cost while retaining the key data needed for troubleshooting.

    Alert thresholds should be set based on the baseline. For example, trigger an alert only when the error rate exceeds 1% for 5 consecutive minutes, or when P99 exceeds 1.5 times the pre-refactoring baseline. Alerts should have a duration window and be routed by service to avoid overwhelming on-call staff with noise.

    For historical “ghost” interfaces, a separate rule can be set: interfaces outside the allowlist that have had no normal business calls in the past 30 days but still have traffic trigger a dedicated alert for the owner to confirm.

    7. Acceptance Checklist Before and After Migration

    Acceptance needs to be compared against the same baseline, mainly covering the following four categories:

    1. Performance comparison: use the same load-testing script and the same concurrency, and record P95, P99, and error rate.
    2. Data consistency: record the difference rate between old and new databases and confirm that all differences have been attributed.
    3. Rollback drill: rehearse the rollback process at least once completely, and confirm that the duration and steps meet expectations.
    4. Operational metrics: compare deployment duration, failure recovery time, and weekly manual intervention count.

    Conclusions without comparison data should not be written into the retrospective report. Each conclusion needs to include measurement conditions and the raw data source.

    Conclusion

    Legacy system refactoring requires long-term, phased progress. Each stage should have a rollback path, measurable metrics, and a clear owner. By following the order of inventory, replacement, migration, observability, and acceptance, teams can gradually clean up technical debt while ensuring business continuity, and make the system capable of continuous evolution.