Thursday, October 9, 2025

Background Service in Micro Services - Complete Guide

 A background service that monitors a database for changes (like new orders) and then acts on them. I’ll explain the flow step by step, typical in a .NET Core + Web API + SQL Server environment.

1. What is a Background Service?

In .NET Core, a background service is a long-running process that executes independently of HTTP requests. It can continuously run in the background and perform tasks like:

  • Polling a database

  • Sending emails or notifications

  • Processing queues or orders

In .NET Core, we usually implement it using IHostedService or BackgroundService.


2. High-Level Flow for Database Polling

Imagine your scenario: the service checks for new orders and processes them.

  1. Database

    • Table: Orders

    • Columns: OrderId, CustomerId, Status, CreatedAt, etc.

    • New orders are inserted with Status = 'Pending'.

  2. Background Service (C#)

    • Runs continuously in the background.

    • Periodically checks the Orders table for Status = 'Pending'.

    • Picks up pending orders and updates them to Processing or triggers other actions.

  3. Processing Flow

    • Fetch orders:

      var pendingOrders = dbContext.Orders .Where(o => o.Status == "Pending") .ToList();
    • Process orders (e.g., send to shipping service, generate invoice, etc.)

    • Update status:

      order.Status = "Processed"; dbContext.SaveChanges();
  4. Notification (Optional)

    • Once processed, the service can send notifications via email, push notifications, or enqueue messages in a message broker like Azure Service Bus.


3. Sample Flow Diagram

Angular / Frontend | | [Customer places order] v SQL Server (Orders Table) | | [Background Service polls DB periodically] v .NET Core Background Service | |-- Fetch pending orders |-- Process orders |-- Update status |-- Send notifications (optional) v External services / APIs / Notifications

4. Polling vs Event-Driven Approach

  • Polling:
    The background service queries the database every N seconds/minutes. Simple but less efficient for large-scale systems.

  • Event-driven:
    Instead of polling, use a message broker (Azure Service Bus, RabbitMQ, Kafka).

    • Orders insert triggers a message.

    • Background service subscribes and processes only when a new order arrives.

    • More scalable and real-time.


5. Example: Implementing BackgroundService in .NET Core

public class OrderProcessingService : BackgroundService { private readonly IServiceScopeFactory _scopeFactory; public OrderProcessingService(IServiceScopeFactory scopeFactory) { _scopeFactory = scopeFactory; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { using var scope = _scopeFactory.CreateScope(); var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>(); var pendingOrders = await dbContext.Orders .Where(o => o.Status == "Pending") .ToListAsync(); foreach (var order in pendingOrders) { // Process order order.Status = "Processed"; } await dbContext.SaveChangesAsync(); // Wait for some time before next check await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken); } } }

Summary of the Flow:

  1. Frontend inserts an order into SQL Server.

  2. Background service wakes up periodically.

  3. It queries the database for pending orders.

  4. Processes each order.

  5. Updates the order status.

  6. Optional: sends notifications or triggers other services.

  7. Repeats indefinitely.

Tuesday, October 7, 2025

🔑 Where to Configure Ports in .NET Core

 There are 3 main ways:


1️⃣ launchSettings.json (Local Development Only)

  • Located in:
    Properties/launchSettings.json

Example:

{ "profiles": { "ProductService": { "commandName": "Project", "dotnetRunMessages": true, "applicationUrl": "http://localhost:5002;https://localhost:7002", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }

👉 This means:

  • ProductService will listen on http://localhost:5002 and https://localhost:7002.

  • Useful for local debugging.


2️⃣ appsettings.json or appsettings.{Environment}.json

  • You can configure Kestrel endpoints directly.

Example:

{ "Kestrel": { "Endpoints": { "Http": { "Url": "http://localhost:5002" }, "Https": { "Url": "https://localhost:7002" } } } }

👉 This works in development, staging, and production.
👉 More flexible, especially when deploying in Docker/Kubernetes.


3️⃣ Hardcode in Program.cs (Not Recommended for Production)

var builder = WebApplication.CreateBuilder(args); builder.WebHost.UseUrls("http://localhost:5002", "https://localhost:7002"); var app = builder.Build(); app.MapControllers(); app.Run();

👉 Quick way to bind to specific ports, but harder to manage in large deployments.


⚙️ Best Practices

  1. Local Development → use launchSettings.json.

  2. Production (IIS, Azure, Docker, Kubernetes)

    • Use appsettings.json (Kestrel:Endpoints).

    • Or environment variables → DOTNET_URLS=http://+:5002.

  3. Dockerized Microservices → expose ports in Dockerfile / docker-compose.yml. Example:

    EXPOSE 5002
    ports: - "5002:5002"

✅ Summary

  • launchSettings.json → local dev only.

  • appsettings.json (Kestrel) → preferred for production.

  • Program.cs → UseUrls() → quick overrides.

  • Environment Variables / Docker → best in containerized/cloud setups.

Blog Archive

Don't Copy

Protected by Copyscape Online Plagiarism Checker

Pages