Meet The Author

I'm Ethan Jackson, An 25 years old blogger Currently living in London, United Kingdom. I'm a Skilled Blogger, Part Time web Developer And Creating new things as a web Designer.

author

ASP.NET Core Web API Idempotency Key Implementation

Leave a Comment

Duplicate HTTP requests are a common occurrence for modern online applications. An API gateway could resubmit a request if it did not obtain a response in time, a user might click the Submit button again, or a mobile application might try again following a network timeout.

Duplicate requests can cause major issues for processes like order creation, payment processing, ticket booking, and money transfers. It is possible for two orders to be made, inventory to be deducted more than once, or the same payment to be completed twice.

 

One way to prevent these problems is to implement idempotency keys in an ASP.NET Core Web API.

An idempotency key is a unique value sent by a client with a request. The server uses that value to identify repeated attempts to perform the same logical operation. When the same request arrives again with the same key, the API can return the previously stored result instead of executing the operation again.

This approach is especially useful for POST and PATCH endpoints that perform operations with side effects. It also works well with mobile applications, payment integrations, distributed systems, and APIs that use retry policies.

This article explains how idempotency keys work, how to implement them in ASP.NET Core, how to store request and response information, and how to handle concurrent requests safely in production.

What Is an Idempotency Key?

An idempotency key is a client-generated identifier that represents one logical operation.

For example, suppose a mobile application sends a payment request to an ASP.NET Core API. The server processes the payment, but the network connection fails before the response reaches the application.

The client cannot determine whether the payment succeeded. It may send the request again.

Without idempotency protection, the server may process the payment a second time. With an idempotency key, the client sends the same key with both attempts. The server recognizes the repeated operation and returns the result recorded for the original request.

A typical HTTP request looks like this:

POST /api/payments HTTP/1.1
Content-Type: application/json
Idempotency-Key: 8f4c2d10-6b12-4e92-a61c-1e6f20a53d89

{
  "customerId": 1025,
  "amount": 2500,
  "currency": "INR"
}

The client must reuse this key when retrying the same logical payment.

The key should not be generated again for every HTTP attempt. If the client creates a new key for each retry, the server will treat every request as a new operation.

Idempotency and HTTP methods

HTTP defines idempotency as a property of an operation: performing the same request multiple times has the same intended effect as performing it once.

HTTP method

Naturally idempotent?

Typical behavior

GET

Yes

Reads a resource without changing its state

HEAD

Yes

Returns response headers without changing state

PUT

Yes, when implemented correctly

Replaces a resource with the supplied representation

DELETE

Yes, in intended effect

Removes a resource; repeated deletion does not remove additional resources

POST

Not necessarily

Often creates a new resource or triggers an operation

PATCH

Not necessarily

Depends on the requested modification

For example, setting an order's status to Shipped can be idempotent if repeating the operation does not create additional effects. Incrementing a counter by one is not idempotent because repeating the request changes the value again.

An idempotency key is particularly useful when an operation is not naturally idempotent but clients still need safe retry behavior.

How Idempotency Keys Work

A typical idempotency implementation maintains a persistent record for each logical request.

The record usually contains:

  • Idempotency key.

  • Client or tenant identifier.

  • Request fingerprint.

  • Processing status.

  • HTTP response status code.

  • Response body.

  • Relevant response headers.

  • Creation and expiration timestamps.

The request fingerprint helps the server determine whether the same key is being reused with a different request.

Request processing flow

The general workflow looks like this:

  1. The client generates an idempotency key before starting an operation.

  2. The client sends the key in the Idempotency-Key header.

  3. The API validates the key and identifies the authenticated caller.

  4. The server checks whether a record already exists for that caller and key.

  5. If no record exists, the server attempts to claim the key atomically.

  6. The server validates and executes the operation.

  7. The server stores the result and marks the operation as completed.

  8. If the same request arrives again, the server returns the stored result instead of executing the operation again.

The key must be claimed atomically. Otherwise, two requests arriving at almost the same time can both check the database, find no existing record, and execute the same operation.

Different request scenarios

Scenario

Recommended behavior

New key and valid request

Execute the operation and store its result

Same key and same completed request

Replay the stored response

Same key and different request body

Reject the request with a conflict response

Same key while the first request is processing

Return a documented in-progress response or wait for completion

Request fails before the operation is committed

Allow a safe retry according to the failure policy

Stored result has expired

Treat the key according to the documented retention policy

The exact HTTP status codes can vary by API contract. The important requirement is that clients can distinguish a successful replay, a conflicting request, and an operation that is still in progress.

Design the Idempotency Storage

A reliable implementation needs persistent storage. An in-memory dictionary can demonstrate the concept, but it is not sufficient for a production API running across multiple application instances.

For example, if an API runs on three servers behind a load balancer, each server has its own memory. A retry might reach a different server that has no knowledge of the original request.

A shared database or distributed store is therefore required.

Create an idempotency table

The following SQL Server table stores the information needed to identify and replay a request.

CREATE TABLE dbo.IdempotencyRecords
(
    Id BIGINT IDENTITY(1,1) PRIMARY KEY,

    ClientId NVARCHAR(100) NOT NULL,
    IdempotencyKey NVARCHAR(128) NOT NULL,

    RequestHash VARBINARY(32) NOT NULL,

    Status NVARCHAR(20) NOT NULL,

    ResponseStatusCode INT NULL,
    ResponseBody NVARCHAR(MAX) NULL,

    CreatedAtUtc DATETIME2 NOT NULL
        DEFAULT SYSUTCDATETIME(),

    ExpiresAtUtc DATETIME2 NOT NULL,

    CONSTRAINT UQ_Idempotency_Client_Key
        UNIQUE (ClientId, IdempotencyKey)
);

The unique constraint is particularly important. It ensures that one client cannot create multiple records for the same key, even when requests arrive concurrently at different application instances.

The ClientId column identifies the authenticated API consumer, tenant, or user. This prevents two unrelated clients from accidentally sharing the same idempotency-key namespace.

The RequestHash column stores a SHA-256 fingerprint of the request. The Status column can contain values such as Processing and Completed.

For a production implementation, consider storing response headers as well as the response body. If the API returns a Location header or another important response header, a replay should preserve the relevant parts of the original response.

The response body may contain sensitive information. Apply appropriate database permissions, encryption, retention, and access policies.

Generate a request fingerprint

A key should identify one logical request, not become a way to replay an unrelated response.

For example, the following two requests must not be treated as equivalent:

{
  "customerId": 1025,
  "amount": 2500,
  "currency": "INR"
}
{
  "customerId": 1025,
  "amount": 5000,
  "currency": "INR"
}

If both requests use the same key, the API should reject the second request rather than return the first payment's result.

A simple fingerprint can be generated using SHA-256:

using System.Security.Cryptography;
using System.Text;

public static class RequestFingerprint
{
    public static byte[] Create(string requestBody)
    {
        var bytes = Encoding.UTF8.GetBytes(requestBody);

        return SHA256.HashData(bytes);
    }
}

This example hashes the raw request body. A production implementation should also consider the HTTP method, route, relevant query parameters, content type, and authenticated caller scope.

If JSON property ordering or insignificant formatting can vary between retries, raw-body hashing may treat semantically equivalent JSON as different requests. One solution is to serialize a validated request model into a consistent representation before hashing.

Do not include volatile values such as trace IDs, timestamps generated separately for every attempt, or authentication tokens in the fingerprint.

Implement Idempotency Key Validation

Before checking storage, validate the incoming key.

The API should reject missing, empty, or excessively long keys when the endpoint requires idempotency protection.

A simple helper can read the header:

public static class IdempotencyKeyValidator
{
    public static bool TryGetKey(
        HttpRequest request,
        out string key)
    {
        key = string.Empty;

        if (!request.Headers.TryGetValue(
            "Idempotency-Key",
            out var values))
        {
            return false;
        }

        if (values.Count != 1)
        {
            return false;
        }

        var value = values[0];

        if (string.IsNullOrWhiteSpace(value))
        {
            return false;
        }

        if (value.Length > 128)
        {
            return false;
        }

        key = value.Trim();

        return true;
    }
}

