Appearance
Multi-Tenancy
GrydJobs integrates with Gryd.IO's tenant context to capture and restore tenant identity for job execution and tenant-scoped metadata access. Hangfire storage and JobsDbContext use the single connection configured in GrydJobsOptions.ConnectionString; the module does not select a storage database dynamically for each tenant.
How It Works
- Job submission — trusted tenant and user identity are captured in the scheduling envelope
- Job execution — the captured tenant context is restored before resolving the job
- Metadata access — tenant-aware queries and save interception apply row authority
Tenant Context Propagation
When a job is submitted from a tenant-scoped request, GrydJobs captures trusted tenant and user identity in the immutable scheduling envelope. The tenant ID is:
- Stored in the
JobDefinition.TenantIdfield - Persisted with the Hangfire invocation before it becomes runnable
- Established before the job and its dependencies are resolved
csharp
// Tenant context is captured from the current request
await scheduler.EnqueueAsync<SendEmailJob, SendEmailArgs>(
new SendEmailArgs(email, subject, body));
// The job and its scoped dependencies execute with the captured tenant contextDatabase Isolation
Lifecycle persistence establishes the captured tenant before reading or writing tenant-scoped job records:
csharp
// Repository reads use the current established tenant scope
var jobs = await jobStore.GetAllAsync(parameters); // Only returns current tenant's jobs
var stats = await jobStore.GetDashboardStatsAsync(); // Stats scoped to tenantWeb API tenant selection and route authorization are provided by the host's Auth and tenant-session middleware. Requests carry no tenant (ADR 0011, D23): every handler reads the tenant of the session from ITenantSession, and a session without a tenant is a null tenant — a global job:
csharp
public sealed class EnqueueJobCommandHandler(/* ... */, ITenantSession tenantSession)
{
// ...
var tenantId = tenantSession.TenantId; // Guid? — null means a global job
}Cross-Tenant Operations
No request bypasses the tenant filter. PurgeDeadLetterQueueCommand purges the entries the session can see: its tenant's rows and the global ones. Code that must work across tenants — a hosted service or a job, never a request handler — opens the audited system scope (ADR 0011, D21):
csharp
await using (ambient.BeginSystemScope("jobs: dead letter retention across tenants"))
{
await deadLetterQueue.PurgeAsync(olderThan, cancellationToken);
}Recurring Jobs
Recurring jobs can be tenant-scoped:
csharp
var schedule = JobSchedule.Create(
"tenant-report",
"MyApp.TenantReportJob",
"0 8 * * 1", // Every Monday at 8:00 AM
timeZoneId: null,
queue: "default",
tenantId: currentTenantId // Scoped to this tenant
);Recurring executions retain the tenant attached to the schedule, and the registered recurring key remains JobExecutionContext.JobId. The individual provider execution ID is available separately as JobExecutionContext.ExecutionId.
Legacy Hangfire invocations may not contain trusted tenant metadata. GrydJobs can restore it only from a stored job definition or recurring schedule. If required tenant metadata is unavailable, execution fails before user work begins; resubmit through the GrydJobs scheduler. A job type explicitly configured in GlobalJobs may run without tenant scope. GrydJobs does not infer tenant identity from job arguments. Submissions from an active group tenant scope are rejected because a single job must have one explicit tenant identity.
Per-tenant recurring jobs
A job that must run for every active tenant on a schedule (an SLA clock, a nightly check) implements IPerTenantRecurringJob instead of IRecurringJob:
csharp
public sealed class SlaClockJob(ISlaClock clock) : IPerTenantRecurringJob
{
public string JobId => "sla-clock";
public string CronExpression => "*/5 * * * *";
public Task ExecuteForTenantAsync(JobExecutionContext context, CancellationToken cancellationToken)
=> clock.TickAsync(context.TenantId!.Value, cancellationToken);
}Setup:
- Put the assembly in
GrydJobsOptions.JobAssemblieswithAutoRegisterRecurringJobsenabled. Discovery and the checks below only run when auto-registration is on. - Register the GrydAuth readers: the host needs an
IActiveTenantDirectory. Startup fails withPer-tenant recurring jobs need an IActiveTenantDirectory (register GrydAuth readers).otherwise. - A type cannot implement both
IRecurringJobandIPerTenantRecurringJob; startup fails if it does.
What happens on each cron tick:
- A global dispatch (it counts as a global job, like one listed in
GlobalJobs) reads the active tenants in a system scope, 500 at a time, until a short page. The read completes before anything is enqueued, so a failed read is retried by the provider without having dispatched a tenant. - It enqueues one execution per active tenant, each with its tenant in
JobExecutionContext.TenantIdand in the ambient tenant context (ITenantSession.TenantId).JobExecutionContext.JobIdis theJobIdof your job. - A tenant created while the dispatch is reading the directory joins the next tick. A failure to enqueue one tenant is logged with its
TenantIdand does not stop the others; the dispatch itself does not throw, because a retry would enqueue every tenant again.
Each execution is an independent job with its own lifecycle record and its own retry: a failure in one tenant does not affect the others.
Things to design for:
- Idempotency. An execution can be retried or repeated, so the job must tolerate it. This includes the dispatch: if the worker shuts down in the middle of the enqueue loop, the provider retries the dispatch and enqueues again the tenants already enqueued, so the per-tenant execution must be idempotent.
- Overlap. A slow execution can still be running when the next tick enqueues another one for the same tenant; the job must not assume the opposite.
IAdvisoryLock.TryAcquireAsynconly serves short executions, inside the short transaction of the act. A long execution needs a lease in the product's own table. - Cost. Every execution writes GrydJobs lifecycle rows, and they are not purged: tenants times ticks per day. For an SLA clock use a cron of at least 5 minutes. Each dispatch also writes a system scope record (
SystemScopeRecording.Always). - Queue, retry and timeout.
Queueof the job applies to the dispatch; the executions go to the default queue.RetryPoliciesandTimeoutsare keyed byPerTenantRecurringRun<TJob>(the per-tenant execution), not by your job type.