← Back to list

The Legacy Migrator’s Diary: Week 2

The Open/Closed Principle Meets the Cost Optimization Pillar

Mohammed Naved · 2026-06-02 08:16 · 0 claps · 3.1 min read
#aws-fargate #dotnet #solid-principles #monolithic-architecture #wellarchitectedframework
Open on Medium ↗
Wiki topics: ☁️ · DevOps & Cloud 🏛️ · Architecture

The Legacy Migrator’s Diary: Week 2

The Open/Closed Principle Meets the Cost Optimization Pillar

The Journal Entry

It’s Tuesday of Week 2, and the finance team just handed us a reality check. Last quarter, our cloud infrastructure bills spiked during a high-traffic flash sale because our core processing monolith kept calling heavy, resource-intensive recommendation algorithms for every single click. On top of that, leadership announced plans to expand our e-commerce platform into regions with strict data sovereignty acts (like China), meaning we can no longer rely on a single cloud provider’s proprietary database everywhere.

If we keep hardcoding our business logic to specific vendor APIs, we violate the AWS Well-Architected Cost Optimization and Reliability Pillars. We need our system to adapt to fluctuating traffic, throttle expensive features dynamically when budgets bleed, and route data seamlessly based on local country restrictions — all without rewriting our core checkout code every single time.

This week, we are weaponizing the Open/Closed Principle (OCP). Software artifacts should be open for extension, but closed for modification. By using C# abstractions, we will give our core checkout engine running on ECS Fargate the power to dynamically offload spikes and shift storage targets on the fly!

The Refactoring Ledger

The Before: The Rigid, Vendor-Locked Checkout

In the legacy code, the checkout pipeline was tightly coupled to a specific cloud database and ran expensive, heavy analytics right inside the main thread. Switching cloud providers or throttling features meant modifying the core checkout class, risking new bugs in production.

public class LegacyCheckoutEngine
{
    public void CompleteOrder(Order order)
    {
        // Hardcoded direct dependency to a specific cloud provider's DB
        var awsDbClient = new AmazonDynamoDBClient(); 
        awsDbClient.PutItemAsync("OrdersTable", null);

        // Heavy, expensive AI recommendation logic running synchronously
        var recommendationService = new PremiumAiAnalytics();
        recommendationService.GenerateUpSells(order); 
    }
}

Why this fails Cost Optimization & Multi-Cloud Readiness: If a country’s regulations force us to use a local clouThe After: OCP-Compliant Code & Hybrid Cloud Routing

We refactored the checkout system by introducing abstract interfaces for data persistence and feature execution. The core execution engine inside our ECS Fargate container is now completely insulated. It handles the order workflow smoothly and doesn’t care how a feature is implemented under the hood.

1. The Core Checkout Engine (Closed for Modification on ECS Fargate)

Our core containerized engine relies entirely on abstractions. It handles baseline, predictable e-commerce traffic reliably and cost-effectively.d provider’s database instead of DynamoDB, this code breaks. If the AI service gets too expensive during a flash sale, we can’t turn it off without modifying and redeploying the entire checkout engine.

public class OcpCheckoutEngine
{
    private readonly IOrderRepository _orderRepository;
    private readonly IAiFeatureExtension _aiExtension;

    // The engine depends only on abstractions, making it Open for Extension
    public OcpCheckoutEngine(IOrderRepository orderRepository, IAiFeatureExtension aiExtension)
    {
        _orderRepository = orderRepository;
        _aiExtension = aiExtension;
    }

    public async Task ProcessCheckoutAsync(Order order, UserContext context)
    {
        // 1. Save order using whatever localized compliance repository is injected at runtime
        await _orderRepository.SaveOrderAsync(order);

        // 2. Execute AI logic via the injected extension behavior
        await _aiExtension.ExecuteFeatureAsync(order, context);
    }
}

2. The Cost-Throttling & Offloading Extension (Open for Extension)

Now, what happens when traffic spikes or a data restriction hits? We simply create new implementations of our interfaces without touching a single line of code inside OcpCheckoutEngine.

If our primary server becomes overloaded, or if a regional data law requires localized, isolated compute, we can inject a Cost-Throttling Lambda Extension. This extension evaluates a fast runtime feature flag: if costs or compute limits are exceeded, it completely bypasses the expensive processing loop and offloads variable traffic onto an AWS Lambda function triggered by SQS, keeping our core container lean and our cloud bill under control!

public class CostThrottlingAiExtension : IAiFeatureExtension
{
    private readonly IAmazonSQS _sqsClient;
    private readonly ICostFeatureFlagService _flagService;

    public CostThrottlingAiExtension(IAmazonSQS sqsClient, ICostFeatureFlagService flagService)
    {
        _sqsClient = sqsClient;
        _flagService = flagService;
    }

    public async Task ExecuteFeatureAsync(Order order, UserContext context)
    {
        // Check real-time cost guardrails or regional overrides
        if (await _flagService.IsBudgetExceededOrInRestrictedZoneAsync(context.Region))
        {
            // COST OPTIMIZATION: Throttling feature or offloading processing to save container compute
            return; 
        }

        // TRAFFIC SPIKE BALANCE: Offload the execution asynchronously to AWS Lambda via SQS
        var messageBody = JsonSerializer.Serialize(new { Order = order, User = context });
        await _sqsClient.SendMessageAsync("https://sqs.us-east-1.amazonaws.com/ai-processing-queue", messageBody);
    }
}

3. The Multi-Cloud Data Sovereignty Extension

If the code is deployed in a region with strict data acts (like China), we don’t rewrite the checkout engine. We simply swap the repository implementation at the Dependency Injection layer, pointing to an entirely different cloud infrastructure provider’s local data center!

The Cost Optimization & Multi-Cloud Win

By designing our C# architecture around the Open/Closed Principle, we unlocked ultimate infrastructure elasticity. Our core ECS Fargate container handles predictable transaction flows with a locked-in framework version. When seasonal traffic surges or data residency restrictions change, we easily extend the system by snapping in AWS Lambda offloaders or local database providers without modifying a single line of our core, audited billing code


메타데이터
post_id
424ca49781ac
slug
the-legacy-migrators-diary-week-2-424ca49781ac
url
https://medium.com/@naved-shaikh/the-legacy-migrators-diary-week-2-424ca49781ac
canonical_url
https://medium.com/@naved-shaikh/the-legacy-migrators-diary-week-2-424ca49781ac
author_url
https://medium.com/@naved-shaikh
status
ok
fetched_at
2026-07-13 06:23:13