Monday, August 31, 2026

Azure Red Hat OpenShift (ARO) with .NET Core — Complete Guide with Real-Time Example

 

Important clarification: Azure Red Hat OpenShift (ARO) is not mandatory for .NET Core/.NET applications. It is an enterprise container platform that can be an excellent choice when an organization wants OpenShift/Kubernetes capabilities with Azure-managed infrastructure. Microsoft describes ARO as a fully managed OpenShift service jointly operated and supported by Microsoft and Red Hat. (Microsoft Learn)


1. What is Azure Red Hat OpenShift?

Azure Red Hat OpenShift (ARO) is Microsoft's managed Red Hat OpenShift service running on Azure.

In simple terms:

.NET Application
       ↓
Docker Container
       ↓
OpenShift
       ↓
Azure Red Hat OpenShift
       ↓
Microsoft Azure

OpenShift extends Kubernetes with additional enterprise capabilities and developer/operator tooling. ARO gives you those OpenShift capabilities without requiring your team to manually operate the underlying OpenShift control plane and infrastructure. Microsoft and Red Hat jointly engineer, operate, and support the service. (Microsoft Learn)

ARO clusters are deployed into your Azure subscription, while Microsoft and Red Hat handle major platform-management responsibilities such as patching and monitoring of the managed cluster components. (Microsoft Learn)


2. Why do we need OpenShift?

Imagine an organization has 50 microservices:

                    API Gateway
                        |
        +---------------+---------------+
        |               |               |
   Order Service   Payment Service   Customer Service
        |               |               |
      SQL DB          SQL DB          Redis
        |
   Notification
      Service

Each service may have:

  • Different deployments

  • Different versions

  • Different resource requirements

  • Multiple replicas

  • Health checks

  • Networking requirements

  • Secrets

  • Configuration

  • Logging

  • Monitoring

  • Autoscaling

Managing all of this manually becomes difficult.

A container orchestration platform can manage these workloads.

OpenShift provides Kubernetes-based orchestration plus additional platform capabilities. ARO packages this as a managed Azure service. (Microsoft Learn)


3. Is Azure OpenShift mandatory for .NET Core?

❌ No.

This is one of the most important points.

A .NET application can run on:

IIS
Azure App Service
Azure Container Apps
Azure Kubernetes Service
Azure Red Hat OpenShift
Windows Services
Linux
Docker
Virtual Machines
On-premises servers

For example:

ASP.NET Core Web API
       |
       +----> IIS
       |
       +----> Azure App Service
       |
       +----> Docker
       |
       +----> AKS
       |
       +----> ARO

So .NET does not require OpenShift.

The decision depends on your organization's architecture, operational requirements, existing platform standards, compliance requirements, and team expertise.


4. Why would an enterprise choose ARO?

ARO becomes particularly interesting when an organization wants:

1. Kubernetes

OpenShift is built on Kubernetes.

2. Enterprise OpenShift platform

Organizations that already standardize on Red Hat OpenShift can use ARO while keeping their workloads on Azure.

3. Managed platform

Microsoft and Red Hat manage important parts of the platform, reducing the amount of cluster administration required from application teams. (Microsoft Learn)

4. Containerized microservices

.NET applications can be packaged as containers and deployed as independent workloads.

5. Scaling

Multiple replicas of a service can run simultaneously.

6. Security and identity

ARO supports integration with Microsoft Entra ID and Kubernetes RBAC. (Microsoft Learn)

7. CI/CD

It can be integrated with enterprise CI/CD pipelines.

8. Hybrid-cloud strategy

OpenShift can be useful for organizations that want consistency between OpenShift environments across different infrastructure.


5. ARO Architecture

A simplified architecture looks like this:

                   Internet
                      |
                      ↓
                Azure Front Door
                      |
                      ↓
             Application Gateway
                      |
                      ↓
             Azure Red Hat OpenShift
              ┌───────────────────┐
              │    OpenShift      │
              │     Cluster       │
              │                   │
              │  ┌─────────────┐  │
              │  │   Router    │  │
              │  └──────┬──────┘  │
              │         │         │
              │  ┌──────┴──────┐  │
              │  │   Service   │  │
              │  └──────┬──────┘  │
              │         │         │
              │   ┌─────┴─────┐   │
              │   │   Pods    │   │
              │   │           │   │
              │   │ .NET API  │   │
              │   │ .NET API  │   │
              │   │ .NET API  │   │
              │   └───────────┘   │
              └───────────────────┘
                       |
                Azure SQL Database

ARO provides single-tenant, high-availability OpenShift clusters on Azure. (Microsoft Learn)


6. Important OpenShift Terminology

Before deploying .NET, understand these concepts.

Cluster

The complete OpenShift environment.

ARO Cluster
   |
   +-- Control Plane
   |
   +-- Worker Nodes
   |
   +-- Networking
   |
   +-- Storage
   |
   +-- Operators

Node

A node is a machine that runs workloads.

Worker Node
   |
   +-- Pod
   +-- Pod
   +-- Pod

Pod

A Pod is the basic Kubernetes/OpenShift unit in which containers run.

For a simple .NET API:

Pod
 |
 +-- .NET Container

If you have three replicas:

Pod 1 → .NET API
Pod 2 → .NET API
Pod 3 → .NET API

Deployment

Defines how your application should be deployed.

For example:

replicas: 3

means we want three instances.


Service

Provides stable networking to the Pods.

             Service
                |
       +--------+--------+
       |        |        |
      Pod      Pod      Pod

Route

OpenShift Route exposes an application outside the cluster.

Internet
   |
   ↓
OpenShift Route
   |
   ↓
Service
   |
   ↓
Pods

7. Real-Time .NET Microservices Example

Let's design an e-commerce application.

