How RedCrab is adopted, step by step
The way a team goes from one process to two nodes that talk through a broker, on one operation, GetCarDetails of the samples' cluster carservices: what the code looks like at each step, and what RedCrab takes away.
Steps 1 and 2 are illustrative and say so; steps 3 to 6 show the code of the samples, each excerpt naming its file.
The monolith
The caller and the service live in one process. A call is a method: typed, awaited, and it either returns a car or throws. Nothing is agreed with anybody, because there is nobody else.
// One process: the caller holds the service itself.
var carservices = new CarServices(garage);
var car = await carservices.GetCarDetails(carId);
Console.WriteLine($"{car.Make} {car.Model}, {car.Year}");sealed class CarServices(Garage garage) {
public async Task<CarDetails> GetCarDetails(int carId) =>
await garage.Find(carId) ?? throw new KeyNotFoundException($"No car has id {carId}.");
}The broker, by hand
The service moves to a node of its own, and the two talk through a broker so that each can stop, restart or scale without the other. Written by hand, the one line of step 1 becomes all of the code below. Each node now builds broker clients, names channels as strings both must spell alike, keeps a correlation id and the calls it waits for, runs a loop, encodes payloads, and decides what an error means. These are the fifteen responsibilities of the reference paper, each marked with its id: none of them is the domain's, and every one of them is in the domain's code.
Deeper: The criterion
var producer = new ProducerBuilder<string, string>(
new ProducerConfig { BootstrapServers = "localhost:9092" }).Build(); // LEL-1
var consumer = new ConsumerBuilder<string, string>(new ConsumerConfig {
BootstrapServers = "localhost:9092", GroupId = $"orders-{Guid.NewGuid()}" }).Build(); // LEL-1
const string RequestTopic = "carservices.GetCarDetails.req"; // DEL-1 the operation bound to a channel by hand
const string ReplyTopic = "carservices.GetCarDetails.reply"; // DEL-2 which reply channel completes the request
var pending = new ConcurrentDictionary<string, TaskCompletionSource<string>>(); // LEL-2
consumer.Subscribe(ReplyTopic);
_ = Task.Run(() => { // LEL-3 the reply loop
while (true) {
var msg = consumer.Consume();
var id = Encoding.UTF8.GetString(msg.Message.Headers.GetLastBytes("correlation-id")); // DEL-4
if (!pending.TryRemove(id, out var waiter)) continue; // LSL-1 a reply nobody waits for: dropped
waiter.SetResult(msg.Message.Value);
}
});
async Task<CarDetails> GetCarDetails(int carId) {
var id = Guid.NewGuid().ToString(); // DEL-4
var waiter = new TaskCompletionSource<string>();
pending[id] = waiter; // LEL-2
try {
await producer.ProduceAsync(RequestTopic, new Message<string, string> {
Key = id,
Value = JsonSerializer.Serialize(carId), // DEL-3, DSL-1
Headers = new Headers { { "correlation-id", Encoding.UTF8.GetBytes(id) } } // DEL-4
});
}
catch (ProduceException<string, string> ex) {
throw new InvalidOperationException("The broker refused the request.", ex); // LEL-5, LSL-2
}
var reply = JsonDocument.Parse(await waiter.Task.WaitAsync(TimeSpan.FromSeconds(15))).RootElement; // DEL-3
if (reply.GetProperty("status").GetString() == "error") // DSL-3 the error space, decoded here
throw new KeyNotFoundException(reply.GetProperty("message").GetString()); // LSL-2
return reply.GetProperty("value").Deserialize<CarDetails>()!; // DSL-2
}
var car = await GetCarDetails(carId);var consumer = new ConsumerBuilder<string, string>(new ConsumerConfig {
BootstrapServers = "localhost:9092", GroupId = "carservices" }).Build(); // LEL-1
var producer = new ProducerBuilder<string, string>(
new ProducerConfig { BootstrapServers = "localhost:9092" }).Build(); // LEL-1
consumer.Subscribe("carservices.GetCarDetails.req"); // DEL-1
while (true) { // LEL-4 the request loop
var msg = consumer.Consume();
var id = msg.Message.Headers.GetLastBytes("correlation-id"); // DEL-4
var carId = JsonSerializer.Deserialize<int>(msg.Message.Value); // DEL-3, DSL-1
string json;
try {
var car = await garage.Find(carId) ?? throw new KeyNotFoundException($"No car has id {carId}."); // LSL-3
json = JsonSerializer.Serialize(new { status = "ok", value = car }); // DSL-2
}
catch (KeyNotFoundException ex) {
json = JsonSerializer.Serialize(new { status = "error", message = ex.Message }); // LSL-2, DSL-3
}
try {
await producer.ProduceAsync("carservices.GetCarDetails.reply", new Message<string, string> { // DEL-2
Key = msg.Message.Key, Value = json,
Headers = new Headers { { "correlation-id", id } } // DEL-4
});
}
catch (ProduceException<string, string> ex) {
Console.Error.WriteLine(ex.Error.Reason); // LEL-5
}
}The contract
The operation is declared once, in a contract the broker holds: its request, reply and error payloads, with their schemas, and the outcomes a caller may receive. The steward publishes it on the broker's configuration stream and creates the streams of its operations. Nobody writes a channel name again: they are derived from the cluster and the operation.
Deeper: Tools
{
"NamingVersion": 1,
"ClusterName": "carservices",
"ConfigTimestampUtc": "2026-11-15T00:00:00Z",
"Payloads": {
"CarDetails": {
"JsonSchema": {
"type": "object",
"properties": {
"Make": { "type": "string" },
"Model": { "type": "string" },
"Year": { "type": "integer", "format": "int32" },
"Color": { "type": "string" }
},
"required": [ "Make", "Model", "Year" ],
"additionalProperties": false
}
}
},
"OperationEndpoints": {
"GetCarDetails": {
"Description": "The details of a car, by its id.",
"RequestPayload": "Int32",
"ReplyPayload": "CarDetails",
"ErrorPayload": "RedCrabError",
"Outcomes": {
"not-found": "No car has the requested id."
},
"RequestPartitions": 1,
"ReplyPartitions": 1
}
}
}The generation, from the contract alone
The generator reads the contract and writes, into each node's project, what that node needs: the requestor facade, one typed method per operation, for the node that calls; the replier projection, one interface per operation, for the node that serves; the outcomes and a typed failure. Neither node sees the other's code. They share the contract, and the generated code carries its hash.
Deeper: Tools
/// <summary>
/// Requests the operation 'GetCarDetails'. A declared failure arrives as <see cref="GetCarDetailsFailed"/>.
/// </summary>
internal async Task<CarDetailsReply> GetCarDetails(int request, int? timeoutMs = null, CancellationToken cancellationToken = default) /// <summary>
/// The replier contract of the operation 'GetCarDetails': implement it to serve the operation; the host finds the implementation.
/// </summary>
[RedCrabOperation(Name = "GetCarDetails", Enabled = true)]
internal interface IGetCarDetails : IReplyQuery<int, CarDetailsReply> { }The wiring
The node registers its cluster and the broker its endpoint names, the transport it uses and the generated surfaces. The serving side implements the generated interface; the host finds it by that. At start-up the node reads the contract from the broker and compares its hash with the one its generated code carries.
Deeper: In code
var services = new ServiceCollection();
services.AddRedCrab()
.AddCluster("carservices", endpoint) // the endpoint's scheme names the transport
.WithRequestTimeout(15000)
.WithLogging() // RedCrab's own log: the transport chosen, the contract check
.Register();
services.AddRedCrabKafka(); // a node registers the transport it uses; this sample registers both, so that
services.AddRedCrabPulsar(); // REDCRAB_ENDPOINT can point at either broker
services.AddRedCrabSdk(); // the generated facades
// The node's local policy for a reply that comes after its request gave up: see Policies/LateReplyPolicy.cs.
services.AddSingleton<IUnmatchedReplyPolicy, LateReplyPolicy>();
using var provider = services.BuildServiceProvider();
await provider.InitializeRedCrabAsync(); // reads the contract, checks its hash, starts the runtimes and the replierinternal sealed class GetCarDetailsReplier : CarservicesReplier.IGetCarDetails {
public Task<CarDetailsReply> ReplyAsync(int carId) {
if (carId <= 0) {
// A governed outcome: the requestor receives GetCarDetailsFailed with this code.
throw GetCarDetailsOutcomes.Fail(GetCarDetailsOutcomes.NotFound, $"No car has id {carId}.");
}
return Task.FromResult(new CarDetailsReply("RedCrab Motors", $"Model {carId}", 2024, "Red"));
}
}The run
The caller's line is the line of step 1 again. Underneath, the call travels as a request event and comes back as a reply event with the same correlation id; a declared outcome arrives as a typed failure, and no reply in time as a RequestException, which the node decides about.
Deeper: The figure, How it works
// A request ends in one of three ways: the reply, an outcome the contract declares, or no reply at all.
foreach (var carId in new[] { 7, 0 }) {
try {
var car = await carservices.GetCarDetails(carId);
Console.WriteLine($"GetCarDetails({carId}): {car.Make} {car.Model}, {car.Year}, {car.Color}");
}
catch (GetCarDetailsFailed failed) when (failed.Code == GetCarDetailsOutcomes.NotFound) {
Console.WriteLine($"GetCarDetails({carId}): not found ({failed.Message})");
}
catch (RequestException ex) {
// No reply in time, or the transport refused the send: what that means is the node's to decide.
Console.WriteLine($"GetCarDetails({carId}): no reply ({ex.Message})");
exitCode = 1;
}
}Two tools write what a node calls and implements
A node's code is never written against the broker. The operations are declared once, in a contract the broker holds, and what the node calls and implements is generated from it.
- The steward publishes the contract. It writes a cluster's operations, with their request, reply and failure payloads and their outcome codes, publishes the contract on the broker and creates the streams of its operations.
- The generator writes the node's surfaces. From the contract, read from the broker or from a file, it writes into the node's project the requestor facade, one typed method per operation that wraps the exchange of events (what RPC frameworks call a client stub), and the replier projection, the interfaces a serving node implements; with them the outcome codes and a typed failure per operation.
- The node checks its contract at start-up. The generated code carries the hash of the contract it was generated from; at start-up the node compares it with the contract on the broker, and a mismatch stops the node, or warns if so configured.
RedCrab.g.cs root facade: RedCrab.<Cluster>
DI/RedCrabSdk.DI.g.cs services.AddRedCrabSdk()
<Cluster>/<Cluster>Cluster.g.cs [RedCrabClusterInfo(Name, NamingVersion, ContractTimestampUtc, ContractHash)]
<Cluster>/Requestor/<Cluster>Requestor.g.cs one typed method per operation
<Cluster>/Requestor/Requests/<Op>Request.g.cs
<Cluster>/Replier/<Cluster>Replier.g.cs I<Op> : IReplyQuery<…> / IReplyCommand<…>, for the replier
<Cluster>/Outcomes/<Cluster>Outcomes.g.cs <Op>Outcomes (the declared codes), <Op>Failed
redcrab.codegen.decisions.json the manifest
The tools come with the source, which is available on request; the packages a node needs are on nuget.org.