This validates the presence and basic format of the header. A production API should also define which characters it accepts and document the maximum key length.

Do not trust the key as an authentication mechanism. The key identifies an operation; authentication and authorization must still be performed for every request.

Implement an Idempotency Service

The application should keep idempotency storage operations separate from the controller or endpoint logic.

A useful design is to introduce an interface that manages the lifecycle of a request:

public interface IIdempotencyService
{
    Task<IdempotencyResult> BeginAsync(
        string clientId,
        string key,
        byte[] requestHash,
        CancellationToken cancellationToken);

    Task CompleteAsync(
        string clientId,
        string key,
        int statusCode,
        string responseBody,
        CancellationToken cancellationToken);
}

The result can describe whether the request is new, already completed, currently processing, or using a different payload.

public enum IdempotencyState
{
    New,
    Completed,
    Processing,
    Conflict
}

public sealed record IdempotencyResult(
    IdempotencyState State,
    int? StatusCode = null,
    string? ResponseBody = null);

The storage implementation should use the database's unique constraint to claim a key atomically.

The important operation is not simply checking whether a record exists. It is attempting to insert a new Processing record and allowing the unique constraint to decide which concurrent request wins.

A simplified SQL Server claim operation is:

INSERT INTO dbo.IdempotencyRecords
(
    ClientId,
    IdempotencyKey,
    RequestHash,
    Status,
    ExpiresAtUtc
)
VALUES
(
    @ClientId,
    @IdempotencyKey,
    @RequestHash,
    'Processing',
    DATEADD(HOUR, 24, SYSUTCDATETIME())
);

If another request has already inserted the same client and key combination, SQL Server rejects the insert because of the unique constraint.

The application can then read the existing record and compare its fingerprint and status.

Handle only the expected duplicate-key errors, such as SQL Server error numbers 2601 and 2627, as a concurrent claim. Other database errors must be treated as actual failures rather than silently interpreted as duplicates.

The claim and completion operations should also use appropriate ownership or state checks. A request that did not acquire the key must never be allowed to overwrite the result created by the request that owns it.

Handle Duplicate and Concurrent Requests

After attempting to claim a key, the API needs to decide what to do with the result.

A completed request with the same fingerprint should return the stored response. A different fingerprint should be rejected. A request that is still processing requires an explicit policy.

For example, an API might use the following responses:

Condition

Example response

First successful request

201 Created

Same key and same completed request

Replay original 201 Created response

Same key with a different payload

409 Conflict

Same key while the original request is processing

409 Conflict with a retry instruction

Missing required key

400 Bad Request

Some APIs choose to wait for the original request to finish instead of returning a conflict. That approach requires bounded waiting, cancellation handling, and a way to observe completion safely.

Returning 409 Conflict for an in-progress request is often simpler. The client can retry after a short delay using the same key.

The response contract should be documented so that mobile applications and other API consumers know how to handle each condition.

Build a Minimal API Endpoint

The following example illustrates how an ASP.NET Core Minimal API can use an idempotency service.

The storage implementation is injected rather than placing database logic directly inside the endpoint.

app.MapPost(
    "/api/payments",
    async (
        HttpContext context,
        PaymentRequest payment,
        IIdempotencyService idempotency,
        IPaymentService paymentService,
        CancellationToken cancellationToken) =>
    {
        if (!IdempotencyKeyValidator.TryGetKey(
            context.Request,
            out var key))
        {
            return Results.BadRequest(
                "A valid Idempotency-Key header is required.");
        }

        var clientId =
            context.User.FindFirst("client_id")?.Value;

        if (string.IsNullOrWhiteSpace(clientId))
        {
            return Results.Unauthorized();
        }

        var requestJson =
            System.Text.Json.JsonSerializer.Serialize(payment);

        var requestHash =
            RequestFingerprint.Create(requestJson);

        var result = await idempotency.BeginAsync(
            clientId,
            key,
            requestHash,
            cancellationToken);

        if (result.State == IdempotencyState.Conflict)
        {
            return Results.Conflict(
                "The idempotency key was used with a different request.");
        }

        if (result.State == IdempotencyState.Processing)
        {
            return Results.Conflict(
                "The original request is still being processed.");
        }

        if (result.State == IdempotencyState.Completed)
        {
            context.Response.Headers["Idempotency-Replayed"] =
                "true";

            return Results.Content(
                result.ResponseBody ?? string.Empty,
                "application/json",
                statusCode: result.StatusCode ?? 200);
        }

        var paymentResult =
            await paymentService.ProcessAsync(
                payment,
                key,
                cancellationToken);

        var responseBody =
            System.Text.Json.JsonSerializer.Serialize(
                paymentResult);

        await idempotency.CompleteAsync(
            clientId,
            key,
            StatusCodes.Status201Created,
            responseBody,
            cancellationToken);

        return Results.Content(
            responseBody,
            "application/json",
            statusCode: StatusCodes.Status201Created);
    });

This endpoint demonstrates the main integration points: validate the key, identify the caller, calculate a fingerprint, claim the operation, replay a completed result, and execute a new operation.

It is an architectural example, not a complete production implementation. The service must implement atomic claiming, ownership checks, expiration, response persistence, and failure recovery. The endpoint should also preserve relevant response headers, such as Location, when storing and replaying the response.

The payment service receives the same key so it can use the key when calling an external payment provider that supports idempotency.

Handle Failures Between Processing and Response Storage

A common implementation mistake is to assume that storing a Processing record and later updating it to Completed is enough to guarantee exactly-once execution.

Consider this sequence:

  1. The API claims the idempotency key.

  2. The payment provider successfully processes the payment.

  3. The API process crashes before saving the response.

  4. The client retries the same request.

  5. The database still contains a Processing record.

The API cannot safely assume that the payment failed. Re-executing the operation might create a duplicate payment.

This is a distributed systems problem: the database and external payment provider do not share one atomic transaction.

There are several ways to address it.

Use downstream idempotency support

If the payment provider supports idempotency keys, forward a stable key to the provider.

The same logical payment should use the same downstream key on every retry. This allows the provider to recognize repeated requests even when the application cannot determine whether an earlier attempt succeeded.

Do not assume every external API supports this feature. Review the provider's documentation and key-retention rules.

Use a database transaction for local operations

When the business operation and idempotency record are stored in the same database, a database transaction can help make the changes atomic.

For example, creating an order and marking its idempotency record as completed can be committed together.

If the transaction rolls back, neither change is committed.

This is different from calling an external payment provider, because a database transaction cannot automatically roll back an operation already completed by another service.

Use an outbox or reconciliation workflow

For operations involving multiple systems, consider the transactional outbox pattern.

The application commits the business operation and an outbox message in the same database transaction. A background worker publishes the message to the external system.

The consumer should also handle duplicate messages safely.

For payment operations, reconciliation may be required when the external provider's result is uncertain. A durable operation state machine is often more reliable than simply expiring a Processing record and allowing another request to execute.

Store and Expire Idempotency Records

Idempotency records should not remain in the database forever. A retention policy controls how long the API remembers completed operations.

For example, a payment API may retain keys for 24 hours or longer, depending on the provider contract and business requirements.

The correct duration depends on how long clients may retry, how long requests can remain in progress, and the consequences of processing the same logical operation again.

A SQL Server cleanup operation might look like this:

DELETE TOP (1000)
FROM dbo.IdempotencyRecords
WHERE Status = 'Completed'
  AND ExpiresAtUtc < SYSUTCDATETIME();

Run cleanup periodically through a background service or scheduled job. Use batches so a large cleanup operation does not create unnecessary database pressure.

Do not delete an active Processing record merely because its original expiration time has passed. First determine whether the operation is still running, completed externally, or needs reconciliation.

The API must also define what happens after a key expires. Once the record is deleted, a request using that key may be treated as new. Therefore, clients should not assume that an idempotency key protects an operation indefinitely.

Secure Idempotency Key Storage

Idempotency keys are not authentication credentials, but they still need careful handling.

A few security practices are important:

  • Scope keys to an authenticated user, tenant, or API client.

  • Do not use a globally shared key namespace for unrelated callers.

  • Validate key length and accepted characters.

  • Avoid logging full request bodies or sensitive payment details.

  • Restrict access to stored response data.

  • Consider storing a hash of the client-provided key rather than the raw value.

  • Use TLS for all API requests.

  • Apply retention and cleanup policies to stored records.

