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.
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();- Stream() takes Order events that your own code emits (an in-app source).
- Filter keeps orders whose Status is "Confirmed". A Pending order is dropped.
- Map turns each kept Order into an OrderEvent.
- Sink writes each OrderEvent with Console.WriteLine.
- This recipe uses no state store and no telemetry.
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.
- An Order event arrives on the stream.
- Join looks up the order's CustomerId in CustomerStore, an InMemoryStateStore.
- An Order with a known Customer becomes an EnrichedOrder and goes to the Sink.
- An Order with no matching Customer is dropped, because Join is an inner join.
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.
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
- PageView events arrive on the stream.
- TumblingWindow puts each event into a fixed 15-minute window by its timestamp. Windows do not overlap.
- When a window closes, Map turns it into one summary: Page, ViewCount and UniqueVisitors.
- Sink receives one summary per window.
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.
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.
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 resourcesSee 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.
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.
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);- 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.
- 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.
- 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.
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
- Kafka
- Pulsar
- RabbitMQ
- AWS SQS
- Azure Service Bus
- Elasticsearch
- Amazon S3
- Azure Blob Storage
- HTTP
- Files
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
Build with Cortex.
Start from GitHub or the docs.