Skip to content

Use this LLM Friendly Docs as an MCP server for Marten.

The search box in the website knows all the secrets—try it!

For any queries, join our Discord Channel to reach us faster.

JasperFx Logo

JasperFx provides formal support for Marten and other JasperFx libraries. Please check our Support Plans for more details.

Async Projections Daemon ​

The Async Daemon is the nickname for Marten's built in asynchronous projection processing engine. The current async daemon from Marten V4 on requires no other infrastructure besides Postgresql and Marten itself. The daemon itself runs inside an IHostedService implementation in your application. The daemon is disabled by default.

The Async Daemon will process events in order through all projections registered with an asynchronous lifecycle.

First, some terminology:

  • Projection -- a projected view defined by the IProjection interface and registered with Marten. See also Projections.
  • Projection Shard -- a logical segment of events that are executed separately by the async daemon
  • High Water Mark -- the furthest known event sequence that the daemon "knows" that all events with that sequence or lower can be safely processed in order by projections. The high water mark will frequently be a little behind the highest known event sequence number if outstanding gaps in the event sequence are detected.

There are only two basic things to configure the Async Daemon:

  1. Register the projections that should run asynchronously
  2. Turn the daemon on with AddAsyncDaemon(DaemonMode.Solo) or AddAsyncDaemon(DaemonMode.HotCold) (more on what these options mean later in this page)

As an example, this configures the daemon to run in the current node with a single active projection:

cs
var host = await Host.CreateDefaultBuilder()
    .ConfigureServices(services =>
    {
        services.AddMarten(opts =>
            {
                opts.Connection("some connection string");

                // Register any projections you need to run asynchronously
                opts.Projections.Add<TripProjectionWithCustomName>(ProjectionLifecycle.Async);
            })
            // Turn on the async daemon in "Solo" mode
            .AddAsyncDaemon(DaemonMode.Solo);
    })
    .StartAsync();

snippet source | anchor

Likewise, we can configure the daemon to run in HotCold mode like this:

cs
var host = await Host.CreateDefaultBuilder()
    .ConfigureServices(services =>
    {
        services.AddMarten(opts =>
            {
                opts.Connection("some connection string");

                // Register any projections you need to run asynchronously
                opts.Projections.Add<TripProjectionWithCustomName>(ProjectionLifecycle.Async);
            })
            // Turn on the async daemon in "HotCold" mode
            // with built in leader election
            .AddAsyncDaemon(DaemonMode.HotCold);
    })
    .StartAsync();

snippet source | anchor

How the Daemon Works ​

How Aggregation Works

First off, in production usage, events should be continuously flowing into the event storage within a Marten-ized PostgreSQL database. Part of the Async Daemon is a little agent that constantly watches your database to know where the high water mark is: the highest assigned event sequence number where it's safe to process asynchronous projections and subscriptions to. At the same time, the async daemon always knows what the current progression by event sequence number is for each individual asynchronous projection. Assuming that the "high water mark" is higher than the current progression point, the daemon loads the next page of events above that projection's progression and applies it, then records the new progression in the same transaction.

Solo vs. HotCold ​

There are three ways to run the daemon:

  1. Solo -- the daemon will be automatically started when the application is bootstrapped and all projections and projection shards will be started on that node. The assumption with Solo is that there is never more than one running system node for your application.
  2. HotCold -- the daemon uses a built in leader election function, an advisory lock, to ensure that each projection is running on exactly one running process. With a single database there is one lock per projection shard. With separate databases for multi-tenancy there is one lock per database, so whichever node holds it runs all of that database's projections (see Projection Distribution). HotCold is failover only. HotCold can do some load distribution through intentionally random assignment polling, but you cannot count on a "fair" distribution.
  3. Wolverine-managed distribution -- if you have more than one node, this is what we recommend. Wolverine spreads the projections and subscriptions evenly across the running nodes, places them by capacity, keeps blue/green deployments apart, keeps related shards together, lets an operator pause, restart or pin an agent, and tells you why it could not place one. This mode is also more resilient to projection interruptions or a single projection somehow hitting the dreaded ProgressionProgressOutOfOrderException that can sometimes happen when node clusters are being started or stopped. See Distributing Work with Wolverine below.

Marten itself will not grow its own distribution of async projections across nodes; that job belongs to Wolverine.

DaemonMode has two more values. Disabled is the default when you never call AddAsyncDaemon(): nothing runs, and Marten writes a warning to the console when the store is built if any projection is registered as Async. ExternallyManaged means another system runs the async projections and subscriptions, which is how Wolverine-managed distribution works. The store itself hosts no projection coordinator and starts no shards, the same as Disabled, but it doesn't warn, because the projections do run somewhere. Integrations such as Wolverine set this mode; application code shouldn't need to. Under ExternallyManaged, ForceAllMartenDaemonActivityToCatchUpAsync() only waits for the externally run shards to reach the high water mark instead of driving them itself.

By default the HotCold leadership lock is session-scoped (pg_try_advisory_lock), so the session holding it keeps no transaction open while it is the leader. Set options.Events.UseAdvisoryLockTransaction to true to use a transaction-scoped lock (pg_try_advisory_xact_lock) instead. That is the better fit behind PgBouncer in transaction pooling mode, which can hand a session-scoped lock's server connection to another client, but it means the leader keeps a transaction open for as long as it holds leadership.

cs
builder.Services.AddMarten(opts =>
{
    opts.Connection(connectionString);

    // Opt into the transaction-scoped leadership lock
    opts.Events.UseAdvisoryLockTransaction = true;
})
.AddAsyncDaemon(DaemonMode.HotCold);

snippet source | anchor

Leadership lock monitoring ​

Marten also monitors the leadership lock, so that it notices when the connection holding the lock is lost — a database restart or a fail-over. Without monitoring, HasLock keeps reporting true after the lock is gone, and because the leadership loop only tries to re-attain a lock when HasLock says it does not have one, two nodes can end up running the same projection. That is why monitoring is on by default:

cs
builder.Services.AddMarten(opts =>
{
    opts.Connection(connectionString);

    // Opt OUT of leadership lock monitoring. Only do this knowing the failure mode above.
    opts.Events.UseMonitoredAdvisoryLock = false;
})
.AddAsyncDaemon(DaemonMode.HotCold);

snippet source | anchor

Monitoring used to be visible in the database as a long-running SELECT pg_catalog.pg_sleep(60), which some monitoring tools reported as load. On a data source Marten owns that is no longer how it works: the monitor waits client-side for a notification instead, and the backend simply sits idle for up to a minute at a time. It still consumes no database resources.

Releasing the locks at shutdown is bounded by Projections.StopAndDrainTimeout

9.46. Monitoring parks the lock connection in a one-minute wait between