The scope should represent the caller that owns the logical operation. For example, a multi-tenant API should normally keep each tenant's keys separate.

Authorization must still run before replaying a stored response. A caller should not receive a previous response simply because they know another user's idempotency key.

Test Idempotency in ASP.NET Core

Idempotency should be tested under normal, repeated, and concurrent request conditions.

A basic test should send the same request twice using the same key and verify that the business operation executes only once.

For example, an integration test can use HttpClient:

[Fact]
public async Task RepeatedRequest_ReturnsSameResult()
{
    var key = Guid.NewGuid().ToString();

    var firstRequest = new HttpRequestMessage(
        HttpMethod.Post,
        "/api/payments");

    firstRequest.Headers.Add(
        "Idempotency-Key",
        key);

    firstRequest.Content = JsonContent.Create(
        new PaymentRequest(1025, 2500, "INR"));

    var firstResponse =
        await _client.SendAsync(firstRequest);

    var secondRequest = new HttpRequestMessage(
        HttpMethod.Post,
        "/api/payments");

    secondRequest.Headers.Add(
        "Idempotency-Key",
        key);

    secondRequest.Content = JsonContent.Create(
        new PaymentRequest(1025, 2500, "INR"));

    var secondResponse =
        await _client.SendAsync(secondRequest);

    Assert.Equal(
        firstResponse.StatusCode,
        secondResponse.StatusCode);

    Assert.Equal(
        "true",
        secondResponse.Headers
            .GetValues("Idempotency-Replayed")
            .Single());

    Assert.Equal(
        1,
        _paymentService.ProcessCount);
}

This example assumes the test application exposes the replay header and uses a test payment service that tracks how many times the operation executes.

A complete test suite should also cover:

Test case

Expected result

Missing key

Request rejected when a key is required

Empty key

Request rejected

Same key and same payload

Original result replayed

Same key and different payload

Conflict response

Two simultaneous requests with the same key

Only one request claims and executes the operation

Different clients using the same key

Requests remain isolated by client scope

First operation fails

Behavior follows the documented failure policy

Application restarts

Completed records remain available in persistent storage

Expired key

Behavior follows the documented retention policy

External service succeeds but API crashes

Retry does not duplicate the external operation

Concurrent tests are especially important. A test that sends two requests sequentially does not prove that the storage implementation handles race conditions.

Run concurrency tests against the same type of database or distributed store used in production. An in-memory test store may not reproduce database locking and uniqueness behavior.

Common Mistakes to Avoid

Mistake

Why it is a problem

Better approach

Generating a new key for every retry

The API treats every attempt as a new operation

Reuse one key for the logical operation

Using only an in-memory dictionary

Multiple instances cannot share state

Use persistent shared storage

Checking for a key before inserting

Concurrent requests can both pass the check

Use an atomic insert and unique constraint

Ignoring request fingerprints

A key can be reused with different data

Compare a stable request fingerprint

Returning cached responses before authorization

Stored data may be exposed to another caller

Authenticate and authorize before replay

Deleting processing records immediately

An external operation may already have succeeded

Use recovery and reconciliation

Assuming a database transaction covers an external API

The external operation cannot be rolled back with the database

Use downstream idempotency and outbox patterns

Keeping records forever

Storage grows unnecessarily

Apply a documented retention policy

Assuming exactly-once execution

Failures across system boundaries make this difficult

Design for deduplication and recovery

Best Practices for Production APIs

  1. Generate one idempotency key for each logical operation.

  2. Reuse the same key for network retries and repeated client submissions.

  3. Scope keys to the authenticated user, tenant, or API consumer.

  4. Enforce uniqueness in persistent storage.

  5. Calculate a fingerprint to detect reuse with a different request.

  6. Store the original response status, body, and relevant headers.

  7. Define explicit behavior for requests that are still processing.

  8. Use downstream idempotency support for payment and other external operations.

  9. Use database transactions when the business operation and idempotency record share the same database.

  10. Apply a retention policy that matches client retry behavior and business requirements.

  11. Test concurrent requests and application restarts.

  12. Monitor duplicate requests, fingerprint conflicts, processing timeouts, and replay counts.

Idempotency should be part of the API contract, not just an internal implementation detail. Document the required header, key scope, retention period, replay behavior, and error responses so every client follows the same rules.

Advantages and Disadvantages

Advantages

Disadvantages

Prevents duplicate processing from repeated requests

Requires persistent storage

Makes client retries safer

Adds database operations to request processing

Useful for payment and order APIs

Requires careful concurrent request handling

Supports distributed API deployments

Requires a shared storage mechanism

Can replay the original response

Response storage increases data-retention requirements

Helps recover from uncertain network outcomes

Does not automatically guarantee exactly-once execution across external systems

Conclusion

Idempotency keys are an important reliability feature for ASP.NET Core APIs that perform operations with side effects. They help prevent duplicate payments, orders, bookings, and other operations when clients retry requests after timeouts or network failures.

A reliable implementation needs more than checking whether a key exists. It requires atomic key claiming, request fingerprinting, persistent storage, response replay, authorization, expiration, and a clear policy for concurrent requests.

For operations that involve external services, combine API-level idempotency with downstream idempotency support, database transactions where appropriate, and reconciliation workflows for uncertain outcomes.

Start with a shared database and a unique constraint, then test repeated and concurrent requests before deploying the implementation. This makes API retries safer and gives clients a predictable way to recover from network failures.

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2025, SQL Server 2025, ASP.NET Core 11, ASP.NET MVC 6.0, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Blazor WebAssembly and ASP.NET Core Share Authentication

Leave a Comment

A crucial component of creating contemporary online applications is authentication. The majority of apps must safeguard sensitive data, manage login sessions, identify users, and restrict access to various functions.

Typically, ASP.NET Core Identity, cookie authentication, or an external identity provider are used to manage authentication in an ASP.NET Core application. However, developers must ensure that both components of the application operate with the same authorised user when a Blazor WebAssembly frontend connects with an ASP.NET Core backend.

 

This creates an important architectural question: How can a Blazor WebAssembly application share authentication with an ASP.NET Core API without implementing separate login systems?

The answer depends on how the application is hosted, how authentication is configured, and how the browser communicates with the backend.

In this article, we will explore how authentication works between Blazor WebAssembly and ASP.NET Core, understand cookie-based and token-based approaches, implement a practical authentication flow, and discuss security considerations for production applications.

Understanding Authentication Between Blazor WebAssembly and ASP.NET Core

Blazor WebAssembly applications execute inside the browser, while ASP.NET Core APIs execute on the server.

Because these applications run in different execution environments, they do not automatically share authentication state.

For example, imagine an employee management application with the following architecture:

  • Blazor WebAssembly handles the user interface.

  • ASP.NET Core Web API handles business operations.

  • ASP.NET Core Identity manages user accounts.

  • SQL Server stores user and application information.

When a user signs in, the backend establishes an authenticated session. However, the Blazor application also needs to understand whether the user is authenticated so it can display the appropriate pages, navigation options, and actions.

There are two important responsibilities here:

  1. The backend must authenticate requests and enforce authorization.

  2. The Blazor application must display the correct authentication state to the user.

These responsibilities are related, but they are not the same.

A Blazor component showing an authenticated user does not prove that the backend has authorized that user. Every protected API endpoint must perform its own authentication and authorization checks.

Understanding Different Authentication Approaches

There are multiple ways to share authentication between Blazor WebAssembly and ASP.NET Core.

The correct approach depends on whether the frontend and backend share the same origin and whether an external identity provider is involved.

Cookie-Based Authentication

Cookie authentication is a practical option when Blazor WebAssembly and ASP.NET Core are hosted under the same origin.

When a user signs in, the ASP.NET Core backend creates an authentication cookie and sends it to the browser.

The browser stores the cookie and automatically includes it in eligible requests to the same origin.

The ASP.NET Core application validates the cookie and identifies the user.

For example:

Blazor WebAssembly
        |
        | Login Request
        |
        v