We have:

E-Commerce
    |
    +-- Product Service
    |
    +-- Order Service
    |
    +-- Payment Service
    |
    +-- Inventory Service
    |
    +-- Notification Service

Suppose the Order Service is built using:

ASP.NET Core Web API
.NET 10
C#
Entity Framework Core
SQL Server
Docker

We want:

                 Client
                   |
                   ↓
              OpenShift
                   |
             Order Service
                   |
        +----------+----------+
        |          |          |
        ↓          ↓          ↓
    Payment    Inventory   Notification

8. Create the .NET API

Create the project:

dotnet new webapi -n OrderService
cd OrderService

Example API:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();

app.Run();

Controller:

using Microsoft.AspNetCore.Mvc;

namespace OrderService.Controllers;

[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
    [HttpGet("{id}")]
    public IActionResult GetOrder(int id)
    {
        return Ok(new
        {
            OrderId = id,
            Product = "Laptop",
            Quantity = 2,
            Status = "Confirmed"
        });
    }
}

Now:

GET /api/orders/1001

returns:

{
  "orderId": 1001,
  "product": "Laptop",
  "quantity": 2,
  "status": "Confirmed"
}

9. Containerize the .NET Application

OpenShift runs containerized workloads, so we can create a Docker image for our API.

Example Dockerfile:

FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build

WORKDIR /src

COPY . .

RUN dotnet restore

RUN dotnet publish -c Release \
    -o /app/publish \
    --no-restore

FROM mcr.microsoft.com/dotnet/aspnet:10.0

WORKDIR /app

COPY --from=build /app/publish .

EXPOSE 8080

ENTRYPOINT ["dotnet", "OrderService.dll"]

The basic flow becomes:

C# Code
   ↓
dotnet publish
   ↓
Docker Image
   ↓
Container Registry
   ↓
OpenShift
   ↓
Pod

10. Build the Docker Image

docker build -t orderservice:1.0 .

Test locally:

docker run -p 8080:8080 orderservice:1.0

Then:

http://localhost:8080/api/orders/1001

11. Push Image to Container Registry

In an enterprise environment, you could use a container registry such as:

Azure Container Registry

Conceptually:

docker tag orderservice:1.0 \
    myregistry.azurecr.io/orderservice:1.0

docker push \
    myregistry.azurecr.io/orderservice:1.0

Now the image is available to OpenShift.


12. Deploy the .NET Application to OpenShift

A Kubernetes/OpenShift Deployment could look like this:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: order-service
spec:
  replicas: 3

  selector:
    matchLabels:
      app: order-service

  template:
    metadata:
      labels:
        app: order-service

    spec:
      containers:
        - name: order-service

          image: myregistry.azurecr.io/orderservice:1.0

          ports:
            - containerPort: 8080

          resources:
            requests:
              cpu: "250m"
              memory: "256Mi"

            limits:
              cpu: "500m"
              memory: "512Mi"

Notice:

replicas: 3

OpenShift will run three Pods.

             Order Service
                   |
       +-----------+-----------+
       |           |           |
       ↓           ↓           ↓
     Pod 1       Pod 2       Pod 3

If one Pod becomes unavailable, the platform can maintain the desired replica state.


13. Create an OpenShift Service

Create:

apiVersion: v1
kind: Service

metadata:
  name: order-service

spec:
  selector:
    app: order-service

  ports:
    - port: 80
      targetPort: 8080

Now:

Service
   |
   +---- Pod 1
   |
   +---- Pod 2
   |
   +---- Pod 3

The application doesn't need to know which Pod receives the request.


14. Expose the API using an OpenShift Route

Example:

apiVersion: route.openshift.io/v1
kind: Route

metadata:
  name: order-service

spec:
  to:
    kind: Service
    name: order-service

  port:
    targetPort: 8080

The resulting flow is:

Client
  |
  | HTTPS
  ↓
OpenShift Route
  |
  ↓
Service
  |
  +--------+--------+
  |        |        |
 Pod 1    Pod 2    Pod 3

15. Deploy Using oc

OpenShift provides the oc command-line client.

For example:

oc login <your-cluster>

Create/select a project:

oc new-project ecommerce

Deploy:

oc apply -f deployment.yaml

Service:

oc apply -f service.yaml

Route:

oc apply -f route.yaml

Check Pods:

oc get pods

Example:

NAME                             READY   STATUS
order-service-7c8d9f7c5d-abc12   1/1     Running
order-service-7c8d9f7c5d-def34   1/1     Running
order-service-7c8d9f7c5d-ghi56   1/1     Running

16. What Happens When Traffic Increases?

Suppose:

Normal traffic
   ↓
3 Pods

During a festival sale:

Traffic increases
       ↓
Autoscaling
       ↓
5 Pods
       ↓
10 Pods

Conceptually:

              Service
                 |
       +---------+---------+
       |         |         |
      Pod       Pod       Pod
       |         |         |
       +---------+---------+
                 |
            More traffic
                 ↓
          Additional Pods

This is one of the major advantages of container orchestration.


17. Health Checks

A production .NET application shouldn't simply be considered healthy because its process is running.

ASP.NET Core provides health-check support.

Example:

builder.Services.AddHealthChecks();

var app = builder.Build();

app.MapHealthChecks("/health");

app.MapControllers();

app.Run();

Now:

GET /health

can be used by the platform to determine application health.


18. Configure Kubernetes/OpenShift Probes

For example:

livenessProbe:
  httpGet:
    path: /health
    port: 8080

  initialDelaySeconds: 10
  periodSeconds: 10

readinessProbe:
  httpGet:
    path: /health
    port: 8080

  initialDelaySeconds: 5
  periodSeconds: 5

There are two important concepts:

Liveness

