Chronicle explicit subscriptions for event forwarding
An explicit subscription in Cratis Chronicle forwards selected event types from a source store’s outbox into the consuming store’s inbox. Register it through the client API when you need to choose the subscription ID, control which types arrive, or create and remove the relationship at runtime.
The source must publish the events to its Chronicle outbox. Explicit registration does not import events directly from an external system; see Outbox and Inbox for the publication and delivery flow.
Setting Up an Explicit Subscription
Section titled “Setting Up an Explicit Subscription”In the consuming application, use the Subscriptions property on its IEventStore. The source name identifies the store to read from; the IEventStore you call determines where forwarded events are stored:
using Cratis.Chronicle;using Cratis.Chronicle.Events;
[EventType]public record SubscriptionsExplicitShipmentDispatched(string OrderId);
public static class SubscriptionsExplicitBasic{ public static Task Run(IEventStore eventStore) => eventStore.Subscriptions.Subscribe( "orders-from-fulfillment", "fulfillment-service", builder => builder.WithEventType<SubscriptionsExplicitShipmentDispatched>());}import io.cratis.chronicle.EventStoreimport io.cratis.chronicle.events.EventType
@EventTypedata class SubscriptionsExplicitPayrollRunCompleted(val employeeId: String, val amount: Double)
suspend fun subscribeToPayroll(store: EventStore) { store.eventStoreSubscriptions.subscribe("payroll-inbox", "PayrollEventStore") { builder -> builder.withEventType(SubscriptionsExplicitPayrollRunCompleted::class) }}import io.cratis.chronicle.EventStore;import io.cratis.chronicle.events.EventType;
import io.cratis.chronicle.java.EventStoreSubscriptionBuilderJavaBridge;import io.cratis.chronicle.java.EventStoreSubscriptionsServiceJavaBridge;
@EventTyperecord SubscriptionsExplicitPayrollRunCompleted(String employeeId, double amount) {}
class SubscriptionsExplicitBasic { void subscribeToPayroll(EventStore store) { EventStoreSubscriptionsServiceJavaBridge.subscribe(store.getEventStoreSubscriptions(), "payroll-inbox", "PayrollEventStore", builder -> { EventStoreSubscriptionBuilderJavaBridge.withEventType(builder, SubscriptionsExplicitPayrollRunCompleted.class); }); }}defmodule MyApp.Events.SubscriptionsExplicitShipmentDispatched do use Cratis.Chronicle.Events.EventType, id: "subscriptions-explicit-shipment-dispatched"
defstruct [:order_id]end
defmodule MyApp.SubscriptionsExplicitBasic do alias Cratis.Chronicle.EventStoreSubscriptions.DefinitionBuilder alias MyApp.Events.SubscriptionsExplicitShipmentDispatched
def run do Cratis.Chronicle.subscribe_to_event_store( "orders-from-fulfillment", "fulfillment-service", fn builder -> DefinitionBuilder.with_event_type(builder, SubscriptionsExplicitShipmentDispatched) end, [] ) endendimport { eventType, IEventStore } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class SubscriptionsExplicitShipmentDispatched { @field(String) readonly orderId: string;
constructor(orderId: string) { this.orderId = orderId; }}
class SubscriptionsExplicitBasic { static async run(store: IEventStore): Promise<void> { await store.subscriptions.subscribe( 'orders-from-fulfillment', 'fulfillment-service', builder => builder.withEventType(SubscriptionsExplicitShipmentDispatched) ); }}The three arguments are:
| Argument | Description |
|---|---|
| Subscription ID | A stable, unique string that identifies this subscription within the target event store |
| Source event store | The name of the event store whose outbox to subscribe to |
| Configuration callback | Optional — filters which event types to forward |
Subscription ID
Section titled “Subscription ID”Choose a stable subscription ID that is unique within the target event store. The kernel stores the definition under this ID. Repeating an identical registration does not create another subscription; changing the definition under the same ID updates that subscription.
A name that describes the consuming relationship is easier to recognize later:
using Cratis.Chronicle;using Cratis.Chronicle.Events;
[EventType]public record SubscriptionsExplicitStockAdjusted(string ItemId, int Delta);
public static class SubscriptionsExplicitNamingConvention{ public static async Task Run(IEventStore eventStore) { // subscription-id format: {target}-from-{source} await eventStore.Subscriptions.Subscribe( "orders-from-fulfillment", "fulfillment-service", builder => builder.WithEventType<SubscriptionsExplicitShipmentDispatched>());
await eventStore.Subscriptions.Subscribe( "inventory-from-warehouse", "warehouse-service", builder => builder.WithEventType<SubscriptionsExplicitStockAdjusted>()); }}import io.cratis.chronicle.EventStore
suspend fun subscribeWithStableId(store: EventStore) { // Use a stable, descriptive id — it identifies this subscription across restarts // and is how you target it later with unsubscribe(). store.eventStoreSubscriptions.subscribe("payroll-inbox-v1", "PayrollEventStore") { // No filter: subscribe to event types currently registered by this client. }}import io.cratis.chronicle.EventStore;
import io.cratis.chronicle.java.EventStoreSubscriptionsServiceJavaBridge;
class SubscriptionsExplicitNamingConvention { void subscribeWithStableId(EventStore store) { // Use a stable, descriptive id — it identifies this subscription across restarts // and is how you target it later with unsubscribe(). // No filter: subscribe to event types currently registered by this client. EventStoreSubscriptionsServiceJavaBridge.subscribe(store.getEventStoreSubscriptions(), "payroll-inbox-v1", "PayrollEventStore", builder -> { }); }}defmodule MyApp.Events.SubscriptionsExplicitStockAdjusted do use Cratis.Chronicle.Events.EventType, id: "subscriptions-explicit-stock-adjusted"
defstruct [:item_id, :delta]end
defmodule MyApp.SubscriptionsExplicitNamingConvention do alias Cratis.Chronicle.EventStoreSubscriptions.DefinitionBuilder alias MyApp.Events.{SubscriptionsExplicitShipmentDispatched, SubscriptionsExplicitStockAdjusted}
def run do # subscription-id format: {target}-from-{source} :ok = Cratis.Chronicle.subscribe_to_event_store( "orders-from-fulfillment", "fulfillment-service", fn builder -> DefinitionBuilder.with_event_type(builder, SubscriptionsExplicitShipmentDispatched) end, [] )
Cratis.Chronicle.subscribe_to_event_store( "inventory-from-warehouse", "warehouse-service", fn builder -> DefinitionBuilder.with_event_type(builder, SubscriptionsExplicitStockAdjusted) end, [] ) endendimport { eventType, IEventStore } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class SubscriptionsExplicitStockAdjusted { @field(String) readonly itemId: string; @field(Number) readonly delta: number;
constructor(itemId: string, delta: number) { this.itemId = itemId; this.delta = delta; }}
class SubscriptionsExplicitNamingConvention { static async run(store: IEventStore): Promise<void> { // subscription-id format: {target}-from-{source} await store.subscriptions.subscribe( 'orders-from-fulfillment', 'fulfillment-service', builder => builder.withEventType(SubscriptionsExplicitShipmentDispatched) );
await store.subscriptions.subscribe( 'inventory-from-warehouse', 'warehouse-service', builder => builder.withEventType(SubscriptionsExplicitStockAdjusted) ); }}Filtering Event Types
Section titled “Filtering Event Types”Without a configuration callback, the C# builder selects every event type registered with that client when it builds the subscription. It does not request every possible type from the source. Use WithEventType<T>() to select only the contracts the consumer needs:
using Cratis.Chronicle;using Cratis.Chronicle.Events;
[EventType]public record SubscriptionsExplicitStockReserved(string ItemId, int Quantity);
public static class SubscriptionsExplicitFiltering{ public static Task Run(IEventStore eventStore) => eventStore.Subscriptions.Subscribe( "inventory-updates", "warehouse-service", builder => builder .WithEventType<SubscriptionsExplicitStockAdjusted>() .WithEventType<SubscriptionsExplicitStockReserved>());}import io.cratis.chronicle.EventStoreimport io.cratis.chronicle.events.EventType
@EventTypedata class SubscriptionsExplicitFilteringPayrollRunCompleted(val employeeId: String)
@EventTypedata class SubscriptionsExplicitFilteringPayrollRunFailed(val employeeId: String, val reason: String)
suspend fun subscribeToPayrollOutcomes(store: EventStore) { store.eventStoreSubscriptions.subscribe("payroll-outcomes", "PayrollEventStore") { builder -> builder .withEventType(SubscriptionsExplicitFilteringPayrollRunCompleted::class) .withEventType(SubscriptionsExplicitFilteringPayrollRunFailed::class) }}import io.cratis.chronicle.EventStore;import io.cratis.chronicle.events.EventType;
import io.cratis.chronicle.java.EventStoreSubscriptionBuilderJavaBridge;import io.cratis.chronicle.java.EventStoreSubscriptionsServiceJavaBridge;
@EventTyperecord SubscriptionsExplicitFilteringPayrollRunCompleted(String employeeId) {}
@EventTyperecord SubscriptionsExplicitFilteringPayrollRunFailed(String employeeId, String reason) {}
class SubscriptionsExplicitFiltering { void subscribeToPayrollOutcomes(EventStore store) { EventStoreSubscriptionsServiceJavaBridge.subscribe(store.getEventStoreSubscriptions(), "payroll-outcomes", "PayrollEventStore", builder -> { EventStoreSubscriptionBuilderJavaBridge.withEventType(builder, SubscriptionsExplicitFilteringPayrollRunCompleted.class); EventStoreSubscriptionBuilderJavaBridge.withEventType(builder, SubscriptionsExplicitFilteringPayrollRunFailed.class); }); }}defmodule MyApp.Events.SubscriptionsExplicitStockReserved do use Cratis.Chronicle.Events.EventType, id: "subscriptions-explicit-stock-reserved"
defstruct [:item_id, :quantity]end
defmodule MyApp.SubscriptionsExplicitFiltering do alias Cratis.Chronicle.EventStoreSubscriptions.DefinitionBuilder alias MyApp.Events.{SubscriptionsExplicitStockAdjusted, SubscriptionsExplicitStockReserved}
def run do Cratis.Chronicle.subscribe_to_event_store( "inventory-updates", "warehouse-service", fn builder -> builder |> DefinitionBuilder.with_event_type(SubscriptionsExplicitStockAdjusted) |> DefinitionBuilder.with_event_type(SubscriptionsExplicitStockReserved) end, [] ) endendimport { eventType, IEventStore } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class SubscriptionsExplicitStockReserved { @field(String) readonly itemId: string; @field(Number) readonly quantity: number;
constructor(itemId: string, quantity: number) { this.itemId = itemId; this.quantity = quantity; }}
class SubscriptionsExplicitFiltering { static async run(store: IEventStore): Promise<void> { await store.subscriptions.subscribe( 'inventory-updates', 'warehouse-service', builder => builder .withEventType(SubscriptionsExplicitStockAdjusted) .withEventType(SubscriptionsExplicitStockReserved) ); }}Omit the callback to select all event types known to the C# client:
using Cratis.Chronicle;
public static class SubscriptionsExplicitNoFilter{ public static Task Run(IEventStore eventStore) => // All events from fulfillment-service outbox will be forwarded eventStore.Subscriptions.Subscribe( "all-fulfillment-events", "fulfillment-service");}import io.cratis.chronicle.EventStore
suspend fun subscribeToEverything(store: EventStore) { // No withEventType calls — subscribe to event types currently registered by this client. store.eventStoreSubscriptions.subscribe("payroll-firehose", "PayrollEventStore") { // Intentionally left unconfigured. }}import io.cratis.chronicle.EventStore;
import io.cratis.chronicle.java.EventStoreSubscriptionsServiceJavaBridge;
class SubscriptionsExplicitNoFilter { void subscribeToEverything(EventStore store) { // No withEventType calls — subscribe to event types currently registered by this client. EventStoreSubscriptionsServiceJavaBridge.subscribe(store.getEventStoreSubscriptions(), "payroll-firehose", "PayrollEventStore", builder -> { }); }}defmodule MyApp.SubscriptionsExplicitNoFilter do def run do # All events from fulfillment-service outbox will be forwarded Cratis.Chronicle.subscribe_to_event_store("all-fulfillment-events", "fulfillment-service", []) endendimport { IEventStore } from '@cratis/chronicle';
class SubscriptionsExplicitNoFilter { static async run(store: IEventStore): Promise<void> { // All events from fulfillment-service outbox will be forwarded await store.subscriptions.subscribe('all-fulfillment-events', 'fulfillment-service'); }}Which Namespaces a Subscription Observes
Section titled “Which Namespaces a Subscription Observes”Nothing needs configuring. A subscription observes the namespaces of the source event store that have the same name as a namespace of the target event store, compared case-insensitively. A subscription never creates a namespace in the source event store:
- A target namespace with no counterpart in the source is not observed. Nothing is created in the source for it.
- When the source event store later gets a namespace of that name, the subscription attaches to it without a restart.
- A namespace added to the target event store is observed at once when the source already has it.
- A name containing a comma is refused. A name like
a,ausually means the tenant header was sent twice. Such a namespace is never observed.
Pin the Generation Your Application Understands
Section titled “Pin the Generation Your Application Understands”An event type’s generation identifies a version of its schema. In the default Compatibility mode, forwarding uses the source event’s generation when the target registers it. If the target registers the event type but not that generation, forwarding selects the highest registered target generation no newer than the source event and uses the source’s migration chain to deliver it. Forwarding does not upgrade an event to a newer target generation. If the target has no registration for the event type at all, compatibility forwarding continues to send the event unchanged.
When the target registers the type but no compatible generation exists, or the source cannot migrate to it, forwarding parks the affected partition instead of retrying indefinitely. The failure message names the event type, the source generation, and the target’s registered generations. Missing pinned generations are also parked. Register the required generation in the target or add the missing downward migration in the source, then recover the parked partition as described in Subscription recovery and replay.
To keep forwarding on the generation your C# application understands, opt in per subscription with WithGenerationDelivery(EventGenerationDelivery.Pinned).
A generic WithEventType<T>() pins the generation declared by that event type. An identifier-only declaration resolves to the single generation your client knows. Use the identifier-and-generation overload when the identifier is ambiguous or you have no .NET type for that contract.
using Cratis.Chronicle;using Cratis.Chronicle.Events;using Cratis.Chronicle.Observation;
[EventType("subscription-stock-adjusted", generation: 2)][Public]public record SubscriptionStockAdjusted(int Quantity);
public static class PinnedInventorySubscription{ public static Task Register(IEventStore eventStore) => eventStore.Subscriptions.Subscribe( "inventory-updates", "warehouse-service", builder => builder .WithGenerationDelivery(EventGenerationDelivery.Pinned) .WithEventType<SubscriptionStockAdjusted>());
public static Task RegisterByIdentifier(IEventStore eventStore) => eventStore.Subscriptions.Subscribe( "inventory-updates", "warehouse-service", builder => builder .WithGenerationDelivery(EventGenerationDelivery.Pinned) .WithEventType("subscription-stock-adjusted", 2));}Register the exact generation in both stores before subscribing, and upgrade every kernel node (silo) before opting in. The kernel validates the entire pinned request before changing definitions. Missing generations or conflicting generations for one event type fail registration; waiting longer for readiness cannot resolve them.
The source forwarding observer delivers the pinned generation for live events, catch-up, replay, and retries. The inbox stores that delivered generation rather than the event’s original append generation. Protected values are decrypted using the selected source schema and encrypted again on the target append. Forwarding does not restore an erased target subject’s key. If the target later loses the pinned schema registration, forwarding fails at that event without appending it or advancing past it.
Pins and the delivery policy survive restarts, reconnects, and identical registrations. To change them, register a deliberately changed definition under the same subscription ID. The kernel updates the source observer without an unsubscribe gap. Inspect GetAll() to read GenerationDelivery and EventTypePins, alongside the id-only EventTypes.
The default is Compatibility. Existing subscriptions continue to send generation 1 in their registration and retain their forwarding behavior. The global client generation-delivery option does not opt subscriptions into pinned delivery.
Accessing Forwarded Events
Section titled “Accessing Forwarded Events”Forwarded events arrive in the target store’s inbox-{sourceEventStore} sequence. Configure the consuming reactor, projection, or reducer to observe that sequence; creating the forwarding subscription alone does not route a handler to it. The following example shows the handler body, not the source-inbox routing configuration:
using Cratis.Chronicle.Events;using Cratis.Chronicle.Reactors;
[EventType]public record SubscriptionsExplicitOrderPlaced(Guid OrderId, decimal Amount);
public class SubscriptionsExplicitIncomingOrdersReactor : IReactor{ public Task OrderPlaced(SubscriptionsExplicitOrderPlaced @event, EventContext context) => HandleIncomingOrderAsync(@event.OrderId, @event.Amount);
Task HandleIncomingOrderAsync(Guid id, decimal amount) => Task.CompletedTask;}import io.cratis.chronicle.events.EventContextimport io.cratis.chronicle.events.EventTypeimport io.cratis.chronicle.observation.Reactor
@EventTypedata class SubscriptionsExplicitOrderPlaced(val orderId: String, val amount: Double)
@Reactorclass SubscriptionsExplicitIncomingOrdersReactor { fun orderPlaced(event: SubscriptionsExplicitOrderPlaced, context: EventContext) { handleIncomingOrder(event.orderId, event.amount) }
private fun handleIncomingOrder(id: String, amount: Double) {}}import io.cratis.chronicle.events.EventContext;import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.observation.Reactor;
@EventTyperecord SubscriptionsExplicitOrderPlaced(String orderId, double amount) {}
@Reactorclass SubscriptionsExplicitIncomingOrdersReactor { void orderPlaced(SubscriptionsExplicitOrderPlaced event, EventContext context) { handleIncomingOrder(event.orderId(), event.amount()); }
private void handleIncomingOrder(String id, double amount) {}}Elixir does not support this workflow yet.import { eventType, onceOnly, reactor } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class SubscriptionsExplicitOrderPlaced { @field(String) readonly orderId: string; @field(Number) readonly amount: number;
constructor(orderId: string, amount: number) { this.orderId = orderId; this.amount = amount; }}
@reactor()class SubscriptionsExplicitIncomingOrdersReactor { // Without @handles(EventType), the method name must be the exact camelCase of the // event's class name - Chronicle discovers undecorated handlers by name, not by parameter type. @onceOnly() async subscriptionsExplicitOrderPlaced(event: SubscriptionsExplicitOrderPlaced): Promise<void> { await this.handleIncomingOrder(event.orderId, event.amount); }
private async handleIncomingOrder(orderId: string, amount: number): Promise<void> {}}For C# routing configuration, follow Subscribe Reactors to External Event Stores or Subscribe Reducers to External Event Stores. Consumers observe the source inbox, not a sequence named after the subscription ID. Check that the event reaches that inbox before diagnosing the handler or its derived view.
Removing a Subscription
Section titled “Removing a Subscription”using Cratis.Chronicle;
public static class SubscriptionsExplicitUnsubscribe{ public static Task Run(IEventStore eventStore) => eventStore.Subscriptions.Unsubscribe("orders-from-fulfillment");}import io.cratis.chronicle.EventStore
suspend fun unsubscribeFromPayroll(store: EventStore) { store.eventStoreSubscriptions.unsubscribe("payroll-inbox")}import io.cratis.chronicle.EventStore;
import io.cratis.chronicle.java.EventStoreSubscriptionsServiceJavaBridge;
class SubscriptionsExplicitUnsubscribe { void unsubscribeFromPayroll(EventStore store) { EventStoreSubscriptionsServiceJavaBridge.unsubscribe(store.getEventStoreSubscriptions(), "payroll-inbox"); }}defmodule MyApp.SubscriptionsExplicitUnsubscribe do def run do Cratis.Chronicle.unsubscribe_from_event_store("orders-from-fulfillment") endendimport { IEventStore } from '@cratis/chronicle';
class SubscriptionsExplicitUnsubscribe { static async run(store: IEventStore): Promise<void> { await store.subscriptions.unsubscribe('orders-from-fulfillment'); }}Calling Unsubscribe requests removal of the persistent definition. Once the kernel processes that removal, forwarding stops. Existing inbox events remain available to consumers; unsubscribing does not delete them.
Removing a subscription stops forwarding but does not erase its forwarding observer’s progress. Recreating the same subscription identity can resume from that retained checkpoint, including catching up on events published while it was disconnected. A new identity with no retained progress starts from the beginning of the retained source outbox.
See Subscription recovery before replaying either the forwarding observer or a consumer inbox observer; these operations have different effects.
Idempotent Registration
Section titled “Idempotent Registration”Register the same definition at application startup rather than checking whether it already exists. The stable ID lets the kernel recognize the registration:
using Cratis.Chronicle;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;
public static class SubscriptionsExplicitStartupRegistration{ public static async Task Configure(string[] args) { var builder = Host.CreateApplicationBuilder(args); builder.AddCratisChronicle(options => options.EventStore = "Quickstart");
// Safe to call on every application startup var app = builder.Build();
var eventStore = app.Services.GetRequiredService<IEventStore>();
await eventStore.Subscriptions.Subscribe( "orders-from-fulfillment", "fulfillment-service", builder => builder.WithEventType<SubscriptionsExplicitShipmentDispatched>());
await eventStore.Subscriptions.Subscribe( "inventory-from-warehouse", "warehouse-service", builder => builder.WithEventType<SubscriptionsExplicitStockAdjusted>());
await app.RunAsync(); }}import io.cratis.chronicle.ChronicleClientimport io.cratis.chronicle.ChronicleOptions
suspend fun configureSubscriptionsAtStartup() { val client = ChronicleClient(ChronicleOptions.development()) val eventStore = client.getEventStore("Quickstart")
// Safe to call on every application startup - Subscribe is idempotent by subscription id eventStore.eventStoreSubscriptions.subscribe("orders-from-fulfillment", "fulfillment-service") { builder -> builder.withEventType(SubscriptionsExplicitShipmentDispatched::class) }
eventStore.eventStoreSubscriptions.subscribe("inventory-from-warehouse", "warehouse-service") { builder -> builder.withEventType(SubscriptionsExplicitStockAdjusted::class) }}import io.cratis.chronicle.java.BlockingChronicleClient;import io.cratis.chronicle.ChronicleOptions;import io.cratis.chronicle.EventStore;
import io.cratis.chronicle.java.EventStoreSubscriptionBuilderJavaBridge;import io.cratis.chronicle.java.EventStoreSubscriptionsServiceJavaBridge;
class SubscriptionsExplicitStartupRegistration { static void configure() { BlockingChronicleClient client = BlockingChronicleClient.connect(ChronicleOptions.development()); EventStore eventStore = (EventStore) client.getEventStore("Quickstart", "Default").unwrap();
// Safe to call on every application startup - subscribe is idempotent by subscription id EventStoreSubscriptionsServiceJavaBridge.subscribe(eventStore.getEventStoreSubscriptions(), "orders-from-fulfillment", "fulfillment-service", builder -> { EventStoreSubscriptionBuilderJavaBridge.withEventType(builder, SubscriptionsExplicitShipmentDispatched.class); });
EventStoreSubscriptionsServiceJavaBridge.subscribe(eventStore.getEventStoreSubscriptions(), "inventory-from-warehouse", "warehouse-service", builder -> { EventStoreSubscriptionBuilderJavaBridge.withEventType(builder, SubscriptionsExplicitStockAdjusted.class); }); }}defmodule MyApp.Events.SubscriptionsStartupShipmentDispatched do use Cratis.Chronicle.Events.EventType, id: "subscriptions-startup-shipment-dispatched"
defstruct [:order_id]end
defmodule MyApp.Events.SubscriptionsStartupStockAdjusted do use Cratis.Chronicle.Events.EventType, id: "subscriptions-startup-stock-adjusted"
defstruct [:item_id, :delta]end
defmodule MyApp.SubscriptionsStartupApplication do use Application
alias Cratis.Chronicle.EventStoreSubscriptions.DefinitionBuilder alias MyApp.Events.{SubscriptionsStartupShipmentDispatched, SubscriptionsStartupStockAdjusted}
@impl true def start(_type, _args) do children = [ {Cratis.Chronicle.Client, connection_string: "chronicle://localhost:35000", event_store: "quickstart"} ]
supervisor = Supervisor.start_link(children, strategy: :one_for_one)
# Safe to call on every application startup — Chronicle treats a repeated # subscription id as idempotent and creates no duplicate. :ok = Cratis.Chronicle.subscribe_to_event_store( "orders-from-fulfillment", "fulfillment-service", fn builder -> DefinitionBuilder.with_event_type(builder, SubscriptionsStartupShipmentDispatched) end, [] )
:ok = Cratis.Chronicle.subscribe_to_event_store( "inventory-from-warehouse", "warehouse-service", fn builder -> DefinitionBuilder.with_event_type(builder, SubscriptionsStartupStockAdjusted) end, [] )
supervisor endendimport { ChronicleClient, ChronicleOptions, eventType, IEventStore } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class SubscriptionsExplicitStartupShipmentDispatched { @field(String) readonly orderId: string; @field(String) readonly trackingNumber: string;
constructor(orderId: string, trackingNumber: string) { this.orderId = orderId; this.trackingNumber = trackingNumber; }}
@eventType()class SubscriptionsExplicitStartupStockAdjusted { @field(String) readonly sku: string; @field(Number) readonly delta: number;
constructor(sku: string, delta: number) { this.sku = sku; this.delta = delta; }}
// Safe to call on every application startupasync function runSubscriptionsExplicitStartupRegistration(): Promise<void> { const client = new ChronicleClient(ChronicleOptions.fromConnectionString('chronicle://localhost:35000')); const eventStore: IEventStore = await client.getEventStore('Quickstart');
await eventStore.subscriptions.subscribe( 'orders-from-fulfillment', 'fulfillment-service', builder => builder.withEventType(SubscriptionsExplicitStartupShipmentDispatched));
await eventStore.subscriptions.subscribe( 'inventory-from-warehouse', 'warehouse-service', builder => builder.withEventType(SubscriptionsExplicitStartupStockAdjusted));}Identical registrations leave existing definitions unchanged. A deliberately changed registration updates the same subscription, including its exact pins and delivery policy when you opt in.
Subscription Lifecycle
Section titled “Subscription Lifecycle”The kernel persists the definition under the ID you supply and manages forwarding independently of the client connection. Subscriptions survive client disconnections and are re-established when the kernel starts, even if the consuming application is offline. Remove a subscription explicitly when the relationship is no longer needed.
Typical Setup Pattern
Section titled “Typical Setup Pattern”A common pattern is to register all subscriptions once during application startup:
using Cratis.Chronicle;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;
public static class SubscriptionsExplicitTypicalPattern{ public static async Task RegisterSubscriptions(IEventStore eventStore) { await eventStore.Subscriptions.Subscribe( "orders-from-fulfillment", "fulfillment-service", builder => builder.WithEventType<SubscriptionsExplicitShipmentDispatched>());
await eventStore.Subscriptions.Subscribe( "inventory-updates", "warehouse-service", builder => builder .WithEventType<SubscriptionsExplicitStockAdjusted>() .WithEventType<SubscriptionsExplicitStockReserved>()); }
public static async Task Configure(string[] args) { var hostBuilder = Host.CreateApplicationBuilder(args); hostBuilder.AddCratisChronicle(options => options.EventStore = "Quickstart");
var app = hostBuilder.Build(); var eventStore = app.Services.GetRequiredService<IEventStore>(); await RegisterSubscriptions(eventStore); await app.RunAsync(); }}import io.cratis.chronicle.ChronicleClientimport io.cratis.chronicle.ChronicleOptionsimport io.cratis.chronicle.IEventStoreimport io.cratis.chronicle.events.EventType
@EventTypedata class SubscriptionsExplicitShipmentDispatched(val shipmentId: String = "")
@EventTypedata class SubscriptionsExplicitStockAdjusted(val sku: String = "", val delta: Int = 0)
@EventTypedata class SubscriptionsExplicitStockReserved(val sku: String = "", val quantity: Int = 0)
suspend fun registerSubscriptions(eventStore: IEventStore) { eventStore.eventStoreSubscriptions.subscribe("orders-from-fulfillment", "fulfillment-service") { builder -> builder.withEventType(SubscriptionsExplicitShipmentDispatched::class) }
eventStore.eventStoreSubscriptions.subscribe("inventory-updates", "warehouse-service") { builder -> builder .withEventType(SubscriptionsExplicitStockAdjusted::class) .withEventType(SubscriptionsExplicitStockReserved::class) }}
suspend fun configureSubscriptionsTypicalPattern() { val client = ChronicleClient(ChronicleOptions.development()) val eventStore = client.getEventStore("Quickstart") registerSubscriptions(eventStore)}import io.cratis.chronicle.java.BlockingChronicleClient;import io.cratis.chronicle.ChronicleOptions;import io.cratis.chronicle.EventStore;
import io.cratis.chronicle.events.EventType;import io.cratis.chronicle.java.EventStoreSubscriptionBuilderJavaBridge;import io.cratis.chronicle.java.EventStoreSubscriptionsServiceJavaBridge;
@EventTyperecord SubscriptionsExplicitShipmentDispatched(String shipmentId) {}
@EventTyperecord SubscriptionsExplicitStockAdjusted(String sku, int delta) {}
@EventTyperecord SubscriptionsExplicitStockReserved(String sku, int quantity) {}
class SubscriptionsExplicitTypicalPattern { static void registerSubscriptions(EventStore eventStore) { EventStoreSubscriptionsServiceJavaBridge.subscribe(eventStore.getEventStoreSubscriptions(), "orders-from-fulfillment", "fulfillment-service", builder -> { EventStoreSubscriptionBuilderJavaBridge.withEventType(builder, SubscriptionsExplicitShipmentDispatched.class); });
EventStoreSubscriptionsServiceJavaBridge.subscribe(eventStore.getEventStoreSubscriptions(), "inventory-updates", "warehouse-service", builder -> { EventStoreSubscriptionBuilderJavaBridge.withEventType(builder, SubscriptionsExplicitStockAdjusted.class); EventStoreSubscriptionBuilderJavaBridge.withEventType(builder, SubscriptionsExplicitStockReserved.class); }); }
static void configure() { BlockingChronicleClient client = BlockingChronicleClient.connect(ChronicleOptions.development()); EventStore eventStore = (EventStore) client.getEventStore("Quickstart", "Default").unwrap(); registerSubscriptions(eventStore); }}defmodule MyApp.Events.SubscriptionsTypicalShipmentDispatched do use Cratis.Chronicle.Events.EventType, id: "subscriptions-typical-shipment-dispatched"
defstruct [:order_id]end
defmodule MyApp.Events.SubscriptionsTypicalStockAdjusted do use Cratis.Chronicle.Events.EventType, id: "subscriptions-typical-stock-adjusted"
defstruct [:item_id, :delta]end
defmodule MyApp.Events.SubscriptionsTypicalStockReserved do use Cratis.Chronicle.Events.EventType, id: "subscriptions-typical-stock-reserved"
defstruct [:item_id, :quantity]end
defmodule MyApp.SubscriptionsTypicalRegistration do @moduledoc false
alias Cratis.Chronicle.EventStoreSubscriptions.DefinitionBuilder
alias MyApp.Events.{ SubscriptionsTypicalShipmentDispatched, SubscriptionsTypicalStockAdjusted, SubscriptionsTypicalStockReserved }
def register_subscriptions do :ok = Cratis.Chronicle.subscribe_to_event_store( "orders-from-fulfillment", "fulfillment-service", fn builder -> DefinitionBuilder.with_event_type(builder, SubscriptionsTypicalShipmentDispatched) end, [] )
:ok = Cratis.Chronicle.subscribe_to_event_store( "inventory-updates", "warehouse-service", fn builder -> builder |> DefinitionBuilder.with_event_type(SubscriptionsTypicalStockAdjusted) |> DefinitionBuilder.with_event_type(SubscriptionsTypicalStockReserved) end, [] ) endendimport { eventType, IEventStore } from '@cratis/chronicle';import { field } from '@cratis/fundamentals';
@eventType()class SubscriptionsExplicitTypicalShipmentDispatched { @field(String) readonly orderId: string; @field(String) readonly trackingNumber: string;
constructor(orderId: string, trackingNumber: string) { this.orderId = orderId; this.trackingNumber = trackingNumber; }}
@eventType()class SubscriptionsExplicitTypicalStockAdjusted { @field(String) readonly sku: string; @field(Number) readonly delta: number;
constructor(sku: string, delta: number) { this.sku = sku; this.delta = delta; }}
@eventType()class SubscriptionsExplicitTypicalStockReserved { @field(String) readonly sku: string; @field(Number) readonly quantity: number;
constructor(sku: string, quantity: number) { this.sku = sku; this.quantity = quantity; }}
async function registerSubscriptionsExplicitTypicalPattern(eventStore: IEventStore): Promise<void> { await eventStore.subscriptions.subscribe( 'orders-from-fulfillment', 'fulfillment-service', builder => builder.withEventType(SubscriptionsExplicitTypicalShipmentDispatched));
await eventStore.subscriptions.subscribe( 'inventory-updates', 'warehouse-service', builder => builder .withEventType(SubscriptionsExplicitTypicalStockAdjusted) .withEventType(SubscriptionsExplicitTypicalStockReserved));}When to Use Explicit Subscriptions
Section titled “When to Use Explicit Subscriptions”Choose explicit subscriptions when the consumer owns the forwarding decision: which event types it needs, what to call the relationship, and when to remove it. Event contracts do not need to be distributed through a shared NuGet package.
For a C# application that shares contracts carrying [EventStore] attributes, implicit subscriptions can infer the source and register the types its observers consume. They do not mean that every event type in the source store is forwarded.
See Also
Section titled “See Also”-
Subscription recovery — fresh history, retained progress, and replay effects
-
Implicit Event Store Subscriptions — automatic subscription via
[EventStore]attributes -
Outbox and Inbox — conceptual explanation of how events flow between stores
-
Reactors — processing inbox events with reactors
-
Projections — building read models from inbox events