Microservice SDK

StellaOps.Microservice turns a .NET process into a Router microservice. It connects the process to a gateway through a transport client, tells the gateway which endpoints the process serves, and dispatches each forwarded request to an endpoint class. This page covers every endpoint kind, the registration options, the microservice.yaml override file and the source generator.

For a first service, follow Getting started. For an existing ASP.NET Core application, use the ASP.NET Core bridge instead of endpoint classes.

Packages

PackageLicenceRole
StellaOps.MicroserviceApache-2.0The SDK: registration, connection, dispatch.
StellaOps.Microservice.SourceGenApache-2.0Development dependency. Generates the endpoint registration at compile time and reports the STELLA diagnostics.
StellaOps.Router.Transport.<Name>Apache-2.0The client half of one transport: InMemory, Tcp, Tls, Udp, RabbitMq or Messaging (Transports).
Microsoft.Extensions.HostingMIT (Microsoft)The generic host. The SDK needs only its abstractions, so a console service adds it.

A typical service project:

<PackageReference Include="StellaOps.Microservice" Version="$(RouterPackageVersion)" />
<PackageReference Include="StellaOps.Microservice.SourceGen" Version="$(RouterPackageVersion)" PrivateAssets="all" />
<!-- The generic host (Host.CreateApplicationBuilder); the Router packages need only its abstractions. -->
<PackageReference Include="Microsoft.Extensions.Hosting" Version="10.0.1" />
<PackageReference Include="StellaOps.Router.Transport.Tcp" Version="$(RouterPackageVersion)" />

Register the service

AddStellaMicroservice registers the SDK and describes the service:

builder.Services.AddStellaMicroservice(options =>
{
    options.ServiceName = "billing";
    options.Version = "1.0.0";
    options.Region = "demo";
    options.InstanceId = builder.Configuration["Router:InstanceId"] ?? $"billing-{Environment.MachineName}";
    // Endpoint overrides (timeouts, streaming, required scopes) read from the output directory.
    options.ConfigFilePath = Path.Combine(AppContext.BaseDirectory, "microservice.yaml");
    // Below the gateway's degraded threshold (Gateway:Health:DegradedThreshold; 20 s in effect by default).
    options.HeartbeatInterval = TimeSpan.FromSeconds(10);
    options.Routers =
    [
        new RouterEndpointConfig { Host = gatewayHost, Port = gatewayPort, TransportType = TransportType.Tcp }
    ];
});

Then register one transport client. The transport client decides where the service connects:

builder.Services.AddTcpTransportClient(options =>
{
    options.Host = gatewayHost;
    options.Port = gatewayPort;
});

Options

The options are set in code. To read them from configuration, read the values yourself, as the sample does for Router:Host and Router:Port. The API reference lists them under StellaMicroserviceOptions.

OptionDefaultMeaning
ServiceNamenone, requiredThe service name. The gateway routes to instances of this name.
Versionnone, requiredThe service version, a semantic version such as 1.0.0 or 2.1.0-beta.1. Start-up fails on another form.
Regionnone, requiredThe region of this instance. A gateway prefers instances in its own region.
InstanceIda new GUID per start, as 32 hexadecimal digitsThe instance identifier in the gateway’s instance list. Set a stable value, such as the host name, to recognise an instance across restarts, and a different one for each process: when a second process connects with the same service name, version, region, transport and InstanceId, the gateway replaces the first one’s registration and routes only to the second.
Weight100The routing weight the instance advertises. 0 or more.
RoutersemptyAt least one entry is required. Each entry names a gateway connection (Host, Port, TransportType). Set it to the address of the transport client.
ConfigFilePathnoneThe path of microservice.yaml. Without it, or when the file does not exist, no overrides apply.
ServiceDescription, ContactInfononeText for the gateway’s OpenAPI document.
HeartbeatInterval10 secondsHow often the instance reports its health. Keep it below the gateway’s degraded threshold (20 seconds with the gateway’s defaults): see the pitfalls below.
DrainDeadline25 secondsOn shutdown, how long the instance waits for requests in flight after it reports Draining.
DrainPollInterval100 millisecondsHow often shutdown checks the number of requests in flight.
ReconnectBackoffInitial1 secondThe first delay before the service connects again: at start-up, after the transport client reports its connection dead, and when a Messaging transport fails. A TCP or TLS client first retries on its own options (Transports).
ReconnectBackoffMax1 minuteThe longest delay between those retries. At least ReconnectBackoffInitial.

The options are validated when the host starts; an invalid value stops the host with Stella microservice options validation failed.

Endpoints

An endpoint is a class with [StellaEndpoint(method, path)] (reference) that implements one handler interface. The attribute has three optional properties:

PropertyDefaultMeaning
TimeoutSeconds30The endpoint’s timeout. The gateway cancels the request when it expires.
SupportsStreamingfalseMarks an endpoint that takes or returns files. In this release the gateway and the SDK still hold the whole request and response body in memory; the gateway sends the response without Content-Length and reports a timeout as Upstream streaming timeout (File uploads and downloads). Use it with IRawStellaEndpoint.
RequiredClaimsnoneClaim types the caller’s token must carry, any value. For a claim with a value, such as a scope, use microservice.yaml (see Endpoint claims).

Path templates use {name} for a segment parameter, for example /invoices/{id}.

Typed endpoints

IStellaEndpoint<TRequest, TResponse> receives a request object and returns a response object. The SDK reads the JSON body into TRequest and writes TResponse as JSON with camel-case property names; property names in the request match in any letter case.

[StellaEndpoint("POST", "/invoices", TimeoutSeconds = 30)]
public sealed class CreateInvoiceEndpoint : IStellaEndpoint<CreateInvoiceRequest, CreateInvoiceResponse>
{
    private readonly ILogger<CreateInvoiceEndpoint> _logger;

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

    public Task<CreateInvoiceResponse> HandleAsync(
        CreateInvoiceRequest request,
        CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "Creating invoice for customer {CustomerId} with amount {Amount}",
            request.CustomerId,
            request.Amount);

        // Simulate invoice creation
        var invoiceId = $"INV-{Guid.NewGuid():N}".ToUpperInvariant()[..16];

        return Task.FromResult(new CreateInvoiceResponse
        {
            InvoiceId = invoiceId,
            CreatedAt = DateTime.UtcNow,
            Status = "draft"
        });
    }
}

Input from the path and the query

The SDK also fills public settable properties of TRequest from the query string and the path parameters, matched by name in any letter case:

  1. With a body, the SDK reads the JSON body first. Without a body, it creates TRequest with its parameterless constructor.
  2. It then sets properties from the query string.
  3. It then sets properties from the path parameters, which win over the query.

The supported property types are string, int, long, double, decimal, bool, Guid and enumerations, and their nullable forms. A value that does not convert is skipped, so the property keeps its earlier value.

public sealed record GetInvoiceRequest
{
    public required string Id { get; init; }
}

For GET /invoices/INV-001, Id is INV-001. For GET /items?category=widgets&page=2 on the inventory sample, Category is widgets and Page is 2.

An endpoint without input

Use an empty request type. A GET request has no body, so the SDK creates the request and fills it from the query and path, which set nothing here:

/// <summary>An empty request: the endpoint takes no input.</summary>
public sealed record ListCategoriesRequest;

/// <summary>The item categories of the catalogue.</summary>
public sealed record CategoriesResponse
{
    public required IReadOnlyList<string> Categories { get; init; }
}

/// <summary>
/// An endpoint without input. A GET request has no body, so the SDK creates the empty request
/// and fills it from the query and path, which here set nothing.
/// </summary>
[StellaEndpoint("GET", "/categories", TimeoutSeconds = 5)]
public sealed class ListCategoriesEndpoint : IStellaEndpoint<ListCategoriesRequest, CategoriesResponse>
{
    public Task<CategoriesResponse> HandleAsync(ListCategoriesRequest request, CancellationToken cancellationToken) =>
        Task.FromResult(new CategoriesResponse { Categories = ["gadgets", "widgets"] });
}

The SDK also defines IStellaEndpoint<TResponse>, a handler without a request: HandleAsync(CancellationToken) returns the response, and the request body is not read. The source generator publishes it like the other typed endpoints.

Raw endpoints

IRawStellaEndpoint receives a RawRequestContext and returns a RawResponse. Use it for bodies that are not JSON, such as files, and for full control of the status code and headers. The reports sample accepts an attachment upload:

[StellaEndpoint("POST", "/reports/{id}/attachments", SupportsStreaming = true, TimeoutSeconds = 60)]
public sealed class UploadAttachmentEndpoint : IRawStellaEndpoint
var contentType = context.Headers["Content-Type"] ?? "application/octet-stream";
_logger.LogInformation(
    "Uploading attachment for report {ReportId}, Content-Type: {ContentType}",
    reportId,
    contentType);

// Copy the body in fixed chunks; the gateway has already received all of it.
long totalBytes = 0;
var buffer = new byte[8192];
int bytesRead;

while ((bytesRead = await context.Body.ReadAsync(buffer, cancellationToken)) > 0)
{
    totalBytes += bytesRead;
    // In a real implementation, you would write to storage here
}

_logger.LogInformation(
    "Received {TotalBytes} bytes for report {ReportId}",
    totalBytes,
    reportId);

var response = new
{
    reportId,
    attachmentId = $"ATT-{Guid.NewGuid():N}"[..16].ToUpperInvariant(),
    size = totalBytes,
    uploadedAt = DateTime.UtcNow
};

var headers = new HeaderCollection();
headers.Set("Content-Type", "application/json");
return new RawResponse
{
    StatusCode = 200,
    Headers = headers,
    Body = new MemoryStream(JsonSerializer.SerializeToUtf8Bytes(response))
};

RawRequestContext holds Method, Path, PathParameters, QueryParameters, Headers, Body, CorrelationId and CancellationToken. RawResponse holds StatusCode (default 200), Headers and Body, and has helpers:

HelperResponse
RawResponse.Ok(string), Ok(byte[]), Ok(Stream)200 with the body
RawResponse.NoContent()204
RawResponse.BadRequest(message)400
RawResponse.NotFound(message)404
RawResponse.InternalError(message)500
RawResponse.Error(statusCode, message)any status with a text message

context.Body holds the whole request body: the gateway receives all of it before it sends the request, with or without SupportsStreaming. File uploads and downloads shows both directions and their size limits.

Register the endpoint classes

The SDK resolves each endpoint class from dependency injection, in a new scope per request, so the class can take any registered service in its constructor. Register every endpoint class:

builder.Services.AddScoped<CreateInvoiceEndpoint>();
builder.Services.AddScoped<GetInvoiceEndpoint>();

AddStellaEndpoint<T>() is the same registration (AddScoped<T>()). An endpoint class that is not registered is still published, and every request to it returns 500 and logs Handler type ... not registered in DI container.

microservice.yaml

microservice.yaml changes the endpoints the code declares, without a rebuild. It cannot add an endpoint. Set ConfigFilePath to its path and copy it to the output directory:

# Endpoint overrides for the billing service (keys: method, path, defaultTimeout, supportsStreaming,
# requiringClaims). The gateway enforces the claims the service publishes: a caller without a valid
# token gets 401, a caller without the scope 403.

endpoints:
  - method: POST
    path: /invoices
    defaultTimeout: 45s
    requiringClaims:
      - type: "scope"
        value: "invoices:write"

  - method: GET
    path: /invoices/{id}
    requiringClaims:
      - type: "scope"
        value: "invoices:read"
KeyMeaning
method, pathSelect the endpoint. Both match in any letter case; the path must equal the declared template.
defaultTimeoutReplaces TimeoutSeconds. A whole number followed by s, m or h (45s, 5m, 1h), or a .NET time span (00:00:45).
supportsStreamingReplaces SupportsStreaming.
requiringClaimsA list of type and optional value. When the list is not empty, it replaces the claims of the code.

Unknown keys are ignored. An entry that matches no endpoint is ignored with a warning, and so is a defaultTimeout the SDK cannot read. A file that is not valid YAML stops the service at start-up.

Endpoint claims

The gateway checks claims before it dispatches a request:

CallerResult
No valid bearer token401 from the gateway, for every endpoint of an endpoint class
A valid token without a required claim403 from the gateway
A valid token with every required claimThe request reaches the service

A claim requirement with a value matches a claim of that type and value. For the scope and scp claims, the gateway also reads a space-separated list in one claim, as OAuth 2.0 access tokens carry it. A requirement without a value matches any claim of that type. RequiredClaims on the attribute creates requirements without a value; microservice.yaml creates both kinds.

An endpoint without claims of its own needs an authenticated caller only, with one exception: a POST, PUT, PATCH or DELETE endpoint, or one that accepts any method, takes the claims of the other endpoints of the same service on the same path. With GET /invoices/{id} requiring invoices:read, a DELETE /invoices/{id} without claims also requires invoices:read, and a caller without it gets 403. Give every write endpoint its own claims.

The gateway checks the endpoint’s claims only. A service that needs the caller’s identity reads the forwarded Authorization header and validates the token itself (Security).

Timeouts

The gateway takes an endpoint’s timeout from microservice.yaml, else TimeoutSeconds (30 seconds when the attribute does not set it), and caps it at Gateway:Routing:GlobalTimeoutCap (120 seconds). Every endpoint class carries a timeout, so the gateway’s own Gateway:Routing:DefaultTimeout never applies to it. An endpoint that needs longer than the cap needs a higher cap on the gateway as well (Long requests and cancellation).

The source generator

StellaOps.Microservice.SourceGen finds every [StellaEndpoint] class at compile time and generates the endpoint table, so the service needs no reflection at start-up. The service then logs Discovered <n> endpoints via source generation. Without the package, the SDK finds the endpoints by reflection when the service starts, and reports no compile-time diagnostics.

The generator reports:

IdSeverityMeaningFix
STELLA001ErrorA [StellaEndpoint] class implements none of IStellaEndpoint<TRequest, TResponse>, IStellaEndpoint<TResponse> and IRawStellaEndpoint.Implement one of them. For an endpoint without input, use IStellaEndpoint<TResponse> or an empty request type.
STELLA002WarningTwo classes declare the same method and path.Remove one declaration, or change its path.
STELLA003Warning[StellaEndpoint] on an abstract class is ignored.Put the attribute on the concrete class.
STELLA004Info, off by defaultThe number of endpoint descriptors generated.Turn it on in .editorconfig (dotnet_diagnostic.STELLA004.severity = suggestion) to see the count in the build.
STELLA005WarningThe JSON Schema of a request or response type could not be generated.Simplify the type (Schema validation and OpenAPI).
STELLA006Warning[ValidateSchema] on a raw endpoint is ignored.Validate the body inside the endpoint.

Shutdown

On shutdown the instance reports Draining. The gateway stops sending it new requests, and the instance waits up to DrainDeadline for the requests in flight, checking every DrainPollInterval. To finish long requests on a rolling update, set DrainDeadline above the longest endpoint timeout and give the process that much time to stop.

Pitfalls