Huge startup performance issue when using tenants
Performance Improvement Request
Performance Issue Overview
Is your performance issue related to a specific functionality? Please describe. Host startup with multitenancy enabled grows linearly with the tenant count. With about 600 tenants on one shared SQL Server database (EF Core persistence, 3.8.4), it takes multiple minutes to reach "Now listening". Tenant activation alone takes over a minute. Causes found in 3.8.4:
- Tenants activate one after another.
DefaultTenantServiceawaitsRegisterTenantAsyncin aforeach. Each activation runs all startup tasks, background tasks and recurring-task setup for that tenant before the next tenant starts. - Migrations run once per tenant.
RunMigrationsStartupTask<TDbContext>callsMigrateAsyncfor every DbContext in every tenant, even when all tenants share one connection string. Every call after the first applies nothing, but it still costs a connection and a round trip. - Single-node lock names ignore the tenant.
TaskExecutornames the lock after the task type only. So every tenant waits for the same distributed lock (sp_getapplock), and each waiter holds a pooled connection while it waits. The result is a serial queue and, eventually,Timeout expired ... obtaining a connection from the pool.DistributedBookmarkQueueWorkerhas the same pattern. - The interrupted-workflow recovery scan runs once per tenant, though it has no per-tenant logic.
InterruptedRecoveryScanneralready pushes each instance's own tenant before restarting it. It runs per tenant only because it is registered as a tenant startup task, and its query is limited by the tenant query filter. So activation runs N filtered scans instead of one, all queued on the one global[SingleNodeTask]lock, and every tenant-agnostic ("*") instance is requeued N times. - Recurring tasks get one timer per task per tenant. Each tenant's timers start when that tenant is activated. So while later tenants are still activating, earlier tenants already run their 10 s tasks and compete with activation for connections. With 600 tenants that is 2,400 timers, or about 180 runs per second. The two
[SingleNodeTask]tasks also queue on one global lock (see point 3). The outbox task takes that lock even whenUseTransactionalOutboxis off. After startup,RestartInterruptedWorkflowsTaskruns per tenant, and each run also sees all"*"instances, so every stuck"*"instance is restarted N times per cycle. - Tenant-agnostic CLR workflows are rebuilt and re-saved for every tenant.
PopulateRegistriesStartupTaskruns per tenant and callsPopulateStoreAsynctwice (before and after the workflow-as-activity refresh).ClrWorkflowsProviderbuilds every registered CLR workflow on each call and gives themTenantId = "*", andDefaultWorkflowDefinitionStorePopulatorimports"*"workflows for every tenant. So each tenant rebuilds, serializes, looks up, saves (MERGE) and re-indexes the triggers of the same shared rows. With 1,000 tenants and 2 CLR workflows that is 6,000 workflow builds, 4,000SaveManyAsynccalls and 2,000 trigger indexings, all of them rewriting identical data.
Proposed Enhancement
Describe the enhancement you'd like
- Parallel tenant activation. Register all tenants and publish the dictionaries first, so a startup task that looks up a tenant does not deadlock. Then activate tenant[0] alone, so migrations finish before any other tenant touches the database. Then activate the rest with
Parallel.ForEachAsync, bounded by a newTenantActivationOptions.MaxDegreeOfParallelism(default 8). MigratedDatabaseRegistry. Migrate each (DbContext type, connection string) pair once, not once per tenant. A tenant with its own database is still migrated.[SingleNodeTask(SingleNodeTaskScope.Tenant | Host)], default Tenant. Tenant-scoped locks are named{type}:{tenantId}. Host-scoped tasks (migrations) keep the global name. The default tenant keeps the old name, so rolling upgrades still work.- A new
ITenantsActivatedEvent, raised once after activation. The recovery scan runs there, once, host-scoped and across all tenants (WorkflowInstanceFilter.TenantAgnostic). TenantRecurringTaskScheduler. One timer per task type, which runs the task for each tenant in turn, bounded byRecurringTaskOptions.MaxDegreeOfParallelism(default 4).RestartInterruptedWorkflowsTaskruns once per cycle across all tenants.- A
lock (registry)inActivityRegistry.RefreshDescriptorsAsync. Parallel activation needs it: every tenant's refresh also rewrites the shared tenant-agnostic registry, and without the lock those refreshes interleave their removes and adds. - Import tenant-agnostic CLR workflows once. A new marker interface
ITenantAgnosticWorkflowsProvider, implemented byClrWorkflowsProvider, plus a singletonTenantAgnosticWorkflowsImport. Once such a provider has returned only"*"workflows on a pass that indexes triggers,DefaultWorkflowDefinitionStorePopulatorskips it for every later tenant. Tenant[0] is activated alone first, so the"*"definitions and triggers exist before the other tenants run their startup tasks. A provider that also returns tenant-specific workflows (WithTenantId) keeps being queried for every tenant. Trade-off: CLR workflows are compiled code and cannot change at runtime, so a runtime reload does not re-import them after the first import.
Affected Use Cases
Identify affected use cases
- Hosts whose
ITenantsProviderreturns hundreds of tenants, one per customer, all sharing one database. - Rolling deployments, autoscaling and container orchestrators: a startup of 90 s or more fails health probes and triggers restarts.
- Multi-node setups: each node repeats the per-tenant startup work and queues on the same distributed locks.
Impact of Enhancement
Explain the potential impact
- Activation time drops about 4-5x at the default parallelism of 8.
- Database connections held during startup and each recurring cycle stay bounded (8 for activation, 4 per recurring task type) instead of growing with the tenant count. The pool no longer runs dry.
- The migration check runs once per database, and the interrupted-workflow scan and restart run once per cycle instead of once per tenant.
- CLR workflow builds, saves and trigger indexing at startup no longer depend on the tenant count.
- Single-tenant hosts behave exactly as before: the default tenant keeps the old lock names.
Benchmarks and Metrics
Provide any relevant benchmarks or metrics Manual tests of the full host after the changes above: startup went from several minutes down to about 30 seconds.
PopulateRegistriesStartupTask turned out to be most of those remaining 30 seconds (point 6). A harness that runs the real ITenantService.ActivateTenantsAsync() with in-memory stores, 1,000 tenants and 2 CLR workflows (Release build, median of 3 runs):
| Before | After | |
|---|---|---|
| Tenant activation | 17,954 ms | 2,344 ms |
| CLR workflow builds | 6,000 | 6 |
SaveManyAsync calls |
4,000 | 4 |
IndexTriggersAsync calls |
2,000 | 2 |
With a single default tenant, the counts and timing are unchanged.
Additional Context
Add any other context We are happy to open PRs once you agree with these improvements
Source: elsa-workflows/elsa-core