"Is my application alive?"

Readiness

"Can my application receive traffic?"

This distinction is extremely important in microservices.


19. Configuration Management

Don't hard-code:

var connectionString =
    "Server=production-server;Database=Orders...";

Instead use configuration:

var connectionString =
    builder.Configuration.GetConnectionString("OrdersDb");

Environment-specific values can then be supplied through OpenShift configuration mechanisms.

For example:

env:
  - name: ASPNETCORE_ENVIRONMENT
    value: Production

  - name: ConnectionStrings__OrdersDb
    valueFrom:
      secretKeyRef:
        name: orders-db-secret
        key: connection-string

20. Secrets

Never put passwords directly into:

Dockerfile
Git repository
deployment.yaml
source code

Instead use a Secret.

Example:

oc create secret generic orders-db-secret \
  --from-literal=connection-string="YOUR-CONNECTION-STRING"

Then the application can consume it through an environment variable.

For enterprise Azure environments, you can also integrate workloads with Azure identity capabilities rather than relying on long-lived credentials. ARO supports managed and workload identities. (Microsoft Learn)


21. Scaling a .NET Microservice

Suppose:

Order Service
Current replicas = 3

You can scale manually:

oc scale deployment/order-service --replicas=5

Now:

Order Service
     |
     +-- Pod 1
     +-- Pod 2
     +-- Pod 3
     +-- Pod 4
     +-- Pod 5

In production, autoscaling can be configured based on resource utilization and other supported metrics.


22. Rolling Deployment

Suppose version 1.0 is running:

Pod 1 → v1
Pod 2 → v1
Pod 3 → v1

You deploy:

v2

The platform can perform a rolling update rather than stopping every instance simultaneously.

Conceptually:

Pod 1 → v2
Pod 2 → v1
Pod 3 → v1

Pod 1 → v2
Pod 2 → v2
Pod 3 → v1

Pod 1 → v2
Pod 2 → v2
Pod 3 → v2

This helps reduce application downtime during deployments.


23. Real-Time E-Commerce Architecture

Now let's put everything together.

                         Customers
                             |
                             ↓
                    Azure Front Door
                             |
                             ↓
                    OpenShift Route
                             |
                             ↓
                      API Gateway
                             |
       +---------------------+---------------------+
       |                     |                     |
       ↓                     ↓                     ↓
 Order Service        Product Service       Customer Service
       |                     |                     |
       ↓                     ↓                     ↓
 Payment Service       Inventory Service      Redis
       |
       ↓
 Notification Service
       |
       ↓
 Azure Service Bus

Each microservice can have:

.NET API
   ↓
Docker Image
   ↓
Container Registry
   ↓
OpenShift Deployment
   ↓
Pods
   ↓
Service
   ↓
Route

24. How .NET and OpenShift Work Together

The relationship is important to understand:

.NET
 ↓
Application Framework

Docker
 ↓
Application Packaging

Kubernetes
 ↓
Container Orchestration

OpenShift
 ↓
Enterprise Kubernetes Platform

Azure Red Hat OpenShift
 ↓
Managed OpenShift on Azure

So ARO isn't replacing .NET.

It provides the platform on which your containerized .NET applications can run.


25. OpenShift vs AKS

This is a very common interview question.

FeatureAKSAzure Red Hat OpenShift
TechnologyKubernetesOpenShift/Kubernetes
Azure managed serviceYesYes
MicrosoftManaged serviceJointly operated with Red Hat
Red Hat ecosystemNot centralStrong
OpenShift toolingNoYes
Kubernetes workloadsYesYes
.NET supportYesYes
Enterprise OpenShift standardNoYes
Best fitAzure/Kubernetes environmentsOrganizations standardized on OpenShift

Microsoft explicitly describes ARO as an Azure-managed OpenShift service jointly engineered, operated, and supported by Microsoft and Red Hat. (Microsoft Learn)


26. OpenShift vs Azure App Service

These solve different problems.

Azure App Service

Best when:

I have a web application/API
        ↓
I want managed hosting
        ↓
I don't need Kubernetes

ARO

Better suited when:

I have many containerized services
        ↓
I need Kubernetes/OpenShift
        ↓
I need enterprise container orchestration

Don't introduce OpenShift simply because you are using .NET.


27. OpenShift vs Docker

Another common misunderstanding:

Docker and OpenShift are not competitors in the same sense.

Docker packages the application.

OpenShift orchestrates containerized workloads.

.NET Application
       ↓
Docker Image
       ↓
OpenShift
       ↓
Pods
       ↓
Services
       ↓
Routes

28. Why .NET Applications Work Well on OpenShift

Red Hat provides supported .NET container images and OpenShift guidance for .NET applications. For example, Red Hat's documentation describes dotnet SDK images and corresponding runtime/ASP.NET runtime image streams for OpenShift. (Red Hat Documentation)

That means an enterprise can standardize on:

.NET
+
Red Hat Enterprise Linux/UBI-based containers
+
OpenShift
+
Azure

For example:

.NET 10
   ↓
ASP.NET Core
   ↓
Red Hat UBI-based container
   ↓
OpenShift
   ↓
Azure Red Hat OpenShift

Red Hat's current documentation includes guidance for running .NET 10 on OpenShift and provides dotnet, dotnet-runtime, and dotnet-aspnet image streams. (Red Hat Documentation)


29. CI/CD Pipeline

A typical enterprise pipeline might look like:

Developer
    |
    ↓
Git Repository
    |
    ↓
CI Pipeline
    |
    +-- Build
    +-- Unit Tests
    +-- SonarQube
    +-- Security Scan
    +-- Docker Build
    |
    ↓
Container Registry
    |
    ↓
CD Pipeline
    |
    ↓
ARO
    |
    ↓
