Cortex

Streaming infrastructure for .NET.

Cortex is an open-source .NET streaming framework with fluent pipelines, built-in state management, and broker connectors.

Events in, clean results out

Step through the pipeline. The code highlights as you go.

OrderPipeline.cs
using Cortex.Streams; public record Order(string Id, decimal Amount, string Status);public record OrderEvent(string Id, decimal Amount, DateTime ProcessedAt); var stream = StreamBuilder<Order>    .CreateNewStream("OrderPipeline")    .Stream()    .Filter(o => o.Status == "Confirmed")          // keep only confirmed    .Map(o => new OrderEvent(o.Id, o.Amount, DateTime.UtcNow)) // enrich    .Sink(e => Console.WriteLine($"{e.Id} @ {e.ProcessedAt:O}"))    .Build(); stream.Start();stream.Emit(new Order("ORD-1", 120m, "Confirmed")); // passes throughstream.Emit(new Order("ORD-2", 50m, "Pending"));    // droppedstream.Stop();
  1. Stream() takes Order events that your own code emits (an in-app source).
  2. Filter keeps orders whose Status is "Confirmed". A Pending order is dropped.
  3. Map turns each kept Order into an OrderEvent.
  4. Sink writes each OrderEvent with Console.WriteLine.
  5. This recipe uses no state store and no telemetry.
Filter drops Pending orders, Map reshapes the rest, Sink delivers. Illustrative.

Pipelines that read like the data flow

Chain operators in plain C#. Sources, joins and sinks share one fluent shape.

Enrich events from a lookup table

LeftJoin emits unmatched events with a null right side.

  1. An Order event arrives on the stream.
  2. Join looks up the order's CustomerId in CustomerStore, an InMemoryStateStore.
  3. An Order with a known Customer becomes an EnrichedOrder and goes to the Sink.
  4. An Order with no matching Customer is dropped, because Join is an inner join.
Each Order is matched to a Customer in state. No match, no output. Illustrative.

Stream-table enrichment with a state-store lookup

Enrich streaming events by looking up reference data held in a state store. .Join is an inner join (drops unmatched); .LeftJoin always emits with a null right side for missing keys.

Read the docs

using Cortex.Streams;
using Cortex.States;

public record Order(string OrderId, int CustomerId, decimal Amount);
public record Customer(int Id, string Name, string Tier);
public record EnrichedOrder(string OrderId, decimal Amount, string CustomerName, string Tier);

// Reference table (a state store) - pre-populate or update while running
var customers = new InMemoryStateStore<int, Customer>("CustomerStore");
customers.Put(1001, new Customer(1001, "Alice", "Gold"));
customers.Put(1002, new Customer(1002, "Bob", "Silver"));

var stream = StreamBuilder<Order>
    .CreateNewStream("OrderEnrichment")
    .Stream()
    .Join(
        customers,
        order => order.CustomerId,                 // key selector
        (order, c) => new EnrichedOrder(order.OrderId, order.Amount, c.Name, c.Tier))
    .Sink(e => Console.WriteLine($"{e.OrderId}: {e.CustomerName} ({e.Tier})"))
    .Build();

stream.Start();
stream.Emit(new Order("ORD-1", 1001, 150m));  // emits - Alice exists
stream.Emit(new Order("ORD-2", 9999, 200m));  // dropped - no match (inner join)
stream.Stop();

Group events into fixed time windows

  1. PageView events arrive on the stream.
  2. TumblingWindow puts each event into a fixed 15-minute window by its timestamp. Windows do not overlap.
  3. When a window closes, Map turns it into one summary: Page, ViewCount and UniqueVisitors.
  4. Sink receives one summary per window.
A tumbling window collects events per page, then emits one summary. Illustrative.

Tumbling window: count events per fixed interval

Group events into fixed-size, non-overlapping time windows with .TumblingWindow<TKey>(...), then map each window's Items to a count and other summary metrics.

Read the docs

using System.Linq;
using Cortex.Streams;
using Cortex.Streams.Operators.Windows;

public record PageView(string PageUrl, string UserId, DateTime Timestamp);

var stream = StreamBuilder<PageView>
    .CreateNewStream("TrafficAnalytics")
    .Stream()
    .TumblingWindow<string>(
        keySelector: pv => pv.PageUrl,
        timestampSelector: pv => pv.Timestamp,
        windowSize: TimeSpan.FromMinutes(15))
    .Map(window => new
    {
        Page = window.Key,
        ViewCount = window.Items.Count,
        UniqueVisitors = window.Items.Select(pv => pv.UserId).Distinct().Count(),
        window.WindowStart,
        window.WindowEnd
    })
    .Sink(s => Console.WriteLine(
        $"{s.Page}: {s.ViewCount} views, {s.UniqueVisitors} uniques " +
        $"[{s.WindowStart:HH:mm}-{s.WindowEnd:HH:mm}]"))
    .Build();

stream.Start();

State that survives a restart

Keep state in memory, or in a store you already run. Swap stores without changing the pipeline.

Persist aggregate state with RocksDB

Back a stateful aggregation with a durable RocksDbStateStore so counts survive restarts. Pass the store instance to AggregateSilently and dispose it on shutdown.

Read the docs

State stores

  • In-Memory
  • RocksDB
  • PostgreSQL
  • SQL Server
  • SQLite
  • MongoDB
  • Cassandra
  • ClickHouse
  • DuckDB
using Cortex.Streams;
using Cortex.States.RocksDb;

// Durable, on-disk key-value store: ctor is (name, dbPath)
var wordCounts = new RocksDbStateStore<string, int>("WordCountStore", "./data/rocksdb");

var stream = StreamBuilder<string>
    .CreateNewStream("WordCount")
    .Stream()
    .AggregateSilently<string, int>(
        word => word,                       // group by the word
        (count, _) => count + 1,            // increment
        stateStoreName: "WordCountStore",
        stateStore: wordCounts)             // persistent backend
    .Sink(word => Console.WriteLine($"counted: {word}"))
    .Build();

stream.Start();
foreach (var w in new[] { "apple", "banana", "apple" })
    stream.Emit(w);

Console.WriteLine($"apple => {wordCounts.Get("apple")}");  // 2

stream.Stop();
wordCounts.Dispose();        // flush + release resources

See what every operator does

Metrics and traces per operator, with buffering and a clean shutdown when you need them.

Add OpenTelemetry metrics and traces

Wire telemetry into a pipeline with .WithTelemetry(provider) placed BEFORE .Stream(...). Cortex then records per-operator metrics and traces automatically.

Read the docs

using Cortex.Streams;
using Cortex.Telemetry.OpenTelemetry;

public record Order(string Id, decimal Amount);

// Telemetry must be configured before .Stream(...)
var telemetry = new OpenTelemetryProvider();

var stream = StreamBuilder<Order>
    .CreateNewStream("InstrumentedOrders")
    .WithTelemetry(telemetry)            // <-- before Stream()
    .Stream()
    .Filter(o => o.Amount > 0)
    .Map(o => o with { Amount = o.Amount * 1.2m })
    .Sink(o => Console.WriteLine($"{o.Id}: {o.Amount}"))
    .Build();

stream.Start();
stream.Emit(new Order("ORD-1", 100m));
stream.Stop();

The mediation pattern

Cortex.Mediator sits between the code that sends a request and the code that handles it, so sender and handler never reference each other.

Three messages, one mediator

Step through each message kind. The code highlights as you go.

Sender and handler never reference each other; IMediator sits between. Illustrative.
public class CreateOrderCommand : ICommand<Guid>{    public string CustomerName { get; set; }    // …} public class CreateOrderCommandHandler : ICommandHandler<CreateOrderCommand, Guid>{    // …} var orderId = await _mediator.SendAsync(command);var result = await _mediator.QueryAsync(new GetOrderQuery { OrderId = id });await _mediator.PublishAsync(new OrderCreatedNotification{    OrderId = order.Id,    // …}, cancellationToken);
  1. Command: the Controller sends CreateOrderCommand to IMediator with SendAsync, which passes it to its one handler, CreateOrderCommandHandler. Pipeline behaviors can wrap the handler; for commands they include exception handling, logging, validation and transactions.
  2. Query: the Controller sends GetOrderQuery to IMediator with QueryAsync, which passes it to its one handler, GetOrderHandler. Pipeline behaviors can wrap the handler; for queries they include logging and caching.
  3. Notification: after its work, a command handler publishes OrderCreatedNotification through IMediator with PublishAsync. Every handler for it runs, one after another in registration order: SendOrderConfirmationHandler, UpdateInventoryHandler, AwardLoyaltyPointsHandler.

Read the CQRS guide

Integrations

Connectors for the brokers and sinks you already run. Every connector is its own package with the same source and sink shape.

Plug into the brokers and storage you already run

  1. Kafka
  2. Pulsar
  3. RabbitMQ
  4. AWS SQS
  5. Azure Service Bus
  6. Elasticsearch
  7. Amazon S3
  8. Azure Blob Storage
  9. HTTP
  10. Files
Each connector is its own package.

Packages

Use the packages together, or only the ones you need.

Cortex.Streams
Fluent pipelines: map, filter, aggregate, window, join, fan out
Cortex.States
Pluggable state stores
Cortex.Telemetry
OpenTelemetry metrics and traces
Cortex.Mediator
Commands, queries and notifications for CQRS
Cortex.Types
OneOf, AnyOf and AllOf types

Start from a recipe

Short, runnable recipes for ingest, joins, state and delivery. Browse the Cortex recipes