checks, and a session-scoped lock multiplexes several held locks onto one such connection, so the last release on a connection could end up waiting out that whole window — which made some host stops take 60 or 120 seconds, with nothing logged (#5567). The releases now run concurrently and stop being waited on once the timeout is up; anything still outstanding finishes in the background and is logged as a warning naming how many locks it was still waiting on. The practical consequence of hitting that timeout is that leadership of those projections cannot move to another node until the releases complete, so a rolling deployment may see a projection sit unowned for up to a minute. Before 9.46 the stop simply blocked for the same period instead.

TIP

Marten's gap detection recognizes its own leadership lock connections and never counts them as possible appenders, so a transaction-scoped lock — whether currently held or leaked from a host that has already been torn down — does not stall the high water mark. Before 9.23 it could: one such session was enough to pin the mark for every later daemon in that process, surfacing as WaitForNonStaleProjectionDataAsync timing out and a repeating Daemon high water detection is holding before the sequence gap log. If you are on an older version and see that, UseAdvisoryLockTransaction = false is the workaround, since a session-scoped lock holds no transaction to be seen.

Sequence Gaps and the High Water Mark 9.23 ​

The high water mark is the point below which the daemon knows every event is committed and safely ordered. It advances contiguously, so it stops under any hole in the event sequence.

Most holes fill in within milliseconds — they are simply appends that have drawn a sequence number and not yet committed. Some never fill: a rolled-back SaveChangesAsync, or an optimistic-concurrency loser, burns its sequence numbers permanently, because PostgreSQL sequences are non-transactional. The daemon cannot tell those two apart by looking at the hole, so it asks a different question: is any transaction still running that could have reserved it? While the answer is yes, the mark holds. Once no such transaction remains, the gap is proven dead and the daemon skips the entire dead span in one step, recording it in mt_high_water_skips.

This is why the daemon holds rather than guessing, and why it never skips past events that later commit. It also means an open transaction that will never commit is the thing that can stall it. That covers sessions parked idle in transaction — the daemon rules out any session that has provably executed nothing since before the gap's sequence numbers were handed out, and its own leadership lock connections regardless. The evidence supporting that reasoning is durable, so it survives daemon restarts, deploys and shard rebalancing.

If something else holds an advisory lock on a connection that only holds the lock and never appends events, like Wolverine's transaction-scoped durability pass lock, you can tell the daemon to rule those sessions out too 10.0:

cs
// The full 64-bit key, exactly as passed to pg_advisory_xact_lock(). A session holding
// it is still counted if it has written anything at all.
opts.Projections.IgnoreAdvisoryLockHoldersForGapDetection(lockKey);

If you want a bounded escape hatch anyway — against, say, a leaked application session that holds an open transaction forever — set a cap:

cs
// Skip a stale gap once it has been stuck this long even if a transaction that
// could still fill it appears to be alive. Null (the default) never knowingly
// skips past a live appender.
opts.Projections.SkipStaleGapsDespiteLiveTransactionsAfter = 5.Minutes();

Use it deliberately: past the cap the daemon skips on a suspicion of deadness, so async projections and subscriptions that are already past an append that commits inside the skipped range will not see it (see Events that commit late for what Marten does about that). PostgreSQL's own idle_in_transaction_session_timeout is usually the better backstop, since it removes the cause rather than working around it. Note that it will also kill Wolverine's transaction-scoped listener locks if you use them.

To recover a mark that is stuck for any other reason, AdvanceHighWaterMarkToLatestAsync() moves it to the highest committed sequence:

cs
await store.Advanced.AdvanceHighWaterMarkToLatestAsync(CancellationToken.None);

WARNING

AdvanceHighWaterMarkToLatestAsync() is a manual override. Async projections and subscriptions will not see anything still in flight below the new mark when it commits, so reach for it when you have established that a gap is genuinely dead and not as routine maintenance.

With UseTenantPartitionedEvents, each tenant has its own mark. The overload taking a tenant id advances that tenant's mark, and the overload without one advances every tenant's mark.

Tools that work against any Critter Stack store, such as CritterWatch, use the store-agnostic form on IEventStore instead (added in JasperFx 2.92.0). It also has a read-only preview, so you can see what an advance would skip before you do it:

cs
IEventStore eventStore = store;
var database = (await eventStore.AllDatabases()).Single();

// Read-only: the stored mark, the committed ceiling, and how many sequence numbers would be skipped
var previews = await eventStore.PreviewHighWaterAdvanceAsync(database, tenantId: null, ct);

// Refuses (RefusedStaleExpectation) if the mark moved after the preview
var results = await eventStore.AdvanceHighWaterMarkToLatestAsync(
    database, tenantId: null, expectedCurrentMark: previews[0].CurrentMark, ct);

snippet source | anchor

These methods are stricter about the tenant than the Advanced methods:

  • Without per-tenant partitioning, every tenant shares a database's single mark. Naming a tenant throws an error, because it would otherwise advance every tenant's events.
  • With partitioning, a null tenant selects every tenant's mark. expectedCurrentMark then needs a named tenant.

Events that commit late 10.0 ​

Every skip is recorded in mt_high_water_skips, with the reason for it and the sequence numbers inside the skipped range that had no committed event yet. For an hour after a skip, the daemon checks those sequence numbers every 10 seconds. An event that turns up there is one that async projections and subscriptions already past it did not see. For each one the daemon:

  • records it in mt_high_water_late_events with its sequence, tenant, stream and event type,
  • logs a warning and counts it in the marten.daemon.late_events metric, tagged by event type, tenant and skip reason,
  • rebuilds the event's stream in every async single-stream projection that handles that event type, through the shard that runs the projection, the same way as RebuildSingleStreamAsync(). Side effects do not run in that rebuild.

Other projections and subscriptions are not repaired, because they cannot safely take an event out of order. Use the ledger to decide whether to rebuild them.

A range skipped because no transaction that could fill it was alive should never fill. If one does, the daemon logs it as an error, because that is a bug in Marten's high water detection. Please report it.

The window and the interval are configurable, and this needs opts.Events.EnableAdvancedAsyncTracking (on by default):

cs
opts.Projections.LateEventDetectionWindow = 1.Hours();
opts.Projections.LateEventProbeInterval = 10.Seconds();

Projection Distribution ​

With HotCold, Marten takes one leadership lock per projection (or, with separate databases for multi-tenancy, one per database, so that a node holds all of a database's projections and fewer connections). Whichever node grabs a lock first runs that work. Since every node races for every lock, the first node to start up usually ends up with all of it, and the others sit idle until it goes away. That is failover, not load distribution.

Distributing Work with Wolverine ​

If you run more than one node, use Wolverine-managed distribution instead of HotCold:

cs
builder.Services.AddMarten(opts =>
{
    // your configuration...
})
.IntegrateWithWolverine(opts =>
{
    opts.UseWolverineManagedEventSubscriptionDistribution = true;
});

Wolverine's leader assigns every projection and subscription shard to a node and keeps them spread evenly as nodes come and go. It can also place work by node capacity, keep blue/green versions of a projection on the right nodes, keep related shards together, let an operator pause, restart or pin a shard, and report why a shard could not be placed. See Projection/Subscription Distribution in the Wolverine docs for the details.

To monitor and manage projections and subscriptions across the whole fleet, use CritterWatch. Wolverine-managed distribution works without CritterWatch too.

Daemon Connection Governors 9.13 ​

Every running projection or subscription agent opens its own database session both to load pages of events and to commit each batch of projected documents plus its progression update. On a wide store — many projections, or per-tenant event partitioning where the daemon runs one agent per (projection × tenant) — an unbounded daemon can drive the connection pool's high-water mark toward the total agent count even though only a handful of loads or writes are ever active at the same instant.

Marten therefore governs the daemon's concurrent database work out of the box with two caps, both applied per daemon instance (one daemon per store × database):

cs
// These are the defaults — you don't need to set either one
opts.Projections.MaxConcurrentEventLoadsPerDatabase = 4;
opts.Projections.MaxConcurrentBatchWritesPerDatabase = 4;
  • MaxConcurrentEventLoadsPerDatabase (default 4) caps how many agents may load pages of events from the database concurrently. All of a daemon's agents share one throttle, collapsing the steady-state connection footprint to O(databases) with no measured throughput cost.
  • MaxConcurrentBatchWritesPerDatabase (default 4) caps how many projection batches may execute their SQL (the commit round trip) concurrently against one database.

Setting either knob to zero or a negative number disables that governor and restores the historical unbounded behavior. The governors apply to continuous (running daemon) work only — projection rebuilds are capped separately by MaxConcurrentRebuildsPerDatabase, which derives its default from the Npgsql connection pool size. See Capping Rebuild Concurrency.

Bounding Daemon Memory with Per-Tenant Agents 9.58 ​

With per-tenant event partitioning the daemon runs one agent per (projection × tenant). Each of those agents loads its own pages of events and builds its own batch of projected documents, so the memory the daemon holds grows with the number of tenant agents running on a node. With a few hundred tenant agents starting at once, typically when a projection is being rebuilt for every tenant, that can exhaust the memory of the process.

The connection governors above do not bound this memory:

  • MaxConcurrentBatchWritesPerDatabase is taken only after a batch has been built. Every agent can load its events, run its projection and serialize every document, then wait for a write slot holding the finished batch.
  • Both governors apply per database. On a store with many databases, the number of agents allowed to work at once on one node is still large.
  • Lowering BatchSize does not help when one event fans out to many documents, because a page is bounded by its event count and not by the work inside it.

Marten has two opt-in settings for this. Both are off by default, and both apply only to agents that run for one tenant. A store without per-tenant partitioning already builds one batch at a time per projection and is unaffected.

The tenant load budget ​

TenantLoadBudget is the recommended setting. It gives all of a store's tenant agents on a node one shared budget of events that may be loaded but not yet committed, across every projection and every database of the store:

cs
var builder = Host.CreateApplicationBuilder();
builder.Services.AddMarten(opts =>
{
    opts.Connection(builder.Configuration.GetConnectionString("marten"));

    opts.Events.TenancyStyle = TenancyStyle.Conjoined;
    opts.Events.UseTenantPartitionedEvents = true;

    // The most events this store's tenant agents may hold on this node,
    // loaded but not yet committed. Zero or negative (the default) is unbounded
    opts.Projections.TenantLoadBudget = 2000;

    // Hand out no new pages once the process reaches this fraction of
    // the GC's high memory load threshold. 0.9 is the default
    opts.Projections.TenantLoadMemoryThreshold = 0.9;
});

snippet source | anchor

With a budget set:

  • An agent reserves a page before it loads. It reserves BatchSize events, trims the reservation to the number of events the page really held, and gives it back when the page commits.
  • Loads go straight through while there is room. If the budget has room and no agent is waiting, nothing is delayed. A store that is caught up does not notice the budget.
  • Tenants take turns when there is not. Agents wait in a first in, first out line. Each is let in for one page, then goes to the back of the line, so every tenant keeps moving and none falls behind indefinitely. The agent at the head of the line is never passed by one that needs less room.
  • A waiting agent is still running. It stays assigned and keeps reporting its health, so neither Marten's own daemon nor Wolverine-managed distribution stops or reassigns it. It just does not load.
  • The store always makes progress. A reservation is always granted when nothing at all is in flight. A budget smaller than one page slows the store down to one page at a time, and does not stop it.

TenantLoadMemoryThreshold is a second limit on top of the event count. It is a fraction of the garbage collector's high memory load threshold (GCMemoryInfo.HighMemoryLoadThresholdBytes). Once the process reaches it, no new pages are handed out until the events already in flight have been committed, whatever the budget still allows. The default is 0.9. Set it to null to use the event budget alone. It has no effect unless TenantLoadBudget is set.

WARNING

Set TenantLoadBudget in your AddMarten() configuration. The budget is read once per store per process, when the first tenant agent starts, and a later change is ignored.

The budget covers continuously running projections and rebuilds, including composite projection rebuilds, where it also bounds the built batches because each page keeps its reservation until it has been processed.

Choosing a budget ​

Think of the budget as a number of pages, where a page is your projection's BatchSize (500 by default). A budget of a few pages is usually the right place to start.

These measurements are from the TenantRebuildStress project in the Marten repository. It rebuilds a two-stage composite projection for 24 tenants at once with a BatchSize of 500, where each page builds about 3,000 upserts of 8 KB documents:

ConfigurationPeak memory (workstation GC)Rebuild time
No budget8,215 MB8.6 s
TenantLoadBudget = 4000 (8 pages)6,198 MB6.7 s
TenantLoadBudget = 2000 (4 pages)1,185 to 1,410 MB7.6 to 7.9 s
TenantLoadBudget = 500 (1 page)351 MB17.8 s
SerializeTenantProjectionBatches355 MB16.4 s

Four pages kept the rebuild at about the speed of no budget with roughly a sixth of the memory. One page used the least memory and took about twice as long. Eight pages was already close to no budget at all.

Under server GC the same runs peaked at 5,766 MB with no budget, 3,819 MB with a budget of 2000, and 2,138 MB with a budget of 500. Server GC keeps more memory by design, so the absolute numbers are higher, but the budget still reduces the footprint.

These numbers come from a laptop with about ±20% variance between runs. Use them to compare settings, and measure your own system in a container with its real memory limit before you settle on a value.

One batch at a time per projection ​

SerializeTenantProjectionBatches is the simpler and blunter of the two settings:

cs
opts.Projections.SerializeTenantProjectionBatches = true;

When it is on, the tenant agents of one projection build and commit their batches one at a time on a node, in turn, across every database of the store. The node holds one built batch per projection instead of one for every running tenant agent.

  • Each agent's pages stay in order, and an agent has at most one batch waiting for its turn.
  • Turns are first in, first out, so the queue rotates through the tenants.
  • A composite projection takes one turn per page for all of its members.
  • A page that is still waiting for its turn when the agent is stopped is abandoned, and is picked up by whichever node runs the agent next. A page that has started runs to the end.

The trade-off is throughput. One projection's tenants no longer build in parallel on a node, in continuous mode as well as in rebuilds. It also bounds only the built batches: every waiting agent can still hold up to MaximumHopperSize (two pages, 2 x BatchSize, by default) loaded events.

Prefer TenantLoadBudget. A budget of one page uses about the same memory as the queue, a larger budget gives back the speed, and the budget still helps under server GC, where the queue saved little. Turning both on gains nothing over the queue alone.

What is not governed ​

  • A one-off CatchUpAsync() call loads one page at a time and does not go through the budget.
  • With RebuildFlushThreshold set, a rebuild keeps snapshots in memory across pages until they are flushed. Neither setting bounds that memory.
  • Event subscriptions build no projection batch, so SerializeTenantProjectionBatches does not apply to them.

Graceful Shutdown and the Drain Timeout 9.20 ​

When a projection or subscription shard is stopped, the daemon does not simply cancel it. It first tries to drain the agent: let the in-flight page of events finish being applied, then flush the shard's progression row so the next start picks up exactly where this one left off. StopAndDrainTimeout bounds how long the daemon waits for that drain on a single shard:

cs
// The default is 5 seconds
opts.Projections.StopAndDrainTimeout = 30.Seconds();

The bound applies to every stop path: stopping one agent, stopping all agents (the SIGTERM/host shutdown path), and the internal stop-if-already-running replacement that happens when an agent is reassigned.

What a drain actually does 9.47 ​

A drain is deliberately not "process everything that is queued". Three things happen:

  1. The page or range in flight is allowed to finish, and its progression is committed.
  2. Pages or ranges still queued behind it are skipped. They are not lost — the next owner of the shard resumes them from the committed progression row.
  3. If the in-flight page is still running when StopAndDrainTimeout expires, it is cancelled, and its transaction — the projection or subscription writes plus the progression update — rolls back together. That page is processed again by whichever node runs the shard next.

This is what makes shutdown bounded rather than proportional to the backlog, and it is what stops a node that has lost a shard's lock from continuing to apply its backlog alongside the new owner. That overlap used to end in ProgressionProgressOutOfOrderException and a Stopped shard, because progression is written with an optimistic last_seq_id guard and only one of the two nodes can win it.

WARNING

A page slower than StopAndDrainTimeout is re-processed on every shutdown and every rebalance. Delivery has always been at-least-once, so this is not a new guarantee — but duplicates become far more likely for slow pages. Anything a projection or subscription does outside the store session does not roll back with the cancelled transaction: HTTP calls, or sends that bypass the transactional outbox. If your pages are legitimately slow, raise StopAndDrainTimeout rather than discover this as duplicate processing.

Why you would raise it. So that in-flight pages finish instead of being cancelled and re-processed. Raise the timeout when pages legitimately take longer than five seconds — a large BatchSize, expensive projection code, heavy rebuild load, or a slow or contended database. A shard whose pages never finish inside the bound makes no forward progress across a restart loop: every attempt is cancelled and rolled back, and the next one starts from the same place. This is most visible shutting down a host with a large agent universe: a database-per-tenant deployment with thousands of (projection × tenant) shards all draining inside a Kubernetes termination grace window.

TIP

A per-shard bound is only useful if the process lives long enough to spend it. Match a raised StopAndDrainTimeout with the host's own HostOptions.ShutdownTimeout and, on Kubernetes, the pod's terminationGracePeriodSeconds.

Why you would lower it. A deployment that would rather cut a wedged shard loose quickly and take the progression replay hit — to keep node failover and reassignment latency low, for instance — can set it below the default.

Opting out. Timeout.InfiniteTimeSpan, or any non-positive value, removes the separate bound so the drain is limited only by the daemon's own cancellation. Be aware that this means a genuinely wedged shard can hold up shutdown indefinitely.

Waking the Daemon with LISTEN/NOTIFY 9.0 ​

By default the async daemon discovers new events by polling the high water mark. If you want projections and subscriptions to react to an append almost immediately, opt into PostgreSQL LISTEN/NOTIFY:

cs
builder.Services.AddMarten(opts =>
{
    opts.Connection("some connection string");

    // Off by default
    opts.Events.UseListenNotifyForEventAppends = true;
});

snippet source | anchor

With the flag on, every SaveChangesAsync() that appends events also issues a NOTIFY on the mt_events_appended channel, and the daemon holds a dedicated connection that LISTENs on it and wakes the high water detection as soon as a notification arrives. Polling stays in place as the safety net: if the listening connection cannot be established or is lost, the daemon falls back to timed polling and reconnects on a later cycle, so a missed notification only costs latency, never events.

Things to be aware of:

  • The daemon needs one extra, long-lived connection per database for the LISTEN.
  • LISTEN is a session-level feature, so the listening connection cannot go through PgBouncer in transaction pooling mode. Connect it to the database directly or use session pooling.
  • The flag does nothing for events appended by other tools that do not send the NOTIFY; those are still picked up by polling.

Daemon Settings Reference ​

The daemon's timing, leadership and parking settings are all on opts.Projections, where opts is the StoreOptions passed to AddMarten(). This sample sets each of them to its default, except for DaemonLockId:

cs
// Every value below is the default, except DaemonLockId
opts.Projections.FastPollingTime = 250.Milliseconds();
opts.Projections.SlowPollingTime = 1.Seconds();
opts.Projections.StaleSequenceThreshold = 3.Seconds();
opts.Projections.UseTransactionEvidenceForGapSkipping = true;
opts.Projections.HealthCheckPollingTime = 5.Seconds();
opts.Projections.HighWaterStalenessThreshold = 30.Seconds();
opts.Projections.HighWaterProgressStallThreshold = 2.Minutes();

// HotCold leadership. LeadershipPollingTime is in milliseconds
opts.Projections.LeadershipPollingTime = 5000;
opts.Projections.AgentPauseTime = 1.Seconds();

// The default is 4444. Give every application that shares a database its own value
opts.Projections.DaemonLockId = 5150;

// Parking guard rails and replay batching
opts.Projections.Errors.ParkedTripMinimum = 20;
opts.Projections.Errors.ParkedTripFraction = 0.5;
opts.Projections.Errors.ParkedReplayBatchSize = 10;

snippet source | anchor

SettingDefaultWhat it does
FastPollingTime250 millisecondsHow long the high water agent waits before polling again after the mark moved.
SlowPollingTime1 secondHow long the high water agent waits before polling again when it is caught up, or after a failed poll.
StaleSequenceThreshold3 secondsHow long a gap in the event sequence has to sit unfilled before the high water agent considers skipping it. See Sequence Gaps and the High Water Mark.
UseTransactionEvidenceForGapSkippingtrueBefore skipping a stale gap, check PostgreSQL for a transaction that could still fill it, and hold while there is one. false goes back to skipping on time alone.
HealthCheckPollingTime5 secondsHow often the high water agent's watchdog runs. The projection coordinator also starts a paused shard again once it has been paused for longer than this.
HighWaterStalenessThreshold30 secondsHow long the high water agent's poll loop can go without finishing a cycle before the watchdog restarts it. This measures the loop, not the mark, so a quiet store is never stale.
HighWaterProgressStallThreshold2 minutesHow long the mark can stay still while there are committed events above it before the watchdog restarts the high water agent. A restart never moves the mark. null turns this off.
LeadershipPollingTime5000Milliseconds between the projection coordinator's passes, in which it tries to take leadership locks and starts any shard that isn't running.
AgentPauseTime1 secondUsed instead of LeadershipPollingTime between passes while any shard is paused.
DaemonLockId4444The advisory lock id HotCold leadership is built on. With one database, each shard's lock is this value plus a hash of the schema name and shard name. With several databases, it is the lock for each database as it is. Give every application that shares a database its own value.
WakeupnullAn IDaemonWakeup that can end the high water agent's wait between polls early. With null, the agent just waits. opts.Events.UseListenNotifyForEventAppends replaces whatever is here with Marten's LISTEN listener when the daemon starts. See Waking the Daemon with LISTEN/NOTIFY.
OtelPrefix"marten"The prefix of the high water agent's span and its skipping counter, {OtelPrefix}.daemon.highwatermark and {OtelPrefix}.daemon.skipping. It doesn't change the per-shard spans and metrics. See Open Telemetry and Metrics.

Three more settings on opts.Projections.Errors tune parking:

SettingDefaultWhat it does
ParkedTripMinimum20The fewest identities one batch has to fail before the systemic failure trip pauses the shard instead of parking them.
ParkedTripFraction0.5The share of a batch's identities that has to fail, more than this, before that trip pauses the shard.
ParkedReplayBatchSize10The most parked identities a "replay all" or "replay oldest N" puts into one batch of the shard.

MaxParkedIdentitiesPerShard (default 1,000) is on the same object. The connection governors, the tenant load budget, StopAndDrainTimeout and the late event settings are described in their own sections of this page.

Daemon Logging ​

The daemon logs through the standard .NET ILogger registered in your application's DI container. When a projection shard starts and that projection can't park a failing identity, the daemon logs why, and that a failing event will pause the shard instead.

By default in Marten 10, an event that fails in your projection code parks its identity rather than being skipped, and the parked identity is recorded in the mt_parked_identities table along with the error. An event is only recorded in the DeadLetterEvent storage (the mt_doc_deadletterevent table), with its exception, when it's actually dropped: when you've configured the daemon to skip errors, or when you discard a parked identity and an event still fails. See Error Handling.

PgBouncer ​

If you use Marten's async daemon feature and PgBouncer, make sure you're aware of some Npgsql configuration settings for best usage with Marten. Marten's async daemon uses PostgreSQL Advisory Locks to help distribute work across an application cluster, and PgBouncer can throw off that functionality without the connection settings in the Npgsql documentation linked above.

TIP

If you are also using Wolverine, its ability to distribute Marten projections and subscriptions does not depend on advisory locks and also spreads work out more evenly through a cluster.

Error Handling ​

In all examples, opts is a StoreOptions object.

A transient failure while the daemon builds a projection batch, like a dropped connection, a deadlock, a command timeout or an exhausted connection pool, goes through the daemon's own Polly pipeline first: by default the batch is built again up to 3 times, and then the shard pauses. Replace that pipeline with opts.ConfigureDaemonPolly(...), and start the builder with AddMartenDaemonBatchDefaults() to keep the default and add to it. opts.ConfigureDaemonPolly(_ => { }) turns the retries off. See The async daemon builds a failed batch again.

When your own projection code fails on an event, you choose what the daemon does: park the one failing identity, pause the projection, or skip the event. Marten 10 parks by default. Parking, its guard rails, transient retries and replaying or discarding a parked identity are covered in Parking a Failing Projection Identity.

The sample below turns skipping on for continuous runs:

WARNING

Setting SkipApplyErrors and SkipSerializationErrors to true, as this sample does, turns parking off and goes back to skipping failed events the way Marten 9 did. Leave those two lines out if you want to keep Marten 10's default of parking a failing identity.

cs
using var host = await Host.CreateDefaultBuilder()
    .ConfigureServices(services =>
    {
        services.AddMarten(opts =>
            {
                // connection information...

                opts.Projections.Errors.SkipApplyErrors = true;
                opts.Projections.Errors.SkipSerializationErrors = true;
                opts.Projections.Errors.SkipUnknownEvents = true;

                opts.Projections.RebuildErrors.SkipApplyErrors = false;
                opts.Projections.RebuildErrors.SkipSerializationErrors = false;
                opts.Projections.RebuildErrors.SkipUnknownEvents = false;
            })
            .AddAsyncDaemon(DaemonMode.HotCold);
    }).StartAsync();

snippet source | anchor

OptionDescriptionContinuous DefaultRebuild Default
ApplyErrorsWhat happens when projection code (not Marten or PostgreSQL) throws on an event: Park, Pause or SkipParkPause
SerializationErrorsWhat happens when an event can't be deserialized or upcast: Park, Pause or SkipPark*Pause
SkipUnknownEventsShould unknown event types be skipped by the daemon?TrueFalse

* Only a single-stream projection parks on a serialization error. A multi-stream projection needs the event's body to know which identity it belongs to, so it pauses instead.

SkipApplyErrors and SkipSerializationErrors still work: true means Skip and false means Pause.

Skip writes a DeadLetterEvent for the event and moves on. Pause stops that one projection. During a rebuild, any error that isn't skipped stops the rebuild. Park is new in Marten 10 and is described below.

Park doesn't apply to every failure. An exception from your own projection code parks the identity. A systemic database failure, like a missing column or a permissions problem, pauses the projection instead, because every identity would fail the same way. A transient failure, like a deadlock or a connection pool timeout, doesn't park, pause or skip anything at first: the daemon retries the whole batch through its Polly pipeline, and pauses only when that gives up. Inline projections never park, and neither does a full rebuild. The complete rules are in What fails and what parks.

Parking a failing identity 10.0 ​

By default in Marten 10, when an async aggregation projection throws on an event, the daemon parks that one identity (one aggregate document) instead of skipping the event or pausing the whole projection. The parked identity's document stays at its last good state, its later events are held back, and every other document keeps moving. You can see what's parked in the mt_parked_identities table, and replay or discard a parked identity once you've fixed the problem:

cs
var daemon = await store.BuildProjectionDaemonAsync();

// After deploying the fix
await daemon.ReplayParkedIdentityAsync("Trip", tenantId: null, tripId, token);

// Or accept the loss: the events that still fail are dead-lettered, the rest are applied
await daemon.DiscardParkedIdentityAsync("Trip", tenantId: null, tripId, token);

snippet source | anchor

The same thing works from the command line with dotnet run -- projections parked (see Command Line Support). To see parked identities in your health checks, see the parked identities health check.

If the projection's aggregate has a natural key, the parked list shows it next to the stream id, so you can find the aggregate by the key people actually know it by. projections parked has a "Natural Key" column, and ParkedIdentity.NaturalKey is filled in when you read the list yourself:

cs
var database = (IEventDatabase)theStore.Storage.Database;
var withKeys = await database.FetchParkedIdentitiesAsync(
    new ParkedIdentityQuery { ProjectionName = nameof(NaturalKeyLedger) },
    TestContext.Current.CancellationToken);

// The natural key the ledger was opened with, or null for a stream that never got one
withKeys.Single(x => x.IdentityText == keyed.ToString("D")).NaturalKey.ShouldBe("L-100");
withKeys.Single(x => x.IdentityText == neverKeyed.ToString("D")).NaturalKey.ShouldBeNull();

snippet source | anchor

The key is read from the aggregate's natural key table when the list is read; it isn't stored on the parked row. It's blank (or null) when the aggregate has no natural key or the stream never got one. A replay or a discard still takes the stream id.

A single-stream projection can always park. A multi-stream projection parks only when Marten can find one identity's events again: group it with IdentityFromStream<TEvent>() or IdentityFromTag<TTag>(), or turn on its slice index with Options.UseSliceIndex(), which keeps one mt_slice_index_* table per projection version. Anything else, including event projections, flat table projections and composite projections, pauses instead. When the daemon starts, Marten logs how each async projection finds one identity's events and whether it parks.

The rules, the guard rails, replaying and discarding, rebuilding one identity of a multi-stream projection and the command line are all described in the JasperFx documentation for parking a failing projection identity.

To go back to skipping errors the way Marten 9 did, call opts.RestoreV9Defaults(), or set opts.Projections.Errors.ApplyErrors and opts.Projections.Errors.SerializationErrors to ProjectionErrorAction.Skip.

TIP

Skipping unknown event types is important for "blue/green" deployment of system changes where a new application version introduces an entirely new event type.

Accessing the Executing Async Daemon ​

Marten supports access to the executing instance of the daemon for each database in your system. You can use this approach to track progress or start or stop individual projections like so:

cs
public static async Task accessing_the_daemon(IHost host)
{
    // IProjectionCoordinator is registered as a singleton in your
    // application by IServiceCollection.AddMarten()

    var coordinator = host.Services.GetRequiredService<IProjectionCoordinator>();

    // If targeting only a single database with Marten
    var daemon = coordinator.DaemonForMainDatabase();
    await daemon.StopAgentAsync("Trip:All");

    // If targeting multiple databases for multi-tenancy
    var daemon2 = await coordinator.DaemonForDatabase("tenant1");
    await daemon2.StopAllAsync();
}

snippet source | anchor

WARNING

While the coordinator is running (Solo or HotCold), it starts any shard it owns that isn't running on its next pass, within LeadershipPollingTime (5 seconds by default). A shard you stop with StopAgentAsync() or PauseShardAsync() therefore comes back on its own. To keep shards stopped, call PauseAsync() on the coordinator first, and ResumeAsync() when you're done.

For a store registered with AddMartenStore<TStore>(), resolve IProjectionCoordinator<TStore> instead. These are the members for controlling the coordinator and its daemons at runtime:

MemberWhat it does
IProjectionCoordinator.PauseAsync()Stops the coordinator's leadership loop, so nothing is restarted, and stops every running shard on every database. Leadership locks are kept.
IProjectionCoordinator.ResumeAsync()Starts the leadership loop again, which starts the shards again. Pair it with PauseAsync().
IProjectionCoordinator.AllDaemonsAsync()The daemon of each of the store's databases.
IProjectionDaemon.PauseShardAsync(projectionName, tenantId, token)Stops every running shard of a projection, matched by the projection's name, so you don't need the shard's key or version. A tenant id stops only that tenant's shards, and null stops them all. Start them again with StartAgentAsync() or StartAllAsync().
IProjectionDaemon.StatusFor(shardName)Running, Paused or Stopped. A shard this daemon doesn't hold is Stopped.
IProjectionDaemon.HasAnyPaused()Whether any of this daemon's shards is paused.
IProjectionDaemon.EjectPausedShard(shardName)Removes a paused shard from the daemon without stopping it, so that it can be started fresh. The coordinator uses it when it fails to restart a paused shard.
IProjectionDaemon.RestartHighWaterAgentAsync(token)Restarts the high water agent's poll loop. It never moves the mark. Check IsHighWaterStale and HighWaterLastPolledAt first.
IProjectionDaemon.CatchUpAsync(token)Stops the running shards and runs every async projection and subscription up to the high water mark inline. It's for tests: nothing is restarted afterwards. ForceAllMartenDaemonActivityToCatchUpAsync() on IHost pauses the coordinator, calls it on every daemon, and by default starts the coordinator again.
IProjectionDaemon.FetchParkedIdentitiesAsync(projectionName, tenantId, token)The identities of a projection parked in this daemon's database, oldest first, with the error that parked each one.
IProjectionDaemon.ReplayParkedIdentitiesAsync(projectionName, tenantId, selection, token)Replays ParkedSelection.All or ParkedSelection.OldestFirst(n) of a projection's parked identities in the shards this daemon runs, at most ParkedReplayBatchSize to a batch.
IProjectionDaemon.IsIdentityParked(projectionName, tenantId, identity)Whether an identity is parked in a shard this daemon runs. false when the shard isn't running here.

cs
public static async Task ControlTheRunningDaemon(IHost host, CancellationToken token)
{
    var coordinator = host.Services.GetRequiredService<IProjectionCoordinator>();

    // Stop the coordinator from starting shards again, and stop every running shard
    // on every database. Nothing restarts until ResumeAsync()
    await coordinator.PauseAsync();

    foreach (var daemon in await coordinator.AllDaemonsAsync())
    {
        // Running, Paused or Stopped. A shard this daemon doesn't hold is Stopped
        Console.WriteLine($"Trip:All is {daemon.StatusFor("Trip:All")}");
    }

    await coordinator.ResumeAsync();
}

public static async Task WorkWithOneDaemon(IProjectionDaemon daemon, CancellationToken token)
{
    // Stop every running shard of one projection, matched by name. Pass a
    // tenant id to stop only that tenant's shards
    await daemon.PauseShardAsync("Trip", tenantId: null, token);

    // Restart the high water agent's poll loop if it has stopped cycling.
    // This never moves the high water mark
    if (daemon.IsHighWaterStale)
    {
        await daemon.RestartHighWaterAgentAsync(token);
    }

    // The identities parked in this daemon's database, oldest first
    var parked = await daemon.FetchParkedIdentitiesAsync("Trip", tenantId: null, token);
    Console.WriteLine($"{parked.Count} Trip identities are parked");

    // Replay the five identities parked first, in the shard that runs them here
    var results = await daemon.ReplayParkedIdentitiesAsync("Trip", tenantId: null,
        ParkedSelection.OldestFirst(5), token);

    foreach (var result in results)
    {
        Console.WriteLine($"{result.Identity}: {result.Outcome}");
    }
}

snippet source | anchor

Testing Async Projections 7.0 ​

TIP

This method works by polling the progress tables in the database, so it's usable regardless of where or how you've started up the async daemon in your code.

Asynchronous projections can be a little rough to test because of the timing issues (is the daemon finished with my new events yet?). To that end, Marten introduced an extension method called IDocumentStore.WaitForNonStaleProjectionDataAsync() to help your tests "wait" until any asynchronous projections are caught up to the latest events posted at the time of the call.

You can see the usage below from one of the Marten tests where we use that method to just wait until the running projection daemon has caught up:

cs
[Fact]
public async Task run_simultaneously()
{
    StoreOptions(x => x.Projections.Add(new DistanceProjection(), ProjectionLifecycle.Async));

    NumberOfStreams = 10;

    var agent = await StartDaemon();

    // This method publishes a random number of events
    await PublishSingleThreaded();

    // Wait for all projections to reach the highest event sequence point
    // as of the time this method is called
    await theStore.WaitForNonStaleProjectionDataAsync(15.Seconds());

    await CheckExpectedResults();
}

snippet source | anchor

The basic idea in your tests is to:

  1. Start the async daemon running continuously
  2. Set up your desired system state by appending events as the test input
  3. Call the WaitForNonStaleProjectionDataAsync() method before checking the expected outcomes of the test

There is also another overload to wait for just one tenant database in the case of using a database per tenant. The default overload will wait for the daemon of all known databases to catch up to the latest sequence.

Accessing the daemon from IHost: ​

If you're integration testing with the IHost (e.g. using Alba) object, you can access the daemon and wait for non stale data like this:

cs
[Fact]
public async Task run_simultaneously()
{
    var host = await StartDaemonInHotColdMode(x =>
        x.Projections.Add(new DistanceProjection(), ProjectionLifecycle.Async));

    NumberOfStreams = 10;

    // This method publishes a random number of events
    await PublishSingleThreaded();

    // Wait for all projections to reach the highest event sequence point
    // as of the time this method is called
    await host.WaitForNonStaleProjectionDataAsync(15.Seconds());

    await CheckExpectedResults();
}

snippet source | anchor

Diagnostics ​

The following code shows the diagnostics support for the async daemon as it is today:

cs
public static async Task ShowDaemonDiagnostics(IDocumentStore store)
{
    // This will tell you the current progress of each known projection shard
    // according to the latest recorded mark in the database
    var allProgress = await store.Advanced.AllProjectionProgress();
    foreach (var state in allProgress) Console.WriteLine($"{state.ShardName} is at {state.Sequence}");

    // This will allow you to retrieve some basic statistics about the event store
    var stats = await store.Advanced.FetchEventStoreStatistics();
    Console.WriteLine($"The event store highest sequence is {stats.EventSequenceNumber}");

    // This will let you fetch the current shard state of a single projection shard,
    // but in this case we're looking for the daemon high water mark
    var daemonHighWaterMark = await store.Advanced.ProjectionProgressFor(new ShardName(ShardState.HighWaterMark));
    Console.WriteLine($"The daemon high water sequence mark is {daemonHighWaterMark}");
}

snippet source | anchor

Both AllProjectionProgress() and ProjectionProgressFor() accept an optional tenant id. With a tenant id, the read targets the database containing that tenant. When the tenant id is omitted on a store with a single database, the default database is used. When the tenant id is omitted under multi-tenancy with multiple databases — including MultiTenantedWithShardedDatabases() — the read spans every known database: AllProjectionProgress() concatenates each database's progression rows (with Events.UseTenantPartitionedEvents the per-tenant rows carry the tenant id in their shard identity, {Name}:{ShardKey}:{tenantId}, so results remain attributable per tenant), and ProjectionProgressFor() returns the highest progression found for the shard name across the databases. Since a tenant-qualified shard identity only ever exists in the one database that owns the tenant, ProjectionProgressFor() with such an identity returns that tenant's exact progression.

store.Advanced.AllAsyncProjectionShardNames() lists the shard names of every async projection, the names that StartAgentAsync(), StopAgentAsync() and StatusFor() take. It doesn't include subscriptions.

If the high water mark ever ends up above the highest assigned event sequence in the database, which has been seen when an application was connected to a PostgreSQL server that was shutting down, store.Advanced.TryCorrectProgressInDatabaseAsync() pulls the high water mark, and the progression of any projection or subscription that is also above that sequence, back to the highest assigned event sequence in that database. A shard whose progression is behind that sequence keeps its position, so it still processes the events in between. When the mark isn't above that sequence it does nothing. The overload taking a tenant id corrects only the database that holds that tenant. The marten --correct command does the same thing from the command line.

cs
public static async Task CorrectProgression(IDocumentStore store, CancellationToken token)
{
    // The shard names of every async projection, e.g. "Trip:All"
    foreach (var shardName in store.Advanced.AllAsyncProjectionShardNames())
    {
        Console.WriteLine(shardName.Identity);
    }

    // Every database of the store
    await store.Advanced.TryCorrectProgressInDatabaseAsync(token);

    // Or only the database that holds one tenant
    await store.Advanced.TryCorrectProgressInDatabaseAsync("tenant1", token);
}

snippet source | anchor

Command Line Support ​

If you're using Marten's command line support, you have the new projections command to help manage the daemon at development or even deployment time.

The command takes an action as its first argument: run (the default), list, rebuild, parked or floor. Options like --projection and --tenant are flags.

To just start up and run the async daemon for your application in a console window, use:

bash
dotnet run -- projections

To list out all the known projection shards, use:

bash
dotnet run -- projections list

To run a single projection, use:

bash
dotnet run -- projections --projection [projection name]

or

bash
dotnet run -- projections -p [projection name]

To rebuild all the known projections with both asynchronous and inline lifecycles, use:

bash
dotnet run -- projections rebuild

To rebuild a single projection at a time, use:

bash
dotnet run -- projections rebuild -p [projection name]

If you are using multi-tenancy with multiple Marten databases, you can choose to rebuild the projections for only one tenant database -- but note that this will rebuild the entire database across all the tenants in that database -- by using the --tenant flag like so:

bash
dotnet run -- projections rebuild --tenant tenant1

To list the identities that are parked, or to ask the node running a projection to replay or discard them, use the parked action:

bash
dotnet run -- projections parked
dotnet run -- projections parked --projection Trip --replay --identity [stream id]
dotnet run -- projections parked --projection Trip --discard --identity [stream id] --yes

--replay --all, --replay --oldest N and --wait are described in the JasperFx documentation for the parked command line.

These are the projections command's own flags. dotnet run -- help projections lists them along with the shared host flags such as --environment.

FlagApplies toWhat it does
-p, --projection <name>all but listOnly this projection. floor and parked need it to change anything.
-s, --store <store>all but listOnly the event store whose subject uri matches, or whose uri scheme matches a bare name. Ignored when there's only one store.
-d, --database <identifier>all but listOnly this database of a store with several. Ignored with only one database.
-t, --tenant <tenant>all but listOnly the database that holds this tenant, all of it. For floor and parked, also that tenant's own floor or parked identities.
--shard-timeout <time>rebuildHow long each shard's rebuild may take, such as 10m or 90s. The default is 5 minutes.
-a, --advancerun, rebuildFirst advance the high water mark of every selected database to the latest committed event sequence. Any gap below it is skipped for good.
--max-concurrent <n>rebuildThe most projections rebuilt at once within one database. The default is MaxConcurrentRebuildsPerDatabase.
--show, --pin-current, --set <n>, --clearfloorSee the floor action below.
--replay, --discard, --identity <id>, --all, --oldest <n>, --wait <seconds>parkedSee the parked command line.
--yesfloor, parkedDon't ask for confirmation before changing anything.

--advance is the command line form of AdvanceHighWaterMarkToLatestAsync(), with the same warning as in Sequence Gaps and the High Water Mark: events still in flight below the new mark are never seen by the async projections.

bash
dotnet run -- projections rebuild -p Trip --shard-timeout 10m
dotnet run -- projections --advance

The floor action ​

A projection's start floor is the event sequence below which it never starts, even when it's rebuilt. It's stored in the mt_event_projection_floors table, keyed by the projection's name without its version and, under UseTenantPartitionedEvents, by tenant. SubscribeFromFirstRun() pins one, as described in Pinning the start on the first run. The floor action shows or changes it without SQL:

bash
# Show the stored floor of every projection (--show is the default)
dotnet run -- projections floor

# Pin Trip's floor at the highest event sequence in the database right now
dotnet run -- projections floor --projection Trip --pin-current

# Set it to a sequence, or clear it
dotnet run -- projections floor --projection Trip --set 250000 --yes
dotnet run -- projections floor --projection Trip --clear
  • Use only one of --show, --pin-current, --set and --clear.
  • A change needs --projection, applies to every selected database, and asks for confirmation unless you pass --yes. When nobody can answer, because input is redirected, it changes nothing and tells you to use --yes.
  • --tenant picks that tenant's floor. Leave it off for the store-global floor, which is also the one a database per tenant store uses.
  • Nothing is replayed when you change a floor. The next continuous start or rebuild of the projection uses it. A cleared floor means the next rebuild replays from the beginning, or from the floor configured in code.
  • The floor action doesn't start a daemon, and --advance does nothing with it.

Using the Async Daemon from DocumentStore ​

All of the samples so far assumed that your application used the AddMarten() extension methods to configure Marten in an application bootstrapped by IHostBuilder. If instead you want to use the async daemon from just an IDocumentStore, here's how you do it:

cs
public static async Task UseAsyncDaemon(IDocumentStore store, CancellationToken cancellation)
{
    using var daemon = await store.BuildProjectionDaemonAsync();

    // Fire up everything!
    await daemon.StartAllAsync();

    // or instead, rebuild a single projection
    await daemon.RebuildProjectionAsync("a projection name", 5.Minutes(), cancellation);

    // or a single projection by its type
    await daemon.RebuildProjectionAsync<TripProjectionWithCustomName>(5.Minutes(), cancellation);

    // Be careful with this. Wait until the async daemon has completely
    // caught up with the currently known high water mark
    await daemon.WaitForNonStaleData(5.Minutes());

    // Start a single projection shard
    await daemon.StartAgentAsync("shard name", cancellation);

    // Or change your mind and stop the shard you just started
    await daemon.StopAgentAsync("shard name");

    // No, shut them all down!
    await daemon.StopAllAsync();
}

snippet source | anchor

Open Telemetry and Metrics 7.10 ​

INFO

All of these facilities are used automatically by Marten.

See Open Telemetry and Metrics to learn more about exporting Open Telemetry data and metrics from systems using Marten.

If your system is configured to export metrics and Open Telemetry data from Marten like this:

cs
// This is passed in by Project Aspire. The exporter usage is a little
// different for other tools like Prometheus or SigNoz
var endpointUri = builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"];
Console.WriteLine("OLTP endpoint: " + endpointUri);

builder.Services.AddOpenTelemetry().UseOtlpExporter();

builder.Services.AddOpenTelemetry()
    .WithTracing(tracing =>
    {
        tracing.AddSource("Marten");
    })
    .WithMetrics(metrics =>
    {
        metrics.AddMeter("Marten");
    });

snippet source | anchor

And you are running the async daemon in your system, you should see these spans for each running projection or subscription shard, named marten.{name}.{shard key}.page.*, where the name is the projection or subscription name in lower case, without its version, and the shard key is almost always all:

  • marten.{name}.{shard key}.page.execution -- the execution of a page of events through the projection or subscription, tagged with page.size, event.floor, event.ceiling and database.uri
  • marten.{name}.{shard key}.page.loading -- the loading of a page of events, tagged with event.floor and database.uri
  • marten.{name}.{shard key}.page.grouping -- the grouping that a projection does before execution, with the same tags as execution. Subscriptions don't group

Each shard also gets seven metrics under the prefix marten.{name}.{shard key}. Metric names never include the database: every measurement carries a database.uri tag instead, so with separate databases for multi-tenancy you tell the databases apart by that tag.

  • processed -- a counter of the events the shard has processed
  • gap -- a histogram of the distance between the high water mark and the shard's progression
  • skipped -- a counter of the events the shard skipped. Depending on your configuration, Marten skips events because of serialization errors, unknown events, or errors in your code when you've configured the daemon to skip them (see Error Handling)
  • parked -- a counter of the identities the shard parked
  • unparked -- a counter of the identities taken off the parked list, with an outcome tag as well
  • parked.held_events -- a counter of the events held back because their identity is parked
  • parked.current -- a gauge of how many identities the shard holds parked right now. It's registered the first time the shard reports a parked count

TIP

The gap metrics are a good health check on the performance of any given projection or subscription. If this gap is growing, that's a sign that your projection or subscription isn't being able to keep up with the incoming events

High Water Mark 7.33 ​

Marten emits Open Telemetry spans and metrics around the high water mark detection in the async daemon. For why the mark holds or skips a gap, see Sequence Gaps and the High Water Mark.

Each poll of the high water agent is a span named marten.daemon.highwatermark, whatever the number of databases. It carries a database.uri tag to say which database it polled, and these tags:

  • sequence -- the largest event sequence that has been assigned to the database at this point
  • status -- either CaughtUp, Changed, or Stale meaning "all good", "proceeding normally", or "uh, oh, something is up with outstanding transactions"
  • current.mark -- the current, detected "high water mark" where Marten says is the ceiling on where events can be safely processed
  • skipped -- this tag will only be present as a "true" value if Marten is forcing the high water detection to skip stale gaps in the event sequence
  • last.mark -- if skipping event sequences, this will be the last good mark before the high water detection calculated the skip

There is also a counter called marten.daemon.skipping that counts each time the high water detection skips a stale gap. It has no tags. The marten prefix of both comes from opts.Projections.OtelPrefix.

Extended Progression Tracking ​

Extended progression tracking adds nine monitoring columns (heartbeat, agent_status, pause_reason, running_on_node, failure_category, failure_event_sequence, failure_event_type, failure_event_tenant_id, parked_count) to mt_event_progression. The async daemon writes them from existing runtime state and the shard-state selector reads them back into ShardState so monitoring tooling such as CritterWatch can display per-shard health.

Two further columns, warning_behind_threshold and critical_behind_threshold, are also created but are neither written nor read — nothing has ever owned the value, and every lag threshold lives in the monitoring tool. They are kept rather than dropped purely so that upgrading does not change this table's schema: alter table … drop column needs an ACCESS EXCLUSIVE lock on a small, hot table that every running daemon writes, and while that lock waits it blocks every reader and writer behind it. Two always-NULL columns are the cheaper trade.

Why a shard is down 9.20 ​

The four failure_* columns record the classified reason a shard paused or stopped, so a consumer polling the database — which is exactly what a monitoring tool must fall back to when the node that was running the shard is down — sees the same reason an in-process ShardState observer does instead of only that the shard is Paused. They are read back onto ShardState.Failure:

cs
var states = await store.Storage.Database.AllProjectionProgress();
foreach (var state in states.Where(x => x.Failure != null))
{
    // ApplyEvent, EventSerialization, UnknownEventType, ProgressionOutOfOrder,
    // ParkedLimitReached, or Other
    Console.WriteLine($"{state.ShardName}: {state.Failure!.Category} on {state.Failure.Event}");
}

snippet source | anchor

failure_category stores the enum name rather than its ordinal, so reordering ShardFailureCategory in a future release can never silently re-label rows an older deployment wrote. The reason text has no column of its own — ShardFailure.Detail is exactly what pause_reason has always carried.

Marten's own read-path exceptions declare their category, so a body that fails to deserialize reports EventSerialization with the offending event's sequence and type alias, and an event type alias with no registered .NET type reports UnknownEventType. The two are kept apart deliberately: bad data needs a serializer or data fix, while a missing registration is usually a deployment gap or a rollback past the event type's introduction.

A shard that recovers clears its failure columns on the next successful start, so a supervisor built on them does not keep alerting on a failure that was fixed an hour ago.

Default: on 10.0. The columns are useful for any stuck-shard diagnosis -- not just CritterWatch -- and the write-side cost is negligible, because they carry already-computed daemon-internal values. It was on by default in 9.7.0, reverted in 9.7.1, and is on again in 10.0 (see marten#5763). The mt_mark_event_progression_extended database function is no longer part of the schema -- the daemon always wrote through plain UPDATE statements -- so the flip needs no DDL on a database migrated by 9.31 or later.

The columns themselves are created for every store regardless of this setting, and the next ApplyAllConfiguredChangesToDatabaseAsync() adds them to an existing database. They are nullable, so no backfill is required.

That the shape does not depend on the setting is deliberate. It used to, and two DocumentStores pointed at the same DatabaseSchemaName that disagreed about the flag then stripped each other's columns on every schema application -- last writer wins, with no warning on either side. Two processes over one schema is an ordinary arrangement (a service beside a seeder, a reporting job or a migration tool), so the table shape is now the same for all of them (see marten#5309).

To restore the 9.x behavior, opt out by setting the toggle (IEventStoreInstrumentation.ExtendedProgressionEnabled is the same switch under its storage-agnostic name; both read and write one field):

cs
opts.Events.EnableExtendedProgressionTracking = false;

Marten registers a storage-agnostic IEventStoreInstrumentation adapter (from JasperFx.Events 2.9.0) in the container. Satellite packages such as Wolverine.CritterWatch.Marten control the same columns by resolving that service from DI and setting its ExtendedProgressionEnabled property -- no reference to Marten's concrete EventGraph required.

The adapter's value is applied at store build only if something actually set it, so it does not overwrite a direct opts.Events.EnableExtendedProgressionTracking = ... of either polarity and the two paths compose. Setting ExtendedProgressionEnabled = false on the adapter is a real opt-out, not merely the absence of an opt-in. (Note that opts.Events -- Marten's EventGraph -- does not itself implement IEventStoreInstrumentation; use the EnableExtendedProgressionTracking property shown above.)

What extended progression actually costs ​

The columns themselves are free -- they ride along on writes the daemon already makes when a shard starts, pauses or stops. What is not free is the periodic heartbeat: a timer-driven flush that opens its own connection and transaction per shard database, per node.

Marten 9.22.4 / JasperFx 2.39 turns that periodic beat off by default. Only status transitions reach the database, so an idle store makes no telemetry writes at all. Before that it ran on a hardcoded 5-second interval with no configuration path, which on a 512-shard-database store worked out to roughly 37 connection acquisitions per second per node to keep a handful of rows current -- enough to exhaust a small per-database connection pool and queue application requests behind it (see marten#5167).

If you want the periodic beat back -- a monitoring console that needs to distinguish "this shard is alive but idle" from "this shard's agent died" -- opt in explicitly and pick a cadence that suits your database count:

cs
opts.Events.EnableExtendedProgressionTracking = true;

// Off by default. Any positive value restores the periodic flush at that cadence;
// null, zero or negative keeps it off.
opts.Projections.ExtendedProgressionHeartbeatInterval = TimeSpan.FromSeconds(30);

snippet source | anchor

Budget it as databases-on-this-node / interval connection acquisitions per second. All shard states that arrive within one interval are coalesced into a single flush on one rented connection, so the connection cost scales with the number of databases rather than the number of shards.

Within that flush each shard's row is written by its own single-row statement, in its own implicit transaction. That is deliberate and load-bearing: a batch is there to amortize the connection, not the transaction. Marten 9.22.4 and earlier folded the flush into one UPDATE ... FROM unnest(...), which takes a row lock on every shard in the batch and holds all of them until it commits — so a single slow projection batch sitting on one progression row stalled the telemetry write of every other shard on that database, and whatever was queued behind those. If you are diagnosing lock waits on mt_event_progression on an older version, note that pg_blocking_pids() reports only direct blockers: the telemetry UPDATE genuinely is the blocker, and the projection transaction that is the real root is one hop further down the chain. Walk it recursively.

TIP

Status transitions are always written immediately regardless of this setting, so agent_status, pause_reason and the failure_* columns stay current with the beat switched off. The only thing you lose is the periodic refresh of heartbeat on a shard that is quietly making progress.

Skip Tracking 8.6 ​

Marten writes every time the high water detection has to "skip" over stale data to a table called mt_high_water_skips. This is on by default since Marten 9.0. The table is the ledger that the late event recovery reads, and you can use it to know which streams and projections a skip may have affected.

To turn it off, set EnableAdvancedAsyncTracking to false, or call opts.RestoreV8Defaults():

cs
var builder = Host.CreateApplicationBuilder();
builder.Services.AddMarten(opts =>
{
    opts.Connection(builder.Configuration.GetConnectionString("marten"));

    // On by default. This turns off the mt_high_water_skips ledger
    // and the late event recovery that reads it
    opts.Events.EnableAdvancedAsyncTracking = false;
});

snippet source | anchor

Querying for Non Stale Data ​

There are some potential benefits to running projections asynchronously, namely:

  • Avoiding concurrent updates to aggregated documents so that the results are accurate, especially when the aggregation is "multi-stream"
  • Putting the work of building aggregates into a background process so you don't take the performance "hit" of doing that work during requests from a client

All that being said, using asynchronous projections means you're going into the realm of eventual consistency, and sometimes that's really inconvenient when your users or clients expect up to date information about the projected aggregate data.

Not to worry though, because Marten will allow you to "wait" for an asynchronous projection to catch up so that you can query the latest information as all the events captured at the time of the query are processed through the asynchronous projection like so:

cs
var builder = Host.CreateApplicationBuilder();
builder.Services.AddMarten(opts =>
{
    opts.Connection(builder.Configuration.GetConnectionString("marten"));
    opts.Projections.Add<TripProjection>(ProjectionLifecycle.Async);
}).AddAsyncDaemon(DaemonMode.HotCold);

using var host = builder.Build();
await host.StartAsync();

// DocumentStore() is an extension method in Marten just
// as a convenience method for test automation
await using var session = host.DocumentStore().LightweightSession();

// This query operation will first "wait" for the asynchronous projection building the
// Trip aggregate document to catch up to at least the highest event sequence number assigned
// at the time this method is called
var latest = await session.QueryForNonStaleData<Trip>(5.Seconds())
    .OrderByDescending(x => x.Started)
    .Take(10)
    .ToListAsync();

snippet source | anchor

Do note that this can time out if the projection just can't catch up to the latest event sequence in time. You may need to be both cautious with using this in general, and also cautious especially with the timeout setting.

Returning stale data instead of throwing on timeout ​

By default QueryForNonStaleData throws a TimeoutException if the asynchronous projection cannot catch up to the event store high water mark within the supplied timeout. In some scenarios — for example when a gap in the event sequence (left by a failed append) makes the high water mark effectively unreachable — that would make every call throw, even though the projection has perfectly usable, slightly stale data already materialized. If you would rather serve the latest available data than fail the request, use the overload that takes a NonStaleDataTimeoutMode:

cs
// Wait up to 5 seconds for the projection to catch up, but if it cannot,
// return the latest available (possibly stale) data instead of throwing.
var latest = await session
    .QueryForNonStaleData<Trip>(5.Seconds(), NonStaleDataTimeoutMode.ReturnStaleData)
    .OrderByDescending(x => x.Started)
    .Take(10)
    .ToListAsync();

snippet source | anchor

NonStaleDataTimeoutMode.ThrowException is the default and matches the behavior of the single-argument QueryForNonStaleData<T>(timeout) overload, so existing usages are unaffected. Choose NonStaleDataTimeoutMode.ReturnStaleData only when serving slightly stale data is preferable to a failed query.

Reading Your Own Writes 10.0 ​

QueryForNonStaleData waits for the highest event sequence in the store at the time of the call. On a busy system that includes everybody else's events, so a request waits for work it doesn't care about. And a timeout there is an exception, even though your write went through just fine.

If what you want is to read back what you just wrote, wait for your own events instead. After SaveChangesAsync(), session.LastAppendedPosition tells you where that commit's events are, and IDocumentStore.WaitForProjectionsAsync() waits for the named asynchronous projections to get that far:

cs
await using var session = store.LightweightSession();
session.Events.StartStream(Guid.NewGuid(), new RywCounted(false));
await session.SaveChangesAsync();

// Where this commit's events are: database, tenant and sequence
var position = session.LastAppendedPosition!;

var result = await store.WaitForProjectionsAsync(position, [typeof(RywTally)], 5.Seconds());
if (result.Reached)
{
    var tally = await session.LoadAsync<RywTally>("tally");
}
else
{
    // Timed out, or the projection is paused or rebuilding. The write succeeded either way,
    // and result.Shards says how far each shard got
}

snippet source | anchor

Some things to know:

  • The result is a value, not an exception. Reached means the projections have your events. TimedOut means they don't yet, and Shards tells you how far each one got. Return a 202, read anyway, or fall back to a live aggregation. That's your call.
  • A projection that is paused or being rebuilt returns right away with Paused or Rebuilding instead of making you sit through the timeout. Another node sees a pause only with extended progression tracking turned on, and a rebuild is only visible on the node running it.
  • The wait polls mt_event_progression, so it works on any node, whether or not that node runs the daemon.
  • Pass the projection classes, the documents they write, or the projection names. Asking about something that isn't an asynchronous projection is an ArgumentException. An inline projection is already current when SaveChangesAsync() returns.
  • The position is the database, the tenant and the sequence. With UseTenantPartitionedEvents every tenant has its own sequence, and with a database per tenant every database has its own, and the wait reads the matching progression rows.
  • A gap in the event sequence below your events holds the wait until the daemon's gap detection skips it, and the daemon's polling interval is the floor on how fast any of this can be.

The position is small and serializes as JSON. It also has a compact text form if you want to hand it to the next request in a header:

cs
var position = new EventStorePosition("main", "tenant-a", 1234);

// "main/tenant-a/1234", safe to put in a header
var header = position.ToString();

var back = EventStorePosition.Parse(header);

snippet source | anchor

Migrating a Projection from Inline to Async 7.35 ​

WARNING

This will only work correctly if you have system downtime before migrating the new version of the code with this option enabled. This feature cannot support a "blue/green" deployment model. Marten needs to system to be at rest before it starts up the projection asynchronously or there's a chance you may "skip" events in the projection.

During the course of a system's lifetime, you may find that you want to change a projection that's currently running with a lifecycle of Inline to running asynchronously instead. If you need to do this and there is no structural change to the projection that would require a projection rebuild, you can direct Marten to start that projection at the highest sequence number assigned by the system (not the high water mark, but the event sequence number which may be higher).

To do so, use this option when registering the projection:

cs
opts
    .Projections
    .Snapshot<SimpleAggregate>(SnapshotLifecycle.Async, o =>
    {
        // This option tells Marten to start the async projection at the highest
        // event sequence assigned as the processing floor if there is no previous
        // async daemon progress for this projection
        o.SubscribeAsInlineToAsync();
    });

snippet source | anchor

Just to be clear, when Marten's async daemon starts a projection with this starting option:

  1. If there is no previously recorded progression, Marten will start processing this projection with the highest assigned event sequence in the database as the floor and record that value as the current progress
  2. If there is a previously recorded progression, Marten will start processing this projection at the recorded sequence as normal

Released under the MIT License.