OpenShift Deployment
    |
    ↓
Pods

For example:

docker build -t orderservice:1.0 .
docker push myregistry.azurecr.io/orderservice:1.0

oc apply -f deployment.yaml

In a real enterprise pipeline, image tags would normally be immutable version/build identifiers rather than simply latest.


30. What Happens When a Pod Fails?

Suppose:

Order Service

Pod 1 → Running
Pod 2 → Running
Pod 3 → Failed

The desired state says:

replicas = 3

The orchestration layer can create another Pod:

Pod 1 → Running
Pod 2 → Running
Pod 3 → Failed
Pod 4 → Starting

Eventually:

Pod 1 → Running
Pod 2 → Running
Pod 4 → Running

The application therefore doesn't have to manually detect and recreate failed instances.


31. Production Architecture

A mature enterprise architecture could look like:

                    Internet
                       |
                       ↓
                Azure Front Door
                       |
                       ↓
              WAF / Load Balancing
                       |
                       ↓
              Azure Red Hat OpenShift
                       |
        +--------------+--------------+
        |              |              |
        ↓              ↓              ↓
   API Gateway      Services       Workers
        |              |              |
        |        +-----+-----+        |
        |        |     |     |        |
        ↓        ↓     ↓     ↓        ↓
     Orders   Payment Inventory Customer
        |
        ↓
  Azure Service Bus
        |
        ↓
 Notification Worker
        |
        ↓
 External Systems

Supporting services:

Azure SQL
Azure Cache for Redis
Azure Key Vault
Azure Container Registry
Application monitoring
Centralized logging
CI/CD

32. Is ARO Mandatory in Microservices?

Again:

❌ No.

Microservices can run on:

AKS
ARO
Azure Container Apps
Docker Compose
ECS
GKE
Self-managed Kubernetes
Virtual Machines
Other container platforms

The correct architecture decision is:

Business Requirements
        ↓
Non-functional Requirements
        ↓
Platform Requirements
        ↓
Choose Hosting Platform

Not:

.NET
 ↓
Must use ARO ❌

33. When Should You Choose ARO?

Choose ARO when your organization needs things such as:

Enterprise OpenShift standardization

Your company already uses OpenShift across environments.

Kubernetes + OpenShift ecosystem

You need OpenShift-specific platform capabilities and workflows.

Managed Azure deployment

You want OpenShift deployed into Azure while Microsoft and Red Hat handle important platform operations. (Microsoft Learn)

Large microservices platform

You have many containerized services and need centralized orchestration.

Hybrid-cloud consistency

You want an OpenShift-based application platform that can fit into broader hybrid-cloud strategies.

Enterprise security/governance

You need platform-level identity, RBAC, networking, policy, and operational controls.


34. When Should You NOT Choose ARO?

If you have:

One ASP.NET Core API

and your requirement is simply:

Host the API

ARO could be unnecessary complexity.

You might choose:

Azure App Service

instead.

Likewise, if your team already has strong Azure Kubernetes expertise and doesn't need OpenShift, AKS may be a more natural choice.


35. ARO Interview Question

Q: Is Azure Red Hat OpenShift mandatory for .NET Core?

Answer:

No. Azure Red Hat OpenShift is not mandatory for .NET Core applications. .NET applications can run on Azure App Service, Azure Container Apps, AKS, virtual machines, Docker, and other platforms. ARO is a managed OpenShift platform on Azure and is mainly selected when an organization needs enterprise OpenShift/Kubernetes capabilities, OpenShift standardization, hybrid-cloud consistency, or specific operational and governance requirements.

That's the answer I'd recommend giving in a .NET Architect interview.


36. The Most Important Concept

Remember this hierarchy:

             .NET
              │
              │ builds
              ↓
        ASP.NET Core API
              │
              │ packaged as
              ↓
          Docker Image
              │
              │ deployed to
              ↓
          OpenShift
              │
              │ hosted on
              ↓
       Azure Red Hat OpenShift
              │
              ↓
           Azure

ARO is the hosting/orchestration platform—not a requirement of the .NET framework.


37. Final Summary

Azure Red Hat OpenShift combines Azure + Red Hat OpenShift + Kubernetes-based container orchestration + managed platform operations. Microsoft says ARO provides fully managed OpenShift clusters, with Microsoft and Red Hat jointly engineering, operating, and supporting the service. (Microsoft Learn)

For a .NET microservices application:

.NET Microservice
       ↓
Docker Container
       ↓
Container Registry
       ↓
Azure Red Hat OpenShift
       ↓
OpenShift Deployment
       ↓
Pods
       ↓
Service
       ↓
Route
       ↓
Users

The key takeaway is:

Don't choose ARO because you use .NET. Choose ARO when your application's operational, architectural, enterprise, or organizational requirements justify an OpenShift platform.

Official references

Azure Red Hat OpenShift — Microsoft Learn

Azure Red Hat OpenShift documentation

.NET on OpenShift — Red Hat documentation

Create an Azure Red Hat OpenShift cluster

If you're publishing this as a blog, a strong title would be “Azure Red Hat OpenShift (ARO) with .NET 10: Complete Guide to Deploying ASP.NET Core Microservices with Real-Time E-Commerce Example”.

Worker Services in .NET — Complete Guide


1. What is a Worker Service?

A Worker Service is a .NET application designed to run continuously in the background.

Unlike an ASP.NET Core Web API:

Web API
   ↓
HTTP Request
   ↓
Controller
   ↓
Business Logic
   ↓
HTTP Response

A Worker Service generally works like:

Worker Service
      ↓
Background Process
      ↓
Read Message / Timer / Event
      ↓
Business Logic
      ↓
Database / External API
      ↓
Continue Processing

A Worker Service can run as:

  • Windows Service

  • Linux systemd service

  • Docker container

  • Kubernetes Pod

  • Azure Container Apps

  • Azure App Service background process in appropriate hosting models

  • VM-hosted process

  • Kubernetes CronJob for scheduled/batch work


2. Why do we need Worker Services?

Consider an e-commerce application.

A customer places an order:

Customer
   ↓
Order API
   ↓
Create Order
   ↓
Return response

But after creating the order, many things may need to happen:

Order Created
    │
    ├── Send Email
    ├── Generate Invoice
    ├── Update Inventory
    ├── Send Notification
    ├── Create Shipment
    └── Update Analytics

Doing all of these inside the API request can make the API slow.

Instead:

                 ┌───────────────┐
Customer ───────►│   Order API   │
                 └───────┬───────┘
                         │
                         │ OrderCreated
                         ▼
                 ┌───────────────┐
                 │ Message Queue │
                 └───────┬───────┘
                         │
          ┌──────────────┼──────────────┐
          ▼              ▼              ▼
   Email Worker    Inventory Worker  Invoice Worker

This is where Worker Services become extremely useful.


3. Worker Service vs BackgroundService

These two terms are related but not exactly the same.

Worker Service

A Worker Service is a .NET project/application template designed for long-running background workloads.

You can create one using:

dotnet new worker -n OrderProcessing.Worker

It normally contains:

OrderProcessing.Worker
│
├── Program.cs
├── Worker.cs
└── appsettings.json

BackgroundService

BackgroundService is a base class provided by .NET for implementing long-running background work.

For example:

public class Worker : BackgroundService
{
    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            Console.WriteLine("Worker is running...");

            await Task.Delay(
                TimeSpan.FromSeconds(5),
                stoppingToken);
        }
    }
}

So:

Worker Service
      │
      └── Hosting Model
             │
             └── BackgroundService
                    │
                    └── ExecuteAsync()

4. Basic Worker Service Architecture

A typical Worker Service looks like this:

┌─────────────────────────────────────┐
│         .NET Worker Service         │
│                                     │
│  Generic Host                       │
│       │                             │
│       ├── Dependency Injection      │
│       ├── Configuration             │
│       ├── Logging                   │
│       ├── Configuration             │
│       └── Hosted Services           │
│                  │                  │
│                  ▼                  │
│          BackgroundService          │
│                  │                  │
│                  ▼                  │
│           ExecuteAsync()            │
│                  │                  │
│                  ▼                  │
│          Business Processing        │
└─────────────────────────────────────┘

5. Creating a Worker Service

Create the project:

dotnet new worker -n OrderProcessing.Worker

Move into the project:

cd OrderProcessing.Worker

Run it:

dotnet run

The default template will create something similar to:

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;

    public Worker(ILogger<Worker> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation(
                "Worker running at: {time}",
                DateTimeOffset.Now);

            await Task.Delay(
                1000,
                stoppingToken);
        }
    }
}

6. Understanding ExecuteAsync()

This is the most important method.

protected override async Task ExecuteAsync(
    CancellationToken stoppingToken)

The Worker Service calls this method when the application starts.

For example:

Application Starts
       ↓
Host Starts
       ↓
Worker Starts
       ↓
ExecuteAsync()
       ↓
while loop
       ↓
Background processing

7. Why CancellationToken is important

Suppose your worker is running:

Worker
  ↓
Processing
  ↓
Processing
  ↓
Processing

Now Kubernetes sends a termination signal.

The worker should stop gracefully.

That's why we use:

CancellationToken stoppingToken

Example:

while (!stoppingToken.IsCancellationRequested)
{
    await ProcessOrderAsync(stoppingToken);
}

When cancellation occurs:

Kubernetes
     ↓
SIGTERM
     ↓
CancellationToken
     ↓
Worker stops

This is especially important in production microservices.


8. Real-Time Example — Order Processing Microservice

Let's build a realistic architecture.

Imagine an e-commerce system:

Customer
   ↓
Order API
   ↓
Azure Service Bus
   ↓
Order Processing Worker
   ↓
Order Database

The API doesn't need to process everything synchronously.


9. Step 1 — Order API

The API receives:

POST /api/orders

Request:

{
  "customerId": 1001,
  "productId": 5001,
  "quantity": 2
}

The API creates the order.

[ApiController]
[Route("api/orders")]
public class OrdersController : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> CreateOrder(
        CreateOrderRequest request)
    {
        var order = new Order
        {
            Id = Guid.NewGuid(),
            CustomerId = request.CustomerId,
            ProductId = request.ProductId,
            Quantity = request.Quantity,
            Status = "Pending"
        };

        // Save order

        // Publish OrderCreated event

        return Accepted(order);
    }
}

Notice:

return Accepted(order);

The API doesn't need to wait for the complete background processing.


10. Step 2 — Create an Event

Create:

public class OrderCreatedEvent
{
    public Guid OrderId { get; set; }

    public int CustomerId { get; set; }

    public int ProductId { get; set; }

    public int Quantity { get; set; }
}

The API publishes:

OrderCreatedEvent

to a message broker.

For example:

Azure Service Bus

Architecture:

Order API
    │
    │ OrderCreatedEvent
    ▼
Azure Service Bus
    │
    ▼
Order Processing Worker

11. Step 3 — Create Worker Service

Create:

dotnet new worker -n OrderProcessing.Worker

Install the Azure Service Bus package:

dotnet add package Azure.Messaging.ServiceBus

12. Configure Service Bus

appsettings.json:

{
  "ServiceBus": {
    "ConnectionString": "YOUR_CONNECTION_STRING",
    "QueueName": "orders"
  }
}

In production, don't put secrets directly into appsettings.json.

Use:

  • Azure Key Vault

  • Managed Identity

  • Environment variables

  • Kubernetes Secrets


13. Create Worker

public class OrderWorker : BackgroundService
{
    private readonly ILogger<OrderWorker> _logger;
    private readonly ServiceBusProcessor _processor;

    public OrderWorker(
        IConfiguration configuration,
        ILogger<OrderWorker> logger)
    {
        _logger = logger;

        var connectionString =
            configuration["ServiceBus:ConnectionString"];

        var queueName =
            configuration["ServiceBus:QueueName"];

        var client = new ServiceBusClient(connectionString);

        _processor = client.CreateProcessor(queueName);
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        _processor.ProcessMessageAsync += ProcessMessage;
        _processor.ProcessErrorAsync += ProcessError;

        await _processor.StartProcessingAsync(
            stoppingToken);

        try
        {
            await Task.Delay(
                Timeout.Infinite,
                stoppingToken);
        }
        catch (OperationCanceledException)
        {
            // Application shutting down
        }

        await _processor.StopProcessingAsync();
    }

    private async Task ProcessMessage(
        ProcessMessageEventArgs args)
    {
        var messageBody =
            args.Message.Body.ToString();

        _logger.LogInformation(
            "Received Order: {Message}",
            messageBody);

        // Process order

        await args.CompleteMessageAsync(args.Message);
    }

    private Task ProcessError(
        ProcessErrorEventArgs args)
    {
        _logger.LogError(
            args.Exception,
            "Error processing message");

        return Task.CompletedTask;
    }
}

14. Register Worker in Program.cs

var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddHostedService<OrderWorker>();

var host = builder.Build();

host.Run();

This is the key line:

builder.Services.AddHostedService<OrderWorker>();

It tells .NET:

Start this Worker when the application starts.


15. Complete Processing Flow

Now the entire flow becomes:

             CUSTOMER
                 │
                 ▼
          ┌──────────────┐
          │   Order API  │
          └──────┬───────┘
                 │
                 │ Save Order
                 ▼
          ┌──────────────┐
          │ Azure SQL DB │
          └──────────────┘
                 │
                 │ Publish Event
                 ▼
        ┌───────────────────┐
        │  Azure Service Bus│
        │      orders       │
        └─────────┬─────────┘
                  │
                  ▼
        ┌─────────────────────┐
        │ Order Worker Service│
        └──────────┬──────────┘
                   │
          ┌────────┼─────────┐
          ▼        ▼         ▼
       Inventory  Payment   Notification

This is a very common microservice architecture.


16. Worker Service with Dependency Injection

Don't put all business logic inside:

Worker.cs

Instead:

Worker
  │
  ▼
OrderProcessor
  │
  ├── OrderRepository
  ├── InventoryService
  ├── PaymentService
  └── NotificationService

Example:

public interface IOrderProcessor
{
    Task ProcessAsync(
        OrderCreatedEvent order,
        CancellationToken cancellationToken);
}

Implementation:

public class OrderProcessor : IOrderProcessor
{
    private readonly ILogger<OrderProcessor> _logger;

    public OrderProcessor(
        ILogger<OrderProcessor> logger)
    {
        _logger = logger;
    }

    public async Task ProcessAsync(
        OrderCreatedEvent order,
        CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Processing Order {OrderId}",
            order.OrderId);

        // Business logic

        await Task.CompletedTask;
    }
}

Register:

builder.Services.AddScoped<IOrderProcessor, OrderProcessor>();
builder.Services.AddHostedService<OrderWorker>();

17. Important Issue — Scoped Services

This is a very important interview question.

A Worker Service itself is generally effectively singleton-like because it lives for the lifetime of the host.

But services such as:

DbContext
Repository
UnitOfWork

are usually:

Scoped

You shouldn't inject a scoped DbContext directly into a long-lived singleton worker.

Instead use:

IServiceScopeFactory

Example:

public class OrderWorker : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;

    public OrderWorker(
        IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            using var scope =
                _scopeFactory.CreateScope();

            var processor =
                scope.ServiceProvider
                    .GetRequiredService<IOrderProcessor>();

            await processor.ProcessAsync(
                stoppingToken);

            await Task.Delay(
                TimeSpan.FromSeconds(10),
                stoppingToken);
        }
    }
}

This creates a new DI scope for each processing cycle.


18. Worker + Entity Framework Core

For example:

public class OrderProcessor : IOrderProcessor
{
    private readonly ApplicationDbContext _db;

    public OrderProcessor(ApplicationDbContext db)
    {
        _db = db;
    }

    public async Task ProcessAsync(
        CancellationToken cancellationToken)
    {
        var orders = await _db.Orders
            .Where(x => x.Status == "Pending")
            .ToListAsync(cancellationToken);

        foreach (var order in orders)
        {
            order.Status = "Processed";
        }

        await _db.SaveChangesAsync(
            cancellationToken);
    }
}

Register:

builder.Services.AddDbContext<ApplicationDbContext>(
    options =>
        options.UseSqlServer(
            builder.Configuration.GetConnectionString(
                "DefaultConnection")));

19. Worker Service for Scheduled Processing

Workers aren't limited to queues.

You can also execute tasks periodically.

Example:

public class ReportWorker : BackgroundService
{
    private readonly ILogger<ReportWorker> _logger;

    public ReportWorker(
        ILogger<ReportWorker> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        using var timer = new PeriodicTimer(
            TimeSpan.FromMinutes(5));

        while (await timer.WaitForNextTickAsync(
            stoppingToken))
        {
            await GenerateReportAsync(
                stoppingToken);
        }
    }

    private async Task GenerateReportAsync(
        CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Generating report at {Time}",
            DateTimeOffset.Now);

        await Task.CompletedTask;
    }
}

20. Worker Service for File Processing

Another real-world example:

Customer uploads CSV
       ↓
Blob Storage
       ↓
Queue
       ↓
Worker
       ↓
Read CSV
       ↓
Validate records
       ↓
Insert database
       ↓
Move file to Processed

This is excellent for Worker Services because processing can take several minutes.


21. Worker Service for Email Processing

Architecture:

Application
     │
     ▼
Email Queue
     │
     ▼
Email Worker
     │
     ├── Read message
     ├── Validate
     ├── Send email
     └── Complete message

This prevents email processing from slowing down the main API.


22. Worker Service in Microservices

Suppose your system contains:

Order Service
Payment Service
Inventory Service
Notification Service
Shipping Service

You can have:

Order API
     │
     ▼
Order Worker

Payment Worker

Inventory Worker

Notification Worker

Shipping Worker

Each worker can be independently deployed and scaled.

This follows an important microservice principle:

A microservice should own a specific business capability.


23. Scaling Workers

Suppose there are:

100 messages/hour

One worker might be enough.

But suppose:

100,000 messages/hour

You can run:

             Queue
               │
       ┌───────┼───────┐
       ▼       ▼       ▼
    Worker 1 Worker 2 Worker 3

In Kubernetes:

Deployment
     │
     ├── Pod 1
     ├── Pod 2
     ├── Pod 3
     └── Pod 4

Multiple workers consume messages from the same queue.

The broker distributes messages between consumers.


24. Worker Service + Kubernetes

A Worker can run as a container.

Dockerfile:

FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base
WORKDIR /app

FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src

COPY . .

RUN dotnet restore

RUN dotnet publish \
    -c Release \
    -o /app/publish

FROM base AS final

WORKDIR /app

COPY --from=build /app/publish .

ENTRYPOINT ["dotnet", "OrderProcessing.Worker.dll"]

Then:

Docker Image
      ↓
Azure Container Registry
      ↓
AKS
      ↓
Worker Pod

25. Worker Deployment in Kubernetes

Example:

apiVersion: apps/v1
kind: Deployment

metadata:
  name: order-worker

spec:
  replicas: 3

  selector:
    matchLabels:
      app: order-worker

  template:
    metadata:
      labels:
        app: order-worker

    spec:
      containers:
        - name: order-worker

          image: myregistry/order-worker:1.0

          resources:
            requests:
              cpu: "100m"
              memory: "128Mi"

            limits:
              cpu: "500m"
              memory: "512Mi"

Now Kubernetes runs:

Order Worker
   │
   ├── Pod 1
   ├── Pod 2
   └── Pod 3

26. Worker Service Failure Handling

Production workers must handle failures.

For example:

Worker
   ↓
Process Order
   ↓
Payment API
   ↓
FAILED

Don't simply crash the entire application.

Use:

Retry
 ↓
Retry
 ↓
Retry
 ↓
Still Failed
 ↓
Dead Letter Queue

For example:

Orders Queue
     │
     ▼
Worker
     │
     ├── Success → Complete
     │
     └── Failure
           │
           ▼
       Retry
           │
           ▼
      Max Retries
           │
           ▼
    Dead Letter Queue

27. Idempotency — Extremely Important

Imagine the worker receives:

OrderId = 1001

It processes it.

But before acknowledgement:

Worker crashes

The message may be delivered again.

Now:

Order 1001
     ↓
Processed
     ↓
Worker crashes
     ↓
Message delivered again
     ↓
Order 1001 processed again

Therefore your worker should be idempotent.

For example:

var alreadyProcessed =
    await _db.ProcessedMessages
        .AnyAsync(
            x => x.MessageId == messageId,
            cancellationToken);

if (alreadyProcessed)
{
    return;
}

Then:

Message
  ↓
Check MessageId
  ↓
Already processed?
  │
  ├── Yes → Skip
  │
  └── No → Process

This is extremely important in distributed systems.


28. Worker + Saga Pattern

Workers are also commonly used with Saga-based microservices.

Example:

Order Created
     ↓
Order Worker
     ↓
Payment
     ↓
Inventory
     ↓
Shipping

If inventory fails:

Order
  ↓
Payment SUCCESS
  ↓
Inventory FAILED
  ↓
Compensation
  ↓
Refund Payment
  ↓
Cancel Order

Workers can process these asynchronous commands/events.


29. Worker Service vs API

FeatureWeb APIWorker Service
HTTP endpointYesNo
Long-running processNot idealExcellent
Queue consumerPossibleExcellent
Scheduled jobsPossibleExcellent
Background processingLimitedExcellent
Request/responseYesNo
KubernetesYesYes
DockerYesYes
MicroservicesYesYes

30. Alternatives to Worker Services

Worker Services are not the only solution.

Depending on your requirement, you can use several alternatives.

1. Hangfire

Excellent for:

Background Jobs
Scheduled Jobs
Retries
Recurring Jobs
Dashboard

Architecture:

API
 ↓
Hangfire
 ↓
Background Job
 ↓
Database

Good when you need:

Run every day at 2 AM

or:

Run this job in background

31. Quartz.NET

Quartz.NET is useful for sophisticated scheduling.

Example:

Daily
Hourly
Weekly
Cron
Complex schedules

Architecture:

Application
     ↓
Quartz Scheduler
     ↓
Job
     ↓
Business Logic

Good for complex scheduling requirements.


32. Azure Functions

If you're already using Azure, Azure Functions can be an excellent alternative.

For example:

Service Bus
    ↓
Azure Function
    ↓
Process Order

Or:

Timer
 ↓
Azure Function
 ↓
Generate Report

Advantages:

  • Serverless

  • Automatic scaling

  • Event-driven

  • Less infrastructure management


33. Azure Service Bus Trigger

A common architecture:

Order API
     ↓
Azure Service Bus
     ↓
Azure Function
     ↓
Process Order

Instead of maintaining a continuously running Worker Service, Azure manages the execution environment.


34. Kubernetes CronJob

For batch jobs that run at a specific time:

Every night 2 AM
       ↓
Kubernetes CronJob
       ↓
Create Pod
       ↓
Execute job
       ↓
Pod completes

This is better than keeping a Worker continuously running for a job that only needs to execute once per day.


35. Azure Logic Apps

For workflow/integration scenarios:

Trigger
  ↓
Logic App
  ↓
Service A
  ↓
Service B
  ↓
Email

Useful for integration workflows rather than complex application business logic.


36. Azure Data Factory

For data movement/ETL:

SQL Server
     ↓
Azure Data Factory
     ↓
Transform
     ↓
Azure SQL

If your requirement is:

ETL
Data migration
Data integration
Scheduled data processing

ADF may be better than a Worker.


37. Azure WebJobs

For applications already hosted in Azure App Service, WebJobs can be useful for background execution.

Architecture:

Azure App Service
       │
       ├── Web API
       │
       └── WebJob

38. Which One Should You Choose?

A simple decision matrix:

RequirementRecommended
Long-running background processWorker Service
Queue consumerWorker Service / Azure Functions
Complex scheduled jobsQuartz.NET
Simple background jobsHangfire
Serverless event processingAzure Functions
Kubernetes scheduled batchCronJob
ETL/Data movementAzure Data Factory
Azure App Service background taskWebJobs
Complex integration workflowLogic Apps

39. Worker Service vs Azure Function

This is a common interview question.

Worker Service

You manage:
    Application
    Container/VM
    Deployment
    Scaling

Azure Function

Azure manages:
    Infrastructure
    Scaling
    Runtime

Worker:

Queue
 ↓
Worker
 ↓
Process

Function:

Queue
 ↓
Azure Function Trigger
 ↓
Process

40. Worker Service vs Hangfire

Worker Service

Better for:

Continuous processing
Queue consumers
Long-running workloads
Microservice background processes

Hangfire

Better for:

Scheduled jobs
Fire-and-forget jobs
Recurring jobs
Retry management
Job dashboard

41. Worker Service vs Kubernetes CronJob

Use Worker:

Continuous
 ↓
Consume messages
 ↓
Process continuously

Use CronJob:

2 AM
 ↓
Start
 ↓
Process
 ↓
Exit

For example:

Order queue consumer:

Worker Service

Daily database cleanup:

Kubernetes CronJob

42. Recommended Microservice Architecture

For a production e-commerce system, I'd typically consider:

                     ┌──────────────┐
                     │   Angular UI │
                     └──────┬───────┘
                            │
                            ▼
                    ┌───────────────┐
                    │ API Management│
                    └───────┬───────┘
                            │
            ┌───────────────┼────────────────┐
            ▼               ▼                ▼
       Order API       Payment API      Customer API
            │
            ▼
      Azure Service Bus
            │
     ┌──────┼─────────────┐
     ▼      ▼             ▼
 Order    Inventory    Notification
 Worker     Worker        Worker
     │        │             │
     ▼        ▼             ▼
 Azure     Azure          Email/
 SQL       SQL            SMS

And deploy using:

.NET Worker
     ↓
Docker
     ↓
Azure Container Registry
     ↓
AKS
     ↓
Pods
     ↓
Horizontal Scaling

43. Production Best Practices

When implementing Worker Services, remember these:

1. Use CancellationToken

await ProcessAsync(cancellationToken);

2. Use structured logging

_logger.LogInformation(
    "Processing Order {OrderId}",
    orderId);

3. Don't inject scoped dependencies directly

Use:

IServiceScopeFactory

4. Make processing idempotent

Prevent duplicate processing.

5. Implement retry

Transient failures should be retried.

6. Use Dead Letter Queue

Don't retry permanently bad messages forever.

7. Configure health monitoring

Monitor:

Worker status
Message count
Processing latency
Failure count
Retry count
DLQ count

8. Use distributed tracing

For microservices:

API
 ↓
Service Bus
 ↓
Worker
 ↓
Database

You should be able to trace the complete transaction/correlation flow.


44. Most Important Concept

The biggest idea to remember is:

Worker Services are not simply "another type of API." They are long-running background processes designed to execute work independently of incoming HTTP requests.

In microservices, they are particularly valuable for:

          EVENT
            │
            ▼
      Message Broker
            │
            ▼
     Worker Service
            │
     ┌──────┼──────┐
     ▼      ▼      ▼
    DB     API    Events

This allows your APIs to remain:

Fast
Stateless
Scalable
Responsive

while the Worker handles:

Long-running
Asynchronous
Retryable
Queue-based
Scheduled
Background

processing.

Recommended architecture for your .NET/Azure stack

Given a typical .NET + Microservices + Azure + Docker + AKS architecture, a strong production combination is:

                    CLIENT
                      │
                      ▼
                 API Management
                      │
                      ▼
                 .NET Web API
                      │
               Publish Event
                      │
                      ▼
              Azure Service Bus
                      │
          ┌───────────┼───────────┐
          ▼           ▼           ▼
     .NET Worker  .NET Worker  .NET Worker
       Order       Inventory    Notification
          │           │           │
          ▼           ▼           ▼
       Azure SQL   Azure SQL    External API

with:

Docker
  ↓
Azure Container Registry
  ↓
AKS
  ↓
Worker Pods
  ↓
Horizontal Scaling

That gives you a clean event-driven microservice architecture with independent scaling and asynchronous processing.

Don't Copy

Protected by Copyscape Online Plagiarism Checker