ASP.NET Core API
        |
        | Validate Credentials
        |
        v
Authentication Cookie
        |
        v
Browser Stores Cookie
        |
        v
Future API Requests
        |
        v
ASP.NET Core Validates Cookie

This approach avoids exposing authentication tokens directly to JavaScript.

For browser-based applications, cookie authentication is generally a good choice when the application can use a secure same-origin architecture.

Token-Based Authentication

Token-based authentication is another approach, particularly when an application communicates with APIs hosted on separate origins or uses an external identity provider.

The user authenticates through an identity provider, and the application obtains an access token.

The Blazor application sends the token in the Authorization header when calling protected APIs.

For example:

GET /api/products HTTP/1.1
Host: api.example.com
Authorization: Bearer ACCESS_TOKEN

The backend validates the token and checks the user's permissions.

For production applications, OAuth 2.0 and OpenID Connect are preferred standards for this architecture.

Blazor WebAssembly supports authentication through the Microsoft.AspNetCore.Components.WebAssembly.Authentication library and OpenID Connect providers.

Comparing Cookie and Token Authentication

Feature

Cookie Authentication

Token Authentication

Authentication storage

Browser-managed cookie

Access token

Request handling

Browser sends eligible cookies automatically

Application sends bearer token

JavaScript access

HttpOnly cookies are not accessible to JavaScript

Depends on token storage

CSRF protection

Required for state-changing requests

Bearer-token requests require different CSRF considerations

Cross-origin configuration

Requires careful cookie and CORS configuration

Requires appropriate CORS and token configuration

Best suited for

Same-origin browser applications

API-based and distributed architectures

For a same-origin Blazor application, cookie authentication is often simpler. For applications using multiple APIs and external identity providers, token-based authentication may be more appropriate.

Implementing Cookie Authentication Between Blazor WebAssembly and ASP.NET Core

Let's build a practical example using ASP.NET Core as the authentication authority and Blazor WebAssembly as the frontend.

Assume that the backend already has an ASP.NET Core Identity implementation responsible for validating user credentials.

We will use cookie authentication to maintain the user session.

Step 1: Configure Cookie Authentication in ASP.NET Core

Open the backend application's Program.cs file.

Configure authentication and authorization services:

using Microsoft.AspNetCore.Authentication.Cookies;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddAuthentication(
        CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.Cookie.Name = "Application.Auth";

        options.Cookie.HttpOnly = true;

        options.Cookie.SecurePolicy =
            CookieSecurePolicy.Always;

        options.Cookie.SameSite =
            SameSiteMode.Lax;

        options.LoginPath = "/account/login";

        options.ExpireTimeSpan =
            TimeSpan.FromMinutes(30);

        options.SlidingExpiration = true;

        options.Events.OnRedirectToLogin = context =>
        {
            context.Response.StatusCode = 401;

            return Task.CompletedTask;
        };

        options.Events.OnRedirectToAccessDenied = context =>
        {
            context.Response.StatusCode = 403;

            return Task.CompletedTask;
        };
    });

builder.Services.AddAuthorization();

builder.Services.AddControllers();

var app = builder.Build();

app.UseHttpsRedirection();

app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

app.Run();

Let's understand some important settings.

Cookie.Name defines the authentication cookie name.

HttpOnly prevents JavaScript from reading the cookie directly.

SecurePolicy ensures that the cookie is transmitted over HTTPS.

SameSite controls when the browser sends the cookie in cross-site requests.

ExpireTimeSpan defines the authentication ticket lifetime.

The redirect event configuration is also important for APIs. Instead of redirecting an API request to an HTML login page, the application returns an HTTP 401 response.

This example demonstrates cookie configuration. In an application already using ASP.NET Core Identity, configure the existing Identity application cookie rather than registering a competing authentication scheme.

Step 2: Create a Login Endpoint

The backend needs an endpoint that authenticates the user and establishes the session.

When using ASP.NET Core Identity, the login operation should validate credentials through the configured SignInManager.

A simplified controller example is shown below:

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("api/account")]
public class AccountController : ControllerBase
{
    private readonly SignInManager<ApplicationUser>
        _signInManager;

    public AccountController(
        SignInManager<ApplicationUser> signInManager)
    {
        _signInManager = signInManager;
    }

    [HttpPost("login")]
    public async Task<IActionResult> Login(
        LoginRequest request)
    {
        var result = await _signInManager.PasswordSignInAsync(
            request.Email,
            request.Password,
            request.RememberMe,
            lockoutOnFailure: true);

        if (!result.Succeeded)
        {
            return Unauthorized(
                new { Message = "Invalid login credentials." });
        }

        return Ok(new
        {
            Message = "Login successful."
        });
    }
}

public record LoginRequest(
    string Email,
    string Password,
    bool RememberMe);

The PasswordSignInAsync method validates the supplied credentials and establishes the authentication session when the login succeeds.

The authentication cookie is generated by the configured Identity cookie scheme.

In production, also handle account lockout, email confirmation, two-factor authentication, and antiforgery protection.

Step 3: Configure HttpClient in Blazor WebAssembly

The Blazor application needs to communicate with the backend API.

Register HttpClient in the client project's Program.cs file:

using Microsoft.AspNetCore.Components.WebAssembly.Hosting;

var builder = WebAssemblyHostBuilder.CreateDefault(args);

builder.Services.AddScoped(sp =>
    new HttpClient
    {
        BaseAddress = new Uri(
            builder.HostEnvironment.BaseAddress)
    });

await builder.Build().RunAsync();

This example assumes that the frontend and backend share the same origin.

When the browser sends same-origin HTTP requests, eligible authentication cookies are included automatically.

For a separate API origin, configure the API base address and browser credentials appropriately. The backend must also use an explicit CORS policy that allows the frontend origin and credentials.

Step 4: Create an Authentication State Provider

The Blazor application needs to know whether the current user is authenticated.

For this purpose, Blazor provides the AuthenticationStateProvider abstraction.

We can create a custom provider that retrieves the current user's authentication information from the backend.

First, create a response model:

public class UserInfo
{
    public bool IsAuthenticated { get; set; }

    public string? Name { get; set; }

    public List<string> Roles { get; set; } = new();
}

Next, create a protected backend endpoint:

[Authorize]
[HttpGet("me")]
public IActionResult GetCurrentUser()
{
    return Ok(new UserInfo
    {
        IsAuthenticated = true,

        Name = User.Identity?.Name,

        Roles = User.Claims
            .Where(c => c.Type == ClaimTypes.Role)
            .Select(c => c.Value)
            .ToList()
    });
}

The endpoint returns information about the currently authenticated user.

Now create a custom authentication state provider in the Blazor WebAssembly project:

using Microsoft.AspNetCore.Components.Authorization;
using System.Security.Claims;
using System.Net.Http.Json;

public class CustomAuthenticationStateProvider
    : AuthenticationStateProvider
{
    private readonly HttpClient _httpClient;

    public CustomAuthenticationStateProvider(
        HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public override async Task<AuthenticationState>
        GetAuthenticationStateAsync()
    {
        try
        {
            var userInfo = await _httpClient
                .GetFromJsonAsync<UserInfo>("api/account/me");

            if (userInfo == null ||
                !userInfo.IsAuthenticated)
            {
                return AnonymousState();
            }

            var claims = new List<Claim>
            {
                new Claim(
                    ClaimTypes.Name,
                    userInfo.Name ?? string.Empty)
            };

            claims.AddRange(userInfo.Roles.Select(role =>
                new Claim(ClaimTypes.Role, role)));

            var identity = new ClaimsIdentity(
                claims,
                "ServerAuthentication");

            return new AuthenticationState(
                new ClaimsPrincipal(identity));
        }
        catch
        {
            return AnonymousState();
        }
    }

    private static AuthenticationState AnonymousState()
    {
        return new AuthenticationState(
            new ClaimsPrincipal(
                new ClaimsIdentity()));
    }

    public void NotifyAuthenticationChanged(
        ClaimsPrincipal user)
    {
        NotifyAuthenticationStateChanged(
            Task.FromResult(
                new AuthenticationState(user)));
    }
}

This provider requests the current user information from the backend and creates a ClaimsPrincipal for the Blazor interface.

Register the provider in Program.cs:

using Microsoft.AspNetCore.Components.Authorization;

builder.Services.AddAuthorizationCore();

builder.Services.AddScoped<
    AuthenticationStateProvider,
    CustomAuthenticationStateProvider>();

The provider allows Blazor components to display the current authentication state.

Importantly, the ClaimsPrincipal created inside WebAssembly is only a representation of the user for the client interface. It does not authenticate API requests or replace backend authorization.

The backend remains responsible for validating the authentication cookie on every protected request.

Step 5: Display Authentication Information in Blazor

Blazor provides the AuthorizeView component to display content based on the authentication state.

For example:

<AuthorizeView>
    <Authorized>
        <h3>Welcome, @context.User.Identity?.Name</h3>

        <p>You are successfully authenticated.</p>
    </Authorized>

    <NotAuthorized>
        <p>Please sign in to continue.</p>
    </NotAuthorized>
</AuthorizeView>

The component automatically displays the appropriate content based on the authentication state provider.

This makes it easier to build navigation menus, dashboards, and protected user interface sections.

However, hiding a button or page section does not protect the corresponding backend operation. The API must still enforce authorization independently.

Handling Logout and Session Expiration

Authentication is not complete without a proper logout process.

When a user logs out, the backend must invalidate the authentication session by removing the authentication cookie.

For cookie-based authentication, a logout endpoint can use the configured authentication scheme:

[HttpPost("logout")]
public async Task<IActionResult> Logout()
{
    await HttpContext.SignOutAsync(
        CookieAuthenticationDefaults.AuthenticationScheme);

    return Ok(new
    {
        Message = "Logged out successfully."
    });
}

After the backend clears the cookie, the Blazor application should refresh its authentication state.

For example, the custom provider can notify components that the user is now anonymous.

The application should also handle expired sessions. If an API request returns HTTP 401, the frontend can refresh the authentication state and redirect the user to the login page when appropriate.

Logout and other state-changing endpoints should be protected against cross-site request forgery.

Important Security Considerations for Production

Sharing authentication between Blazor WebAssembly and ASP.NET Core requires careful security configuration.

Use HTTPS Everywhere

Authentication cookies and other sensitive information should never be transmitted over unprotected HTTP connections.

Configure HTTPS for both the frontend and backend.

Protect Against CSRF Attacks

Cookie authentication automatically attaches eligible cookies to browser requests.

This creates a CSRF risk for state-changing operations.

Use antiforgery tokens for operations such as login, logout, updating user information, and deleting records. Validate these tokens on the backend.

Never Trust Client-Side Authorization

A user can inspect and modify client-side application code.

Therefore, authorization checks performed inside Blazor components are not sufficient.

Always use the Authorize attribute, authorization policies, or equivalent backend checks on protected endpoints.

Configure Cookie Properties Correctly

Use HttpOnly and Secure cookies, and choose an appropriate SameSite policy.

If the frontend and backend use different origins, review browser credential handling and cross-origin cookie restrictions carefully.

Handle Session Expiration

Applications should have a clear session expiration strategy.

Handle expired sessions gracefully and avoid leaving users with interfaces that appear authenticated while backend requests are being rejected.

Avoid Storing Sensitive Tokens in Browser Storage

Avoid storing access tokens, refresh tokens, or other sensitive credentials in localStorage or sessionStorage without carefully evaluating the security implications.

For browser-based applications, secure cookies or a properly designed backend-for-frontend architecture can reduce direct exposure of credentials to JavaScript.

Common Mistakes and Troubleshooting

Problem

Possible Cause

Recommended Solution

Blazor shows the user as anonymous

Authentication provider cannot retrieve user information

Verify the current-user API endpoint

API returns HTTP 401

Missing, expired, or invalid authentication cookie

Check cookie configuration and browser requests

API returns HTTP 403

User lacks the required permission

Review roles and authorization policies

Login succeeds but API calls fail

Cookie is not included in subsequent requests

Verify origin, cookie properties, and credentials

Authentication disappears after refresh

Client-only authentication state was not restored

Retrieve the session from the backend

Logout does not update the interface

Authentication state was not refreshed

Notify the authentication state provider

Cross-origin login fails

Incorrect CORS or cookie configuration

Configure explicit origins and credentials

Browser developer tools are particularly useful when troubleshooting authentication issues.

Inspect the Network tab to verify whether the login response contains the expected Set-Cookie header and whether subsequent API requests include the authentication cookie.

Also inspect the browser console for CORS errors and review backend authentication logs.

Summary

Sharing authentication between Blazor WebAssembly and ASP.NET Core requires a clear separation between client-side authentication state and server-side security enforcement.

Cookie authentication is a practical choice when both applications share the same origin. It allows the browser to manage the authentication cookie while ASP.NET Core validates incoming requests.

Token-based authentication is another option when applications communicate with separate APIs or use external identity providers.

Blazor's AuthenticationStateProvider and AuthorizeView components make it easier to display authentication information in the user interface. However, these components should never replace backend authentication and authorization checks.

For production applications, developers should focus on HTTPS, secure cookie configuration, CSRF protection, session expiration, and proper API authorization.

With the right architecture, Blazor WebAssembly and ASP.NET Core can share a consistent authentication experience without creating separate and unnecessary authentication systems.

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2025, SQL Server 2025, ASP.NET Core 11, ASP.NET MVC 6.0, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Maintaining Kafka Consumers Throughout Rebalances

Leave a Comment

A typical aspect of managing a consumer group is Kafka consumer rebalancing. It occurs when members join or depart the organization, when divisions are redistributed, or when the group must bounce back from a setback.

 
When rebalances occur too frequently, the issue arises. It is possible for a customer to do beneficial tasks for a brief period of time before losing their division assignment. While the group decides on a new task, messages may be processed once more, consumption may stop, and latency may increase.

Frequent rebalancing can become a performance and reliability issue for applications handling high event quantities.

Eliminating rebalancing is not the aim. It is necessary for Kafka to preserve partition ownership and consumer group membership. The objective is to stop regular application work from creating needless group instability and to make consumer behaviour predictable during rebalances.

This article describes why Kafka consumers rebalance, what leads to preventable rebalances, and how to create a C# consumer that properly manages them. 

What Is a Kafka Consumer Rebalance?

Kafka divides a topic into partitions.

For example:

orders
├── Partition 0
├── Partition 1
├── Partition 2
└── Partition 3

A consumer group processes those partitions.

With two consumers:

Consumer A -> Partition 0, Partition 1
Consumer B -> Partition 2, Partition 3

If Consumer B leaves the group, Kafka needs to redistribute its partitions.

Consumer A -> Partition 0, Partition 1, Partition 2, Partition 3

That redistribution is a rebalance.

A rebalance can happen when:

  • A new consumer joins the group.

  • A consumer shuts down.

  • A consumer crashes.

  • A consumer misses group heartbeats.

  • Partition assignments change.

  • A consumer takes too long between polls.

  • Deployment replaces consumer instances.

  • Group membership changes.

Rebalancing itself is expected behavior.

The problem is frequent or poorly handled rebalancing.

Why Rebalances Can Affect Application Performance

During a rebalance, partition ownership changes.

A simplified sequence looks like this:

Consumer A
    |
    | Processing
    v
Kafka detects membership change
    |
    v
Rebalance starts
    |
    v
Partition ownership changes
    |
    v
Consumers resume processing

Depending on the consumer configuration and assignment strategy, consumption can pause during this process.

If the application is already under heavy load, even a short pause can increase consumer lag.

Repeated rebalances can create a cycle:

Slow processing
      |
      v
Consumer misses expected timing
      |
      v
Rebalance
      |
      v
Consumption pauses
      |
      v
Lag increases
      |
      v
More work accumulates
      |
      v
Consumer becomes slower
      |
      v
Another rebalance

This is why consumer stability matters as much as raw processing speed.

The Most Common Cause Is Consumer Timing

Kafka needs to know that a consumer is still participating in the group.

Two timing concepts are especially important:

  • Heartbeat behavior

  • Poll interval

The exact configuration depends on the Kafka client and workload, but the underlying principle is simple.

The consumer must continue communicating with Kafka while processing records.

A consumer that spends too long doing synchronous work without polling can be considered unhealthy.

For example:

Poll
 |
 v
Process 10,000 records
 |
 | 10 minutes
 v
Poll again

If the processing interval exceeds the configured limits, Kafka may remove the consumer from the group.

The result is a rebalance.

Separate Polling From Slow Business Work

One of the most useful design improvements is separating Kafka consumption from slow business processing.

Instead of making the Kafka consumer directly perform a long-running operation:

Kafka Consumer
     |
     v
Database
     |
     v
External API
     |
     v
Large computation

use a controlled processing pipeline:

Kafka Consumer
     |
     v
Bounded Work Queue
     |
     +---- Worker 1
     +---- Worker 2
     +---- Worker 3

The consumer can continue participating in the group while workers process the application workload.

However, this design introduces another responsibility.

You must not allow the internal queue to grow without limits.

A bounded queue provides backpressure.

Using a Bounded Channel in C#

The .NET Channel<T> class works well for this type of pipeline.

For example:

var channel = Channel.CreateBounded<OrderEvent>(
    new BoundedChannelOptions(500)
    {
        FullMode = BoundedChannelFullMode.Wait,
        SingleWriter = true,
        SingleReader = false
    });

The Kafka consumer writes records into the channel:

await channel.Writer.WriteAsync(
    orderEvent,
    cancellationToken);

Worker tasks can then process the events:

await foreach (var orderEvent in
    channel.Reader.ReadAllAsync(cancellationToken))
{
    await ProcessOrderAsync(
        orderEvent,
        cancellationToken);
}

The bounded capacity prevents Kafka consumption from creating unlimited in-memory work.

Do Not Process Unlimited Records in Parallel

A common response to consumer lag is increasing concurrency.

For example:

Consumer
   |
   +--> Task 1
   +--> Task 2
   +--> Task 3
   +--> ...
   +--> Task 1000

This can make the problem worse.

If every task performs a database query, the application may overwhelm the database.

If every task calls an external API, the API may throttle the application.

If memory usage increases, the process can become unstable.

A better design uses controlled concurrency:

Kafka Consumer
      |
      v
Bounded Queue
      |
      +--> Worker 1
      +--> Worker 2
      +--> Worker 3
      +--> Worker 4

The correct number of workers should be based on the workload and downstream capacity.

Understand max.poll.interval.ms

Kafka clients expose a configuration that controls the maximum interval between polls.

If your consumer performs too much work between polls, it can exceed this interval.

For a .NET Kafka client, the configuration may look like:

var config = new ConsumerConfig
{
    BootstrapServers = bootstrapServers,
    GroupId = "orders-service",
    AutoOffsetReset = AutoOffsetReset.Earliest,
    EnableAutoCommit = false,
    MaxPollIntervalMs = 300000
};

The important point is not to simply increase the value whenever rebalances occur.

If processing genuinely takes longer, you should first understand why.

Increasing the interval can hide an underlying performance problem.

For example:

Database query = 2 seconds
Message processing = 3 seconds
External API = 8 seconds
Total = 13 seconds

If the consumer processes many records in one poll before polling again, the total time can become much larger than expected.

Reduce the Amount of Work Per Poll

Another useful configuration is the maximum number of records returned in one poll.

For example:

var config = new ConsumerConfig
{
    BootstrapServers = bootstrapServers,
    GroupId = "orders-service",
    MaxPollIntervalMs = 300000,
    MaxPollRecords = 100
};

If processing each record takes time, reducing the number of records processed per polling cycle can help keep the consumer responsive.

The right value depends on:

  • Processing time per record

  • Database capacity

  • External API latency

  • Consumer CPU usage

  • Message size

  • Desired throughput

There is no universal value that works for every application.

Offset Commit Strategy Matters

Kafka consumers need to commit offsets to track progress.

There are two broad concerns:

Message received
      |
      v
Message processed
      |
      v
Offset committed

The order matters.

If an offset is committed before the business operation completes, a crash can result in lost processing.

If the business operation completes but the offset is not committed before a crash, Kafka can deliver the record again.

That second scenario is why consumers should be idempotent.

A safe mental model is:

Process successfully
      |
      v
Commit offset

But even this does not create exactly-once business behavior by itself.

The database operation and Kafka offset commit are separate systems.

Why Duplicate Processing Can Still Happen

Consider this sequence:

1. Kafka delivers message 100
2. Consumer processes message 100
3. Database transaction succeeds
4. Consumer crashes
5. Offset 100 was not committed
6. Kafka delivers message 100 again

The message is processed twice.

This is normal for at-least-once processing.

The application should make important operations idempotent.

For example:

eventId = 7b8e...

First processing
    -> Database change
    -> Record eventId

Duplicate processing
    -> eventId already exists
    -> Skip business operation

This is particularly important when rebalances are frequent.

Cooperative Rebalancing Can Reduce Disruption

Kafka supports different partition assignment approaches.

Some strategies can move many partitions away from consumers during a rebalance.

Cooperative rebalancing allows partition movement to happen more gradually.

With the Confluent Kafka .NET client, the configuration can be selected through the partition assignment strategy.

For example:

var config = new ConsumerConfig
{
    BootstrapServers = bootstrapServers,
    GroupId = "orders-service",
    PartitionAssignmentStrategy =
        PartitionAssignmentStrategy.CooperativeSticky
};

The exact behavior depends on the Kafka client version and broker/client compatibility, so configuration changes should be tested in a staging environment.

The main benefit is reducing unnecessary disruption when membership changes.

Graceful Shutdown Is Important

Consumer deployments often cause rebalances.

If an application shuts down abruptly, Kafka has to detect that the consumer disappeared.

A graceful shutdown allows the consumer to leave the group cleanly.

For example:

await consumer.CloseAsync();

A hosted service can handle application cancellation:

public async Task StopAsync(
    CancellationToken cancellationToken)
{
    _consumer.Close();

    await base.StopAsync(cancellationToken);
}

The exact implementation depends on how the consumer is hosted.

The important idea is that deployment should not look like a consumer crash.

A clean shutdown can reduce unnecessary group disruption.

Be Careful With Deployments

Suppose a consumer group has ten instances.

A rolling deployment replaces them one by one.

If each replacement causes partition movement, the group may experience several rebalances during deployment.

A deployment strategy should therefore consider:

  • Number of consumer instances

  • Partition count

  • Shutdown behavior

  • Startup timing

  • Health checks

  • Readiness checks

  • Maximum unavailable instances

A consumer should not receive production traffic before it is ready to participate correctly in the group.

Static Membership Can Help Stable Consumer Groups

Kafka also supports static group membership.

A stable member identity can reduce unnecessary partition movement when a consumer temporarily restarts.

For example:

var config = new ConsumerConfig
{
    BootstrapServers = bootstrapServers,
    GroupId = "orders-service",
    GroupInstanceId = instanceId
};

The GroupInstanceId should be stable for the intended consumer instance.

This is useful in environments where consumer instances have predictable identities.

It should not be configured casually with the same value on multiple instances.

Two active consumers should not incorrectly claim the same group instance identity.

Watch Out for Long External API Calls

A Kafka consumer can become unstable when message processing depends on slow external services.

For example:

Kafka
  |
  v
Consumer
  |
  v
Payment API
  |
  | 30 seconds
  v
Response

If the consumer processes many records sequentially, the delay can become large.

A better design can move external work into a bounded worker pool or use a workflow architecture appropriate for the operation.

Timeouts are also important:

using var timeoutCts =
    CancellationTokenSource.CreateLinkedTokenSource(
        cancellationToken);

timeoutCts.CancelAfter(
    TimeSpan.FromSeconds(10));

await paymentClient.ProcessAsync(
    payment,
    timeoutCts.Token);

A timeout prevents one dependency from keeping a message-processing task alive indefinitely.

Avoid Blocking Async Code

Blocking calls can make consumer responsiveness worse.

Avoid:

var result = ProcessAsync().Result;

and:

ProcessAsync().Wait();

Prefer:

var result = await ProcessAsync();

This is especially important in consumers because a blocked processing pipeline can increase latency, reduce throughput, and make timing problems harder to diagnose.

Monitor Consumer Lag

Consumer lag is one of the most useful metrics for Kafka applications.

It represents the difference between messages available in the partition and the consumer's current position.

A simplified example:

Partition 0
Latest offset: 10000
Consumer offset: 9800

Lag = 200

A temporary increase is not necessarily a problem.

The important question is whether the consumer can recover.

Lag
 |
 |       /\
 |      /  \
 |_____/    \____
              \
               \____

Healthy consumers can catch up after a short traffic spike.

A struggling consumer might look like:

Lag
 |
 |     /
 |    /
 |   /
 |  /
 | /
 |/____________

If lag keeps increasing, investigate:

  • Processing time

  • Database latency

  • External API latency

  • Consumer CPU

  • Memory pressure

  • Number of workers

  • Partition count

  • Rebalance frequency

Useful Metrics to Monitor

A production Kafka consumer should expose enough information to answer why processing is slowing down.

Useful metrics include:

Metric

What it tells you

Consumer lag

Whether the consumer is keeping up

Rebalance count

Whether group membership is unstable

Processing duration

How long business work takes

Poll interval

Whether the consumer is polling regularly

Error rate

Whether messages are failing

Retry count

Whether downstream operations are unstable

Commit latency

Whether offset commits are delayed

CPU usage

Whether the consumer is resource constrained

Memory usage

Whether buffering is excessive

Database latency

Whether the database is slowing processing

Do not look at consumer lag alone.

A high lag value tells you that the consumer is behind, but not why.

Common Mistakes

Increasing max.poll.interval.ms without fixing processing time

This may hide the problem instead of solving it.

First measure how long message processing actually takes.

Processing everything inside the Kafka callback

Long-running work inside the consumer loop can make polling behavior difficult to control.

A bounded worker pipeline is often easier to operate.

Creating unlimited background tasks

Starting one task per message can move the bottleneck from Kafka to the application or database.

Use bounded concurrency.

Committing offsets too early

If the offset is committed before business processing succeeds, a crash can result in lost work.

Assuming a rebalance means messages are lost

A rebalance changes partition ownership. With appropriate offset management and idempotent processing, messages can be processed safely again.

Ignoring graceful shutdown

Abrupt termination can make deployments look like consumer failures.

Close consumers cleanly when the application stops.

Using the same GroupInstanceId for multiple consumers

Static membership requires unique, stable instance identities.

Duplicate identities can cause membership problems.

A Practical Consumer Design

A production-oriented architecture can look like this:

                  Kafka
                    |
                    v
            Consumer Group
                    |
                    v
             Poll Records
                    |
                    v
          Bounded Work Queue
                    |
          +---------+---------+
          |         |         |
          v         v         v
       Worker    Worker    Worker
          |         |         |
          +---------+---------+
                    |
                    v
          Business Operations
                    |
                    v
             Commit Offset

The important controls are distributed across the pipeline.

Kafka controls partition assignment.

The consumer controls polling.

The bounded queue controls memory and backpressure.

Workers control processing concurrency.

The database or downstream services control transaction and idempotency behavior.

This separation makes the system easier to tune.

When to Increase Consumer Count

Adding more consumers can increase throughput, but only when enough partitions are available.

For example:

Topic partitions = 3
Consumers = 3

Each consumer can receive work.

But:

Topic partitions = 3
Consumers = 10

Seven consumers will remain idle because there are not enough partitions to assign.

Increasing consumer count also changes group membership and can trigger rebalancing.

Scale consumers based on:

  • Partition count

  • Consumer lag

  • Processing time

  • CPU usage

  • Downstream capacity

Do not scale purely because lag increased.

The bottleneck might be the database or an external API.

Production Checklist

Before running a Kafka consumer in production, verify:

  1. Consumer processing time is measured.

  2. Polling is not blocked by long-running operations.

  3. MaxPollIntervalMs matches the actual workload.

  4. MaxPollRecords is tuned appropriately.

  5. Consumer concurrency is bounded.

  6. Backpressure exists between Kafka and workers.

  7. Offsets are committed only after successful processing.

  8. Business operations are idempotent.

  9. Graceful shutdown is implemented.

  10. Rebalance events are monitored.

  11. Consumer lag is monitored.

  12. Database and external API latency are monitored.

  13. Retry behavior is bounded.

  14. Static membership is configured only when appropriate.

  15. Cooperative assignment is tested when suitable.

  16. Deployments are designed to minimize unnecessary consumer disruption.

Advantages and Disadvantages

Advantages

  • More stable consumer groups.

  • Lower impact from normal membership changes.

  • Better control over processing concurrency.

  • Reduced risk of consumer lag caused by slow message handling.

  • Easier troubleshooting through clear processing boundaries.

  • Better protection for downstream databases and APIs.

Disadvantages

  • The architecture becomes more complex.

  • Worker queues require capacity planning.

  • Incorrect concurrency can still overload downstream systems.

  • Rebalance tuning depends on workload characteristics.

  • More metrics and operational monitoring are required.

The objective is not to prevent every rebalance.

A healthy Kafka application should be able to rebalance without turning the event-processing pipeline into an outage.

Conclusion

Kafka rebalancing is part of how consumer groups maintain reliable partition ownership. It becomes a problem when consumers take too long to process records, fail to poll regularly, shut down abruptly, or constantly join and leave the group.

The first step is to understand the processing path rather than immediately changing Kafka timeout values.

Measure how long message processing takes. Keep polling responsive. Limit the amount of work performed in each polling cycle. Use bounded concurrency instead of creating unlimited tasks. Make business operations idempotent so records can safely be processed again when necessary.

Graceful shutdown, cooperative rebalancing, and stable group membership can further reduce unnecessary disruption.

Most importantly, monitor consumer lag and rebalance frequency together with database and external-service latency. A Kafka consumer that appears to have a Kafka problem may actually be waiting on a slow database or API.

A well-designed consumer does not depend on rebalances never happening. It is designed so that when a rebalance does happen, processing can continue without losing messages or overwhelming the systems behind it.

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2025, SQL Server 2025, ASP.NET Core 11, ASP.NET MVC 6.0, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Making a Console App Faster and Smaller with .NET 11

Leave a Comment

Even though a console application appears straightforward, putting it into production is quite another. Framework dependencies, NuGet packages, configuration files, and runtime components may all add to the deployment footprint of even modest applications.

When deploying command-line tools to numerous servers, cloud environments, containers, or CI/CD agents, this becomes crucial.

Consider a console application that runs every few minutes, processes a file, calls an API, and exits. The actual business logic might take only a few milliseconds, but application startup and deployment overhead can become a noticeable part of its execution time.

.NET provides several ways to address these problems. You can remove unused code through trimming, compile applications ahead of time using Native AOT, and configure publishing to prioritize application size or execution speed.

.NET 11 continues to build on these capabilities.

In this article, we will create a console application, examine its publishing options, and see how to make it smaller and faster without unnecessarily changing the application logic.

Why Does a Small Console Application Need Optimization?

Let's take a simple example.

You have a console application responsible for processing daily transaction files. It starts, reads a file, performs calculations, writes the results, and exits.

The application itself may contain only a few classes, but its published output can include much more than your source code.

Some of the additional components include:

  • .NET runtime libraries.
  • Application dependencies.
  • Third-party NuGet packages.
  • Native libraries.
  • Configuration and supporting files.

The actual deployment size depends on the publishing model, target operating system, architecture, and dependencies.

There are also performance considerations.

If the application starts and exits frequently, startup time matters. If it runs continuously, steady-state execution performance may be more important.

This is why optimization should begin with understanding how the application is used.

Step 1: Create a Basic .NET 11 Console Application

First, create a new console application.

dotnet new console -n FastConsoleApp -f net11.0

cd FastConsoleApp

Open the project file. It should contain a configuration similar to this:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>

Now replace the contents of Program.cs with a small processing example.

using System.Diagnostics;

var stopwatch = Stopwatch.StartNew();

Console.WriteLine("Transaction processing started.");

var transactions = new[]
{
    1200.50m,
    2500.00m,
    850.75m,
    4200.00m,
    1750.25m
};

decimal total = transactions.Sum();

stopwatch.Stop();

Console.WriteLine($"Transactions: {transactions.Length}");
Console.WriteLine($"Total Amount: {total}");
Console.WriteLine($"Execution Time: {stopwatch.ElapsedMilliseconds} ms");

This application performs a small calculation and prints the result.

Build and run it:

dotnet build -c Release

dotnet run -c Release

At this point, we have a working application. Next, we will change how it is published.

Step 2: Understand the Different Publishing Options

.NET supports multiple deployment models. Each one makes a different trade-off between deployment size, startup performance, and runtime requirements.

Publishing optionMain purposeImportant consideration
Framework-dependentUses an installed .NET runtimeSmaller application-specific deployment
Self-containedIncludes the required runtimeLarger deployment output
Single-fileBundles application-dependent filesSimplifies distribution
ReadyToRunPrecompiles assembliesCan improve startup but increases size
Native AOTCompiles application code into native machine codeFaster startup and potentially lower memory usage

These options are not interchangeable.

For example, single-file publishing does not automatically make an application faster or smaller. It primarily simplifies distribution.

Native AOT is different because it compiles application code into native machine code during publishing and removes the need for a JIT compiler at runtime.

For a small console application, Native AOT is worth testing.

Step 3: Enable Native AOT

Native AOT is one of the most useful options when your application needs fast startup and does not depend on runtime code generation.

To enable it, update the project file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>

    <PublishAot>true</PublishAot>

  </PropertyGroup>

</Project>

The important setting is:

<PublishAot>true</PublishAot>

This tells the .NET SDK to use Native AOT when publishing the application.

Native AOT also enables trimming because the compiler needs to determine which code is required and which code can be removed.

Unlike traditional JIT-based applications, Native AOT does not generate machine code dynamically when the application starts.

Publish the application for a specific platform:

dotnet publish -c Release -r win-x64

For Linux:

dotnet publish -c Release -r linux-x64

For macOS on Apple Silicon:

dotnet publish -c Release -r osx-arm64

Replace the runtime identifier according to your deployment environment.

One important point: Native AOT requires the appropriate native compiler toolchain. Depending on the operating system, you may need Visual C++ build tools, Clang, or other platform-specific development tools.

Also, publish separately for each operating system and architecture.

Step 4: Reduce Application Size Using Trimming

Trimming removes code that static analysis determines is not required by your application.

For example, a project may reference a library containing dozens of features while using only a small portion of them.

Without trimming, unnecessary code can remain in the published application.

You can enable trimming for a compatible application using:

<PropertyGroup>
    <PublishTrimmed>true</PublishTrimmed>
    <TrimMode>full</TrimMode>
</PropertyGroup>

The full trimming mode allows the linker to remove unused members from assemblies where trimming is supported.

However, trimming requires attention.

Some libraries use reflection to discover classes, methods, or properties dynamically. The linker may not recognize these dependencies through static analysis.

As a result, required code could be removed from the published application.

If your application uses reflection, serialization, dependency injection, or dynamically loaded components, test the trimmed output carefully.

Do not enable full trimming in production without validating the application.

Step 5: Optimize for Size or Execution Speed

Another useful publishing option is OptimizationPreference.

.NET provides this setting to communicate whether the application should prioritize size or execution speed during Native AOT compilation.

For example, to prioritize a smaller executable:

<PropertyGroup>
    <PublishAot>true</PublishAot>
    <OptimizationPreference>Size</OptimizationPreference>
</PropertyGroup>

To prioritize execution speed:

<PropertyGroup>
    <PublishAot>true</PublishAot>
    <OptimizationPreference>Speed</OptimizationPreference>
</PropertyGroup>

The difference is important.

When you choose Size, the compiler favors a smaller native executable. Some execution performance may be affected.

When you choose Speed, the compiler prioritizes execution performance, potentially producing a larger binary.

There is no universal winner. The right choice depends on the workload.

For a short-lived command-line utility, startup and deployment size may matter more than peak throughput.

For a continuously running data-processing application, execution speed may be more important.

Step 6: Compare the Published Output

Do not assume that Native AOT has reduced your application size simply because it is enabled.

Publish the application using different configurations and compare the output.

For example:

dotnet publish -c Release -r win-x64 \
    --self-contained true

For Native AOT:

dotnet publish -c Release -r win-x64 \
    -p:PublishAot=true

For a single-file deployment:

dotnet publish -c Release -r win-x64 \
    -p:PublishSingleFile=true

Record the executable size and total deployment folder size.

You should also measure:

  • Application startup time.
  • Time taken to complete the actual workload.
  • Peak memory consumption.
  • CPU utilization.
  • Build and publishing time.

Remember that an optimized executable is not automatically the fastest application in every scenario.

Native AOT generally improves startup behavior and can reduce memory usage, but a JIT-compiled application may achieve better steady-state throughput for certain workloads.

Step 7: Validate the Application Before Production

This is the part developers should not skip.

A successful Native AOT publish does not guarantee that every application feature will work correctly.

For example, consider an application that dynamically loads assemblies:

var assembly = Assembly.LoadFrom("Plugin.dll");

This type of dynamic loading is not supported in the normal Native AOT deployment model.

Similarly, runtime code generation through Reflection.Emit is not supported.

If your application depends on these capabilities, you may need to redesign that functionality or use a different publishing model.

For JSON serialization, source generation is a useful approach because it makes serialization metadata available at compile time.

For example:

using System.Text.Json;
using System.Text.Json.Serialization;

public class Transaction
{
    public int Id { get; set; }

    public decimal Amount { get; set; }
}

[JsonSerializable(typeof(Transaction))]
internal partial class AppJsonContext
    : JsonSerializerContext
{
}

You can then serialize using the generated metadata:

var transaction = new Transaction
{
    Id = 101,
    Amount = 2500.50m
};

string json = JsonSerializer.Serialize(
    transaction,
    AppJsonContext.Default.Transaction);

Console.WriteLine(json);

This avoids depending on runtime reflection for the serialization metadata.

For production applications, test the actual published executable rather than relying only on tests executed through the development environment.

Common Mistakes to Avoid

MistakeWhy it causes problemsBetter approach
Enabling Native AOT without checking dependenciesSome packages are not AOT-compatibleReview package compatibility
Assuming single-file means smallerBundling can increase executable sizeCompare actual output sizes
Ignoring trimming warningsRequired dynamically accessed members may be removedResolve warnings and test published output
Publishing for the wrong architectureNative binaries are platform-specificUse the correct runtime identifier
Measuring only build timeDoes not represent application performanceMeasure startup and workload execution
Disabling globalization without checking requirementsDate, number, and culture behavior may changeKeep globalization support when needed

Advantages and Disadvantages

Advantages

  • Faster application startup through Native AOT.
  • Potentially lower memory consumption.
  • No separate .NET runtime installation required for Native AOT deployment.
  • Smaller deployment output in many suitable scenarios.
  • Easier distribution of command-line utilities.
  • Reduced dependency on runtime JIT compilation.

Disadvantages

  • Longer publishing and compilation times.
  • Platform-specific builds are required.
  • Dynamic loading and runtime code generation are restricted.
  • Some NuGet dependencies may not support Native AOT.
  • Trimming requires additional testing.
  • The resulting executable may be larger when optimization prioritizes execution speed.

Summary

.NET provides several ways to make console applications smaller and faster, but the best results come from choosing the right publishing strategy for the workload.

Native AOT is particularly useful for short-lived command-line tools, containerized utilities, and applications where startup time and memory consumption matter. Trimming can further reduce unnecessary code, while OptimizationPreference allows developers to prioritize size or execution speed.

However, these optimizations come with compatibility requirements. Applications that depend heavily on reflection, dynamic loading, or runtime code generation may require additional changes.

My recommendation is to start with a normal Release build, measure the application, enable Native AOT, and compare the published results. Keep the optimization only when the measurements demonstrate a real improvement.

The goal is not simply to produce a smaller executable. It is to make the application faster to start, easier to deploy, and more efficient to operate in production.

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2025, SQL Server 2025, ASP.NET Core 11, ASP.NET MVC 6.0, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More
Previous PostOlder Posts Home