Transform Your .NET Monolith application with the Sidecar Pattern

Adding Festival Discounts to Item API with Zero Disruption!

DotNet Full Stack Dev
4 min readOct 28, 2024

Imagine this: it’s festival season, and your users are buzzing with excitement! They’re expecting discounts, offers, and deals — but your monolithic Item API just doesn’t support this functionality. Normally, you’d have to crack open the codebase and risk introducing bugs. But what if there was a way to add discounts seamlessly, without touching your core application?

Introducing the Sidecar Pattern! With this pattern, you can deploy new features like festival discounts independently and with minimal risk. Ready to bring in the “WOW!” factor for your users? Let’s dive in!

📌Explore more at: https://dotnet-fullstack-dev.blogspot.com/
🌟 Clapping would be appreciated! 🚀

🌐 What is the Sidecar Pattern?

In simple terms, the Sidecar Pattern allows us to add complementary features to an application by running them in a separate container that sits right next to the main app. Think of it as a “companion” service to your Item API. This sidecar service can handle new features — like calculating festival discounts — without disturbing the monolithic application.

Key benefits of this approach:

  • Isolated Development: No need to modify the core API.
  • Independent Deployment: Update or fix the discount feature without redeploying the whole app.
  • Enhanced Scalability: Scale the sidecar independently based on demand.

🚀 Step-by-Step Guide: Adding a Festival Discount Sidecar

Let’s walk through setting up the Sidecar Pattern for your Item API and implementing the festival discount logic!

Step 1: Define the Sidecar Service (Discount API)

First, we’ll create a new microservice called DiscountAPI to handle the festival discounts. Since it’ll sit alongside our Item API, it will listen for discount requests and return the calculated price with the discount applied.

Set Up the Project:

  • Start a new ASP.NET Core Web API project called DiscountAPI.
  • Add an endpoint to accept the item ID and return a discount for it.

Define the Discount Logic:

  • In our discount logic, we’ll apply a 20% festival discount for all items. You can extend this logic to handle other conditions later.
public class DiscountController : ControllerBase
{
[HttpGet("{itemId}")]
public IActionResult GetDiscountedPrice(int itemId)
{
// Mock discount calculation
var discountRate = 0.20;
var itemPrice = GetItemPrice(itemId); // Simulating item price retrieval
var discountedPrice = itemPrice * (1 - discountRate);

return Ok(new { ItemId = itemId, DiscountedPrice = discountedPrice });
}

private double GetItemPrice(int itemId)
{
// Placeholder for retrieving actual price
return 100.0; // Assume item price is $100 for demo
}
}

This API will return a JSON response with the discounted price, which our main application can fetch whenever it needs to display the festival discount.

Step 2: Integrate the Sidecar with the Main Application

Now that we have a separate DiscountAPI up and running, let’s modify our Item API to communicate with this sidecar.

Configure HTTP Client:

  • Use HttpClient to call the DiscountAPI and retrieve the discount details.

Enhance Item API to Include Discount Information:

  • Add an endpoint in Item API that fetches the original item details and then calls DiscountAPI for the discounted price.
public class ItemController : ControllerBase
{
private readonly IHttpClientFactory _httpClientFactory;

public ItemController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}

[HttpGet("{id}/festival-discount")]
public async Task<IActionResult> GetItemWithDiscount(int id)
{
var item = GetItemDetails(id); // Mock method to retrieve item info

var discountClient = _httpClientFactory.CreateClient();
var discountResponse = await discountClient.GetAsync($"http://localhost:5001/api/discount/{id}");
var discountData = await discountResponse.Content.ReadAsAsync<dynamic>();

return Ok(new
{
ItemId = item.Id,
OriginalPrice = item.Price,
DiscountedPrice = discountData?.DiscountedPrice
});
}

private Item GetItemDetails(int id)
{
// Mock data retrieval for item
return new Item { Id = id, Price = 100.0, Name = "Sample Item" };
}
}

public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}

Here’s what’s happening:

  • The GetItemWithDiscount endpoint fetches basic item details.
  • It then sends a request to the DiscountAPI sidecar to get the discounted price.
  • Finally, it combines the original price and discounted price into a single response.

🔗 Step 3: Containerize and Deploy the Sidecar

Deploying both services is a breeze with Docker. Here’s how:

Containerize DiscountAPI:

  • Add a Dockerfile to DiscountAPI and Item API if they’re not already containerized.
# Dockerfile for DiscountAPI
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "DiscountAPI.dll"]

Run Both Containers with Docker Compose:

  • Use Docker Compose to deploy Item API and DiscountAPI as separate containers.
version: '3.4'

services:
item-api:
image: item-api
build:
context: .
dockerfile: ItemAPI/Dockerfile
ports:
- "5000:80"

discount-api:
image: discount-api
build:
context: .
dockerfile: DiscountAPI/Dockerfile
ports:
- "5001:80"

Run: In the terminal, run docker-compose up to start both services.

And boom! Now you have a festival discount feature deployed alongside your Item API with zero disturbance to the main codebase. The Sidecar Pattern has turned your monolithic application into a powerhouse with the flexibility of microservices!

🎉 The “WOW!” Factor: Why the Sidecar Pattern Rocks

Not only have you added a festival discount without altering the main codebase, but you’ve also set yourself up for future expansion. Imagine adding other sidecars for features like:

  • Special Membership Discounts: Launch a sidecar for membership-based pricing.
  • Inventory Management: Spin up another sidecar to track inventory levels.

The Sidecar Pattern lets you be agile, responsive, and innovative — all while keeping your core application stable. Now, your monolith is festival-ready with a sprinkle of microservice magic!

🎬 Final Takeaway: Keep Your Core Stable and Enhance with Sidecars

The Sidecar Pattern is a game-changer for adding new features without disrupting your monolithic application. As you continue to build out functionalities like DiscountAPI, remember that this pattern doesn’t just save time — it’s a scalable, future-proof way to evolve your app. So, next time there’s a festival season rush, or a new feature request, your Item API is ready to adapt without breaking a sweat!

--

--

DotNet Full Stack Dev
DotNet Full Stack Dev

Written by DotNet Full Stack Dev

Join me to master .NET Full Stack Development & boost your skills by 1% daily with insights, examples, and techniques! https://dotnet-fullstack-dev.blogspot.com

No responses yet