API reference — Projections
Nuvora.Nexus.Relay.Projections
Read-model projections and catch-up subscription host for Nuvora Nexus Relay
dotnet add package Nuvora.Nexus.Relay.Projections
Nuvora.Nexus.Relay.Projections
GlobalProjectionTenantSource
public sealed class GlobalProjectionTenantSource : IProjectionTenantSource
Default single-stream source: only the global (null) stream is projected.
Methods
IReadOnlyList<Guid?> TenantsToProject()
Tenants to project this cycle (null = the global stream).
ICheckpointStore
public interface ICheckpointStore
Stores per-projection catch-up checkpoints. The checkpoint is the gap-safe EventCursor (inserting transaction id + global position) of the last processed event, not the position alone — see EventCursor for why ordering on position alone can skip a late-committing event.
Methods
Task SaveAsync(string projectionName, EventCursor cursor, Guid? tenantId = null, CancellationToken cancellationToken = default(CancellationToken))
Persists the last processed cursor for a projection within a tenant (null = global).
Task<EventCursor> GetAsync(string projectionName, Guid? tenantId = null, CancellationToken cancellationToken = default(CancellationToken))
Returns the last processed cursor for a projection within a tenant (null = global), or EventCursor.Start if none.
IProjection
public interface IProjection
A read-model projection. Implementations must be idempotent: an event may be delivered more than once (at-least-once), and a rebuild replays the entire stream from position 0.
Properties
string Name { get; }
Stable name; used as the checkpoint key. Must be unique per projection.
Methods
Task ProjectAsync(EventData @event, CancellationToken cancellationToken = default(CancellationToken))
Apply a single event to the read model. Stage writes on the shared scoped DbContext and do not call SaveChanges — the projection host commits the batch and the checkpoint advance together in one transaction.
Task ResetAsync(CancellationToken cancellationToken = default(CancellationToken))
Clears this projection’s read model so a reset/rebuild can repopulate it from the start. Stage the deletes on the shared scoped DbContext and do not call SaveChanges — the reset commits the clear together with rewinding the checkpoint. Defaults to a no-op for projections that own no tables of their own.
bool Handles(string eventType)
Whether this projection handles the given (fully-qualified) event type.
IProjectionController
public interface IProjectionController
Operator control over which projections the host advances. Pausing leaves the checkpoint untouched, so resuming simply catches up from where it stopped. The default is Running for any unknown projection.
Methods
IReadOnlyDictionary<string, ProjectionRunState> Snapshot()
ProjectionRunState GetState(string projectionName)
bool IsPaused(string projectionName)
void Pause(string projectionName)
void Resume(string projectionName)
IProjectionCoordinator
public interface IProjectionCoordinator
Coordinates projection processing across multiple host instances so a projection is never advanced by two instances at once. Implementations take a lock that is scoped to the caller’s current transaction (e.g. a Postgres transaction-scoped advisory lock), so it is released automatically when that transaction commits or rolls back — including if the holder crashes. Locking is per projection name, so different projections can still progress on different instances concurrently. The default NoOpProjectionCoordinator grants every request, preserving single-instance behavior when no coordinator is configured.
Methods
Task AcquireAsync(string projectionName, CancellationToken cancellationToken = default(CancellationToken))
Blocking acquisition of the projection’s processing lock within the current transaction; waits until any in-flight batch on another instance completes. Used by administrative operations (e.g. reset) that must not race the host.
Task<bool> TryAcquireAsync(string projectionName, CancellationToken cancellationToken = default(CancellationToken))
Non-blocking attempt to take the projection’s processing lock within the current transaction. Returns false if another instance currently holds it (the caller should skip this cycle).
IProjectionDeadLetterStore
public interface IProjectionDeadLetterStore
Stores projection dead letters. The host stages a dead letter on the shared scoped context in the SAME transaction as the checkpoint advance that skips the event, so the skip and its record commit atomically.
Methods
Task AddAsync(ProjectionDeadLetter deadLetter, CancellationToken cancellationToken = default(CancellationToken))
Stages a dead letter; the surrounding unit of work commits it. Idempotent on (projection name, global position).
Task<IReadOnlyList<ProjectionDeadLetter>> GetAsync(string? projectionName = null, int maxCount = 100, CancellationToken cancellationToken = default(CancellationToken))
Returns dead letters, newest first, optionally filtered to one projection.
Task<ProjectionDeadLetter?> FindAsync(string projectionName, long globalPosition, CancellationToken cancellationToken = default(CancellationToken))
Returns the dead letter for the (projection, position) key, or null.
Task<bool> RemoveAsync(string projectionName, long globalPosition, CancellationToken cancellationToken = default(CancellationToken))
Stages removal of a dead letter (after a successful replay); the surrounding unit of work commits it. Returns false when no such dead letter exists.
IProjectionFailureStore
public interface IProjectionFailureStore
Durable store for projection event-failure counts, shared by all projection-host instances. The in-memory tally alone resets on restart and is per-instance, so a poison event could be retried MaxEventRetries × instances times (each aborting a whole batch) before being skipped; the durable count makes the retry budget global and restart-proof.
Transactional position: failure recording must happen on its OWN connection, OUTSIDE the batch transaction — the batch rolls back on failure, and an increment inside it would be erased by the very rollback it is counting.
Methods
Task ClearAsync(string projectionName, long position, CancellationToken cancellationToken = default(CancellationToken))
Removes the failure record for an event that finally succeeded or was skipped as poison.
Task ClearProjectionAsync(string projectionName, CancellationToken cancellationToken = default(CancellationToken))
Removes all durable failure tallies for a projection. Used by a reset/rebuild so the poison budget starts clean and events previously skipped as poison are re-applied rather than re-skipped.
Task<IReadOnlyDictionary<long, ProjectionFailure>> GetFailuresAsync(string projectionName, long fromPosition, long toPosition, CancellationToken cancellationToken = default(CancellationToken))
Returns the recorded failures for one projection within an inclusive global-position range (the positions of the batch about to be applied), keyed by position.
Task<int> RecordFailureAsync(string projectionName, long position, string error, CancellationToken cancellationToken = default(CancellationToken))
Increments (upserting) the failure count for the event and returns the new count. Committed immediately on an independent connection.
IProjectionManager
public interface IProjectionManager
Administrative operations over projections, e.g. resetting one to rebuild its read model.
Methods
Task ResetAsync(string projectionName, long fromPosition = 0, Guid? tenant = null, CancellationToken cancellationToken = default(CancellationToken))
Resets a projection so the host re-applies events from fromPosition (default 0 = full rebuild). Takes the projection’s processing locks — the in-process lock shared with the hosted service (so the default no-op coordinator is safe on a single instance) and the coordinator’s cross-instance lock — so it cannot race an in-flight batch, invokes the projection’s read-model clear hook, rewinds the checkpoint, and commits both together. After this returns, the running host repopulates the read model on its next cycles. tenant (null = global) scopes the rewind to that tenant’s checkpoint; the read-model clear runs under that tenant so RLS scopes the delete to the tenant’s own rows.
Task<IReadOnlyList<ProjectionDeadLetter>> GetDeadLettersAsync(string? projectionName = null, int maxCount = 100, CancellationToken cancellationToken = default(CancellationToken))
Returns dead letters (poison events the host skipped), newest first, optionally filtered to one projection. Requires an IProjectionDeadLetterStore to be registered (e.g. the EF Core one via AddRelayProjectionCheckpointsEfCore). maxCount must be positive; stores cap it (the EF Core store at 1000) to keep result sets bounded.
Task<bool> DiscardDeadLetterAsync(string projectionName, long globalPosition, CancellationToken cancellationToken = default(CancellationToken))
Permanently discards one dead-lettered event without replaying it (operator decision that the event should be dropped). Returns false when no such dead letter exists.
Task<bool> ReplayDeadLetterAsync(string projectionName, long globalPosition, CancellationToken cancellationToken = default(CancellationToken))
Replays one dead-lettered (skipped poison) event into its projection and, on success, removes the dead letter — the standard recovery path after the underlying defect is fixed. Runs under the same in-process and cross-instance locks as IProjectionManager.ResetAsync, in one transaction: the read-model write and the dead-letter removal commit atomically. Returns false when no such dead letter exists; throws (and rolls back, keeping the dead letter) when the projection still fails the event.
IProjectionPartitioner
public interface IProjectionPartitioner
Shards a single projection into parallel lanes (intra-projection partitioning). Each event is assigned to one of IProjectionPartitioner.PartitionCount lanes by a stable hash of its aggregate id, so all events for an aggregate land in the same lane and per-aggregate order is preserved; different aggregates fan out across lanes that can run concurrently. Each lane checkpoints independently under IProjectionPartitioner.CheckpointName, so a sharded host (one worker per lane, coordinated by the existing per-checkpoint advisory lock) can process a hot projection in parallel — the mechanism the reserved IPartitionedProjection marker anticipated.
Properties
int PartitionCount { get; }
Number of lanes.
Methods
int PartitionFor(EventData @event)
The lane (in [0, PartitionCount)) that owns event.
string CheckpointName(string projectionName, int partition)
The independent checkpoint key for a projection’s lane (e.g. orders#p3).
IProjectionTenantSource
public interface IProjectionTenantSource
The set of tenants the projection host catches up each cycle (each as its own independently-ordered log, checkpointed per (tenant, projection)). Soft-dependency so the projection host has no compile edge to the tenancy package: the default projects only the global stream (null); the tenancy package replaces it to enumerate the registry’s tenants.
Methods
IReadOnlyList<Guid?> TenantsToProject()
Tenants to project this cycle (null = the global stream).
InMemoryProjectionController
public sealed class InMemoryProjectionController : IProjectionController
In-memory, thread-safe projection controller (single-process). Default registration.
Methods
IReadOnlyDictionary<string, ProjectionRunState> Snapshot()
ProjectionRunState GetState(string projectionName)
bool IsPaused(string projectionName)
void Pause(string projectionName)
void Resume(string projectionName)
MultiStreamProjection
public abstract class MultiStreamProjection : IProjection
Convenience base for projections that react to several event types. Register strongly-typed handlers in MultiStreamProjection.Configure with MultiStreamProjection.On instead of switching on the raw EventData: the base maps the handled event types to their stable names (via the IEventTypeRegistry), deserializes each delivered event (via the IEventSerializer), and routes it to the matching handler. Events without a registered handler are ignored. Handlers stage their read-model writes on the shared scoped DbContext exactly like a hand-written IProjection — no storage shape is imposed — so this serves both single-stream (handlers keyed off EventData.AggregateId) and multi-stream models.
Constructors
MultiStreamProjection(IEventSerializer serializer, IEventTypeRegistry eventTypeRegistry)
Properties
IEventTypeRegistry EventTypeRegistry { get; }
Registry used to map a handler’s event type to its stable persisted name.
abstract string Name { get; }
Stable name; used as the checkpoint key. Must be unique per projection.
Methods
Task ProjectAsync(EventData @event, CancellationToken cancellationToken = default(CancellationToken))
Apply a single event to the read model. Stage writes on the shared scoped DbContext and do not call SaveChanges — the projection host commits the batch and the checkpoint advance together in one transaction.
abstract void Configure()
Register the typed handlers (via MultiStreamProjection.On) for this projection.
bool Handles(string eventType)
Whether this projection handles the given (fully-qualified) event type.
void On<TEvent>(Func<TEvent, EventData, CancellationToken, Task> handler)
Routes delivered events of type TEvent to handler.
NoOpProjectionCoordinator
public sealed class NoOpProjectionCoordinator : IProjectionCoordinator
Default IProjectionCoordinator that grants every request. Used when no real coordinator is registered, preserving the original single-host behavior. Deploy more than one projection host only with a real coordinator (e.g. the Postgres advisory-lock one).
Methods
Task AcquireAsync(string projectionName, CancellationToken cancellationToken = default(CancellationToken))
Blocking acquisition of the projection’s processing lock within the current transaction; waits until any in-flight batch on another instance completes. Used by administrative operations (e.g. reset) that must not race the host.
Task<bool> TryAcquireAsync(string projectionName, CancellationToken cancellationToken = default(CancellationToken))
Non-blocking attempt to take the projection’s processing lock within the current transaction. Returns false if another instance currently holds it (the caller should skip this cycle).
ProjectionDeadLetter
public sealed record ProjectionDeadLetter : IEquatable<ProjectionDeadLetter>
A poison event that the projection host skipped after exhausting retries, preserved durably so the skip is operationally visible and replayable (unlike a log line, it survives restarts and is queryable per projection).
Constructors
ProjectionDeadLetter(string ProjectionName, long GlobalPosition, string EventType, string Payload, string Error, DateTimeOffset OccurredAt)
A poison event that the projection host skipped after exhausting retries, preserved durably so the skip is operationally visible and replayable (unlike a log line, it survives restarts and is queryable per projection).
Properties
DateTimeOffset OccurredAt { get; init; }
When the event was dead-lettered.
long GlobalPosition { get; init; }
Global position of the skipped event.
string Error { get; init; }
The failure that made the event poison (message + exception type).
string EventType { get; init; }
Stored event type name.
string Payload { get; init; }
Raw serialized event payload (JSON).
string ProjectionName { get; init; }
Projection that skipped the event.
ProjectionFailure
public readonly record struct ProjectionFailure : IEquatable<ProjectionFailure>
A durable per-(projection, event position) failure tally.
Constructors
ProjectionFailure(int Count, string LastError)
A durable per-(projection, event position) failure tally.
Properties
int Count { get; init; }
Consecutive failed attempts recorded for the event.
string LastError { get; init; }
The most recent failure (exception type + message).
ProjectionFailureCache
public sealed class ProjectionFailureCache
Process-wide, fast in-memory cache of per-(projection, event position) consecutive failure counts (plus the last error, for the dead letter), layered over the durable IProjectionFailureStore. Used by ProjectionHostedService to detect poison events, and cleared per projection by ProjectionManager.ResetAsync so a rebuild re-applies events that were previously poison instead of skipping them. Registered as a singleton so the host and the manager share one instance.
Methods
bool TryGet(string projection, long position, out (int Count, string LastError) failure)
void ClearProjection(string projection)
Drops every in-memory tally for one projection (used by reset/rebuild).
void Merge(string projection, long position, int count, string lastError)
void RecordFailure(string projection, long position, int durableCount, string error)
void Remove(string projection, long position)
ProjectionHostedService
public sealed class ProjectionHostedService : BackgroundService
Hosted catch-up subscription that drives all registered IProjections. For each projection it reads forward from its checkpoint in global-position order, applies handled events, and advances the checkpoint. A fresh DI scope is created per projection per cycle, so one projection’s failed batch (entities staged on its scoped DbContext, then rolled back) can never leak into another projection’s commit. Multiple host instances are safe when an IProjectionCoordinator is registered: each projection is processed under a per-projection lock taken inside the batch transaction, and the checkpoint is re-read under that lock, so no two instances advance the same projection at once. With the default no-op coordinator the behavior is the original single-host one (a per-process lock shared with ProjectionManager still guards in-process resets). A repeatedly failing event becomes poison after ProjectionOptions.MaxEventRetries failed attempts: it is then skipped WITHOUT being applied (so no partial writes from a failing attempt can commit), recorded in the dead-letter store (when registered) atomically with the checkpoint advance, and logged.
Constructors
ProjectionHostedService(IServiceScopeFactory scopeFactory, IOptions<ProjectionOptions> options, ILogger<ProjectionHostedService> logger, ProjectionFailureCache failures, IRelayWakeHub? wakeHub = null)
Methods
override Task ExecuteAsync(CancellationToken stoppingToken)
This method is called when the IHostedService starts. The implementation should return a task that represents the lifetime of the long running operation(s) being performed.
ProjectionManager
public sealed class ProjectionManager : IProjectionManager
Default IProjectionManager. Runs each operation in its own DI scope (so the scoped checkpoint store, coordinator, and unit of work share one DbContext/transaction), mirroring how the host processes a cycle.
Constructors
ProjectionManager(IServiceScopeFactory scopeFactory, ProjectionFailureCache failures, ILogger<ProjectionManager> logger)
Methods
Task ResetAsync(string projectionName, long fromPosition = 0, Guid? tenant = null, CancellationToken cancellationToken = default(CancellationToken))
Resets a projection so the host re-applies events from fromPosition (default 0 = full rebuild). Takes the projection’s processing locks — the in-process lock shared with the hosted service (so the default no-op coordinator is safe on a single instance) and the coordinator’s cross-instance lock — so it cannot race an in-flight batch, invokes the projection’s read-model clear hook, rewinds the checkpoint, and commits both together. After this returns, the running host repopulates the read model on its next cycles. tenant (null = global) scopes the rewind to that tenant’s checkpoint; the read-model clear runs under that tenant so RLS scopes the delete to the tenant’s own rows.
Task<IReadOnlyList<ProjectionDeadLetter>> GetDeadLettersAsync(string? projectionName = null, int maxCount = 100, CancellationToken cancellationToken = default(CancellationToken))
Returns dead letters (poison events the host skipped), newest first, optionally filtered to one projection. Requires an IProjectionDeadLetterStore to be registered (e.g. the EF Core one via AddRelayProjectionCheckpointsEfCore). maxCount must be positive; stores cap it (the EF Core store at 1000) to keep result sets bounded.
Task<bool> DiscardDeadLetterAsync(string projectionName, long globalPosition, CancellationToken cancellationToken = default(CancellationToken))
Permanently discards one dead-lettered event without replaying it (operator decision that the event should be dropped). Returns false when no such dead letter exists.
Task<bool> ReplayDeadLetterAsync(string projectionName, long globalPosition, CancellationToken cancellationToken = default(CancellationToken))
Replays one dead-lettered (skipped poison) event into its projection and, on success, removes the dead letter — the standard recovery path after the underlying defect is fixed. Runs under the same in-process and cross-instance locks as IProjectionManager.ResetAsync, in one transaction: the read-model write and the dead-letter removal commit atomically. Returns false when no such dead letter exists; throws (and rolls back, keeping the dead letter) when the projection still fails the event.
ProjectionOptions
public sealed class ProjectionOptions
Options for the projection host.
Properties
TimeSpan IdlePollingInterval { get; set; }
Fallback polling interval used while LISTEN/NOTIFY wakes are active (the event store notifies the relay_events channel at commit, so the host is woken immediately and this safety-net poll can be much lazier than ProjectionOptions.PollingInterval). Used only when a wake listener is connected; otherwise ProjectionOptions.PollingInterval applies.
TimeSpan PollingInterval { get; set; }
Delay between polls once a projection has caught up.
bool Enabled { get; set; }
Whether the projection host is enabled.
int BatchSize { get; set; }
Number of events read per catch-up batch.
int MaxDegreeOfParallelism { get; set; }
Maximum number of distinct projections caught up concurrently per cycle. Each projection runs in its own DI scope (its own DbContext/transaction/lock), so this is safe cross-projection parallelism — it does not parallelise a single projection’s apply (that stays strictly ordered and atomic on its one shared DbContext). Default 1 (sequential, the original behaviour).
int MaxEventRetries { get; set; }
How many times a single event may fail a projection before it is treated as poison: logged as an error and skipped so it cannot block the stream forever (head-of-line blocking).
ProjectionPartitioner
public sealed class ProjectionPartitioner : IProjectionPartitioner
Default IProjectionPartitioner: assigns events to lanes with an IPartitioner over the event’s aggregate id (so a stream stays in one lane), and names each lane’s checkpoint {projection}#p{n}. Pass a ConsistentHashPartitioner to keep lane assignments stable when the lane count changes; the default is the FNV-1a hash-modulo DefaultPartitioner.
Constructors
ProjectionPartitioner(int partitionCount, IPartitioner? partitioner = null)
Properties
int PartitionCount { get; }
Number of lanes.
Methods
int PartitionFor(EventData @event)
The lane (in [0, PartitionCount)) that owns event.
string CheckpointName(string projectionName, int partition)
The independent checkpoint key for a projection’s lane (e.g. orders#p3).
ProjectionRunState
public enum ProjectionRunState
Run state of a projection as controlled by an operator.
Values
Running— The projection host advances this projection normally.Paused— The projection host skips this projection until resumed (no checkpoint movement).
Nuvora.Nexus.Relay.Projections.DependencyInjection
ProjectionServiceCollectionExtensions
public static class ProjectionServiceCollectionExtensions
Registration helpers for read-model projections and the projection host.
Methods
static IServiceCollection AddProjection<TProjection>(this IServiceCollection services)
Registers a projection implementation. Multiple projections may be registered.
static IServiceCollection AddRelayProjections(this IServiceCollection services, Action<ProjectionOptions>? configure = null)
Adds the projection host. Requires an ICheckpointStore (e.g. the EF Core one) and an IEventStore to be registered. Register projections with ProjectionServiceCollectionExtensions.AddProjection.
Nuvora.Nexus.Relay.Projections.HealthChecks
ProjectionHealthCheckBuilderExtensions
public static class ProjectionHealthCheckBuilderExtensions
Health-check registration for read-model projections.
Methods
static IHealthChecksBuilder AddRelayProjections(this IHealthChecksBuilder builder, Action<ProjectionHealthCheckOptions>? configure = null, string name = "relay-projections", IEnumerable<string>? tags = null)
Adds the projection lag health check (per-projection distance from the event-store head). Wire it into the readiness endpoint: services.AddHealthChecks().AddRelayProjections().
ProjectionHealthCheckOptions
public sealed class ProjectionHealthCheckOptions
Thresholds for ProjectionLagHealthCheck.
Properties
long DegradedLag { get; set; }
Per-projection lag (events behind the head) at which the check reports Degraded.
long DegradedVisibilityLag { get; set; }
Visibility-horizon lag (committed events not yet readable because an older write transaction is still in flight) at which the check reports Degraded. A stalled horizon freezes every projection while the per-projection lag stays at zero, so without this signal the check could report Healthy during a full stall. Default 1: any sustained horizon stall is worth surfacing.
long UnhealthyLag { get; set; }
Per-projection lag at which the check reports Unhealthy (read models badly stale).
ProjectionLagHealthCheck
public sealed class ProjectionLagHealthCheck : IHealthCheck
Health check over read-model freshness: compares each registered projection’s checkpoint to the event-store head and reports Degraded/Unhealthy when any projection falls behind the thresholds. Per-projection lags are always included in the health-report data.
Constructors
ProjectionLagHealthCheck(IServiceScopeFactory scopeFactory, IOptions<ProjectionHealthCheckOptions> options)
Methods
Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default(CancellationToken))
Runs the health check, returning the status of the component being checked.
Nuvora.Nexus.Relay.Projections.Monitoring
ProjectionLagMonitor
public sealed class ProjectionLagMonitor : BackgroundService
Periodically samples each registered projection’s lag (event-store head position minus its checkpoint) and publishes the maximum to the RelayTelemetry.ProjectionMaxLag gauge — the read-model staleness number operators alert on. Sampling failures are logged and retried next interval, never propagated.
Constructors
ProjectionLagMonitor(IServiceScopeFactory scopeFactory, IOptions<ProjectionMonitoringOptions> options, ILogger<ProjectionLagMonitor> logger)
Methods
override Task ExecuteAsync(CancellationToken stoppingToken)
This method is called when the IHostedService starts. The implementation should return a task that represents the lifetime of the long running operation(s) being performed.
ProjectionMonitoringOptions
public sealed class ProjectionMonitoringOptions
Options for ProjectionLagMonitor.
Properties
TimeSpan SamplingInterval { get; set; }
How often projection lag is sampled into the gauge.
bool Enabled { get; set; }
Whether lag sampling runs.
Nuvora.Nexus.Relay.Projections.Rebuild
AutomaticProjectionSwapper
public sealed class AutomaticProjectionSwapper : IAutomaticProjectionSwapper
Drives a shadow rebuild to completion and swaps it in automatically (zero-touch blue/green), instead of requiring an operator to call IProjectionRebuildManager.SwapAsync. Starts the rebuild, polls progress, and on ProjectionRebuildStatus.Completed performs the swap; stops without swapping if the rebuild fails or is cancelled.
Constructors
AutomaticProjectionSwapper(IProjectionRebuildManager manager, TimeProvider? timeProvider = null, TimeSpan? pollInterval = null)
Methods
Task RunAsync(string projectionName, RebuildOptions? options = null, Guid? tenant = null, CancellationToken cancellationToken = default(CancellationToken))
IAutomaticProjectionSwapper
public interface IAutomaticProjectionSwapper
Drives a shadow rebuild to completion and swaps it in automatically (zero-touch blue/green), instead of requiring an operator to call IProjectionRebuildManager.SwapAsync. Starts the rebuild, polls progress, and on ProjectionRebuildStatus.Completed performs the swap; stops without swapping if the rebuild fails or is cancelled.
Methods
Task RunAsync(string projectionName, RebuildOptions? options = null, Guid? tenant = null, CancellationToken cancellationToken = default(CancellationToken))
IPartitionedProjection
public interface IPartitionedProjection : IProjection
Opt-in marker for a projection whose events can be grouped by an independent partition key (e.g. aggregate id). The partition key lets tooling reason about which events are order-independent. NOTE on parallelism: Relay projections stage their writes on a single shared scoped DbContext and commit atomically with their checkpoint. EF Core’s DbContext is not thread-safe, so a single projection’s apply is never parallelised across partitions on that shared context (doing so would be a concurrency bug and would break the single-commit guarantee). Throughput parallelism is provided across projections via ProjectionOptions.MaxDegreeOfParallelism. This contract reserves partition semantics for that future per-partition-context work without changing today’s correctness guarantees.
Methods
string? PartitionKey(EventData @event)
Returns the partition key for an event, or null when it must keep global order.
IProjectionRebuildManager
public interface IProjectionRebuildManager
Orchestrates projection rebuilds with observable progress. In-place rebuilds rewind the live projection (the running host then re-applies); shadow rebuilds (for IRebuildableProjection) build a fresh copy and swap. Progress is derived from the projection’s checkpoint versus the head captured when the rebuild started.
Methods
Task CancelRebuildAsync(string projectionName, Guid? tenant = null, CancellationToken cancellationToken = default(CancellationToken))
Task StartRebuildAsync(string projectionName, RebuildOptions? options = null, Guid? tenant = null, CancellationToken cancellationToken = default(CancellationToken))
tenant null = the global stream; non-null rebuilds just that tenant’s read model.
Task SwapAsync(string projectionName, Guid? tenant = null, CancellationToken cancellationToken = default(CancellationToken))
Promotes a shadow rebuild to live (only for IRebuildableProjection).
Task<RebuildProgress?> GetProgressAsync(string projectionName, Guid? tenant = null, CancellationToken cancellationToken = default(CancellationToken))
Returns live progress, or null if no rebuild has been recorded for the (projection, tenant).
IProjectionRebuildStore
public interface IProjectionRebuildStore
Durable rebuild state (one row per (projection, tenant); tenant null = global), written on an independent connection so progress is observable across instances and survives restarts. Mirrors the durable failure-store pattern.
Methods
Task SetStatusAsync(string projectionName, Guid? tenant, ProjectionRebuildStatus status, string? error = null, CancellationToken cancellationToken = default(CancellationToken))
Task StartAsync(string projectionName, Guid? tenant, RebuildMode mode, long targetPosition, CancellationToken cancellationToken = default(CancellationToken))
Task<IReadOnlyList<ProjectionRebuild>> ListAsync(CancellationToken cancellationToken = default(CancellationToken))
Task<ProjectionRebuild?> GetAsync(string projectionName, Guid? tenant, CancellationToken cancellationToken = default(CancellationToken))
IRebuildableProjection
public interface IRebuildableProjection : IProjection
Opt-in capability for blue/green (zero-downtime) rebuilds. A projection that owns its read model can build a fresh copy into a shadow location while the live read model keeps serving, then atomically swap. Projections that do not implement this use in-place rebuild (reset + re-apply), which is correct but serves partial data during the rebuild.
Methods
Task DiscardShadowAsync(CancellationToken cancellationToken = default(CancellationToken))
Discards the shadow read model (rollback / cleanup after a cancelled rebuild).
Task PrepareShadowAsync(CancellationToken cancellationToken = default(CancellationToken))
Prepares an empty shadow read model (e.g. a side table) to receive the rebuild.
Task SwapAsync(CancellationToken cancellationToken = default(CancellationToken))
Atomically promotes the shadow read model to live (e.g. table rename/pointer swap).
ProjectionRebuild
public sealed record ProjectionRebuild : IEquatable<ProjectionRebuild>
Persisted rebuild state/progress for a projection within a tenant (Tenant null = global).
Constructors
ProjectionRebuild(string ProjectionName, Guid? Tenant, RebuildMode Mode, ProjectionRebuildStatus Status, long TargetPosition, DateTimeOffset StartedAt, DateTimeOffset UpdatedAt, string? Error)
Persisted rebuild state/progress for a projection within a tenant (Tenant null = global).
Properties
DateTimeOffset StartedAt { get; init; }
DateTimeOffset UpdatedAt { get; init; }
Guid? Tenant { get; init; }
ProjectionRebuildStatus Status { get; init; }
RebuildMode Mode { get; init; }
long TargetPosition { get; init; }
string ProjectionName { get; init; }
string? Error { get; init; }
ProjectionRebuildManager
public sealed class ProjectionRebuildManager : IProjectionRebuildManager
Default IProjectionRebuildManager. In-place rebuilds rewind the projection via IProjectionManager.ResetAsync (the running host re-applies), recording a rebuild row whose target is the head captured at start; progress is the live checkpoint versus that target.
Constructors
ProjectionRebuildManager(IServiceScopeFactory scopeFactory, IProjectionManager projectionManager, ILogger<ProjectionRebuildManager> logger)
Methods
Task CancelRebuildAsync(string projectionName, Guid? tenant = null, CancellationToken cancellationToken = default(CancellationToken))
Task StartRebuildAsync(string projectionName, RebuildOptions? options = null, Guid? tenant = null, CancellationToken cancellationToken = default(CancellationToken))
tenant null = the global stream; non-null rebuilds just that tenant’s read model.
Task SwapAsync(string projectionName, Guid? tenant = null, CancellationToken cancellationToken = default(CancellationToken))
Promotes a shadow rebuild to live (only for IRebuildableProjection).
Task<RebuildProgress?> GetProgressAsync(string projectionName, Guid? tenant = null, CancellationToken cancellationToken = default(CancellationToken))
Returns live progress, or null if no rebuild has been recorded for the (projection, tenant).
ProjectionRebuildServiceCollectionExtensions
public static class ProjectionRebuildServiceCollectionExtensions
Registration helpers for projection rebuild tooling.
Methods
static IServiceCollection AddRelayAutomaticProjectionSwap(this IServiceCollection services)
Registers the IAutomaticProjectionSwapper for zero-touch blue/green: it starts a shadow rebuild, polls to completion, and swaps automatically. Requires ProjectionRebuildServiceCollectionExtensions.AddRelayProjectionRebuild.
static IServiceCollection AddRelayProjectionRebuild(this IServiceCollection services)
Registers the IProjectionRebuildManager. Requires AddRelayProjections (for IProjectionManager) and an IProjectionRebuildStore (the EF Core one via AddRelayProjectionRebuildEfCore<TContext>) for durable progress.
ProjectionRebuildStatus
public enum ProjectionRebuildStatus
Lifecycle state of a rebuild.
Values
RunningCompletedCancelledFailed
RebuildMode
public enum RebuildMode
How a rebuild repopulates the read model.
Values
InPlace— Rewind the live projection and re-apply (serves partial data while rebuilding).Shadow— Build into a shadow read model, then atomically swap (requiresIRebuildableProjection).
RebuildOptions
public sealed class RebuildOptions
Options for starting a rebuild.
Properties
RebuildMode Mode { get; set; }
long SwapThreshold { get; set; }
For shadow rebuilds: how close to the live head the shadow must get before swapping.
RebuildProgress
public sealed record RebuildProgress : IEquatable<RebuildProgress>
Live progress of a rebuild, derived from the rebuild row and the projection’s checkpoint.
Constructors
RebuildProgress(string ProjectionName, Guid? Tenant, ProjectionRebuildStatus Status, long CurrentPosition, long TargetPosition, double PercentComplete)
Live progress of a rebuild, derived from the rebuild row and the projection’s checkpoint.
Properties
Guid? Tenant { get; init; }
ProjectionRebuildStatus Status { get; init; }
double PercentComplete { get; init; }
long CurrentPosition { get; init; }
long TargetPosition { get; init; }
string ProjectionName { get; init; }
RelayProjectionCli
public static class RelayProjectionCli
Minimal, dependency-free operations entry point for projection rebuilds, intended to be invoked from a host application’s Program (e.g. if (args is ["relay", ..]) return await RelayProjectionCli.RunAsync(app.Services, args);). It uses the host’s own DI (DbContext + registered projections), so there is no privileged database backdoor. Commands:
relay projections listrelay projections status <name>relay projections rebuild <name> [--shadow|--in-place]relay projections replay-dead-letters <name> <position>
Methods
static Task<int> RunAsync(IServiceProvider services, string[] args, TextWriter? output = null)