# MassiveJobs > Distributed background jobs for .NET on RabbitMQ 4.4+. Apps publish jobs (immediate, scheduled, long-running) as messages; workers in any number of apps run them, and the application's database isn't involved. Scheduled jobs and retries wait in the broker (delayed delivery in quorum queues), periodic jobs are defined with attributes in code, failed jobs end in a failed queue that IFailedJobs inspects and requeues. Targets .NET 10, .NET 11 and netstandard2.0 (.NET Framework 4.6.2+), trimming and Native AOT compatible. These docs describe MassiveJobs 1.0 (on NuGet: MassiveJobs.Core, MassiveJobs.RabbitMqBroker). Versions before 1.0 (0.45.1 and older) have a different API. Source: https://github.com/enadzan/massivejobs # Getting started Source: https://massivejobs.net/docs/getting-started/ MassiveJobs publishes jobs to RabbitMQ. Any app can publish, and every app that runs workers takes jobs from the same queues. This page gets one app doing both, then a second app sharing the work. ## Requirements - **RabbitMQ 4.4 or later.** Scheduled jobs and retries use the delayed delivery of quorum queues, new in 4.4. MassiveJobs refuses to connect to an older server. - **.NET 10 or 11**, or anything that runs `netstandard2.0`: .NET 8 and 9, and .NET Framework 4.6.2 or later. - **A C# compiler from the .NET 8 SDK or Visual Studio 2022 17.8 on**, in the projects that register jobs: MassiveJobs' source generator runs there. ## Your first job 1. **Start RabbitMQ.** In a container, with the management UI on [localhost:15672](http://localhost:15672) (user and password `guest`): ```bash docker run -d --name rabbit -p 5672:5672 -p 15672:15672 rabbitmq:4-management ``` 2. **Create an app and add the package.** A worker service here; an ASP.NET Core app works the same way. ```bash dotnet new worker -n Shop.Worker cd Shop.Worker dotnet add package MassiveJobs.RabbitMqBroker ``` `MassiveJobs.RabbitMqBroker` brings `MassiveJobs.Core` with it. 3. **Write a job.** A job is a class with a `Perform` method. Derive it from `Job` (or `JobAsync` for an async one), where `TArgs` is what you pass when you publish it: ```csharp // SendWelcomeEmail.cs using MassiveJobs.Core; public class SendWelcomeEmail(ILogger logger) : JobAsync { public override async Task Perform(int customerId, CancellationToken cancellationToken) { await Task.Delay(500, cancellationToken); // the email logger.LogInformation("Welcome email sent to customer {CustomerId}", customerId); } } ``` The constructor gets its parameters from your services, in a scope created for each run. 4. **Register MassiveJobs.** In `Program.cs`, add MassiveJobs, the jobs of this project, and RabbitMQ: ```csharp // Program.cs var builder = Host.CreateApplicationBuilder(args); builder.Services.AddMassiveJobs() .WithJobsFromAssemblyOf() .UseRabbitMq(); // localhost, as guest builder.Services.AddHostedService(); builder.Build().Run(); ``` The host starts the workers with the app and stops them with it. 5. **Publish.** Inject `IJobPublisher` where you need it. In the template's `Worker`, publish a job every few seconds: ```csharp // Worker.cs using MassiveJobs.Core; public class Worker(IServiceScopeFactory scopes) : BackgroundService { protected override async Task ExecuteAsync(CancellationToken stoppingToken) { for (var customerId = 1; !stoppingToken.IsCancellationRequested; customerId++) { using (var scope = scopes.CreateScope()) { var publisher = scope.ServiceProvider.GetRequiredService(); await publisher.PublishAsync(customerId, cancellationToken: stoppingToken); } await Task.Delay(2000, stoppingToken); } } } ``` `IJobPublisher` is scoped: a controller or a minimal API handler just takes it as a parameter. 6. **Run it, twice.** `dotnet run` in two terminals. Both publish, and the jobs are shared: each one runs once, in either app. ## What you get by default Each app that runs workers consumes **4 immediate queues**, one job at a time each, and **2 long-running queues** for jobs published with a timeout of 10 seconds or more. A job that throws is retried 25 times with growing delays, then kept in the failed queue. All of it is in [Configuration](https://massivejobs.net/docs/configuration/); how the queues are shared is in [Queues and workers](https://massivejobs.net/docs/queues-and-workers/). Apps that share jobs must agree on a few things: the job tags, the queue counts, and the name prefix. The defaults agree. ## Other kinds of apps **ASP.NET Core** ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddMassiveJobs() .WithJobsFromAssemblyOf() .UseRabbitMq(o => o.ConnectionString = builder.Configuration.GetConnectionString("RabbitMq")); var app = builder.Build(); app.MapPost("/customers/{id:int}/welcome", async (int id, IJobPublisher publisher) => { await publisher.PublishAsync(id); return Results.Accepted(); }); app.Run(); ``` **Publish only** An app that publishes jobs but doesn't run them, e.g. a web front end with separate worker apps: ```csharp builder.Services.AddMassiveJobs(o => o.StartWorkers = false) .WithJobsFromAssemblyOf() .UseRabbitMq(o => o.ConnectionString = builder.Configuration.GetConnectionString("RabbitMq")); ``` It still registers the jobs: only registered jobs can be published. **No host** A console app or a .NET Framework app without `Microsoft.Extensions.Hosting` starts MassiveJobs itself, once the service provider is built: ```csharp var services = new ServiceCollection(); services.AddLogging(); services.AddMassiveJobs() .WithJobsFromAssemblyOf() .UseRabbitMq(); using var provider = services.BuildServiceProvider(); var jobs = MassiveJobsMediator.Initialize(provider); // checks the configuration, throws if it's wrong await jobs.StartAsync(); await SendWelcomeEmail.PublishAsync(42); // the static API: no publisher to inject Console.ReadLine(); await jobs.StopAsync(); MassiveJobsMediator.Deinitialize(); ``` ## Next - [Jobs](https://massivejobs.net/docs/jobs/): job classes, arguments, tags, publishing, timeouts. - [Guarantees](https://massivejobs.net/docs/guarantees/): when a job can run twice, and what to do about it. - [Scheduling](https://massivejobs.net/docs/scheduling/) and [Periodic jobs](https://massivejobs.net/docs/periodic-jobs/). --- # Jobs Source: https://massivejobs.net/docs/jobs/ A job is a class with a `Perform` method. A worker creates it for each run, in a DI scope of its own, calls `Perform` with the arguments it was published with, and disposes it. ## Job classes The usual way is to derive from one of the base classes. `TJob` is the class itself: | Base class | `Perform` | |---|---| | `Job` | `void Perform()` | | `Job` | `void Perform(TArgs args)` | | `JobAsync` | `Task Perform(CancellationToken cancellationToken)` | | `JobAsync` | `Task Perform(TArgs args, CancellationToken cancellationToken)` | ```csharp public class ResizeImage(IBlobStore blobs) : JobAsync { public override async Task Perform(ResizeArgs args, CancellationToken cancellationToken) { var image = await blobs.ReadAsync(args.Path, cancellationToken); await blobs.WriteAsync(args.Path + ".thumb", Thumbnail(image, args.Width), cancellationToken); } } public record ResizeArgs(string Path, int Width); ``` A **plain class** works too: no base class, just a public `Perform` method. It takes `()`, `(CancellationToken)`, `(TArgs)` or `(TArgs, CancellationToken)`, and returns `void`, `Task` or `ValueTask`: ```csharp public class RebuildSearchIndex(ISearchIndex index) { public Task Perform(CancellationToken cancellationToken) => index.RebuildAsync(cancellationToken); } ``` The constructor's parameters come from the job's scope: a scoped `DbContext` is the job's own. A job that implements `IDisposable` or `IAsyncDisposable` is disposed after its run. ### Arguments The arguments are serialized with System.Text.Json into the message, without .NET type names: a class or record with properties, a string, a number. Keep them small (ids rather than whole entities), and keep them compatible: during a rolling deployment an app of the old version can run a job published by the new one. Under trimming or Native AOT, list the arguments types in a `JsonSerializerContext`: see [Trimming and Native AOT](https://massivejobs.net/docs/trimming-and-aot/). ## Registering jobs Only registered jobs can be published and run. Register them on the builder that `AddMassiveJobs` returns: ```csharp builder.Services.AddMassiveJobs() .WithJobsFromAssemblyOf() // every Job/JobAsync class of that project .WithJob() // a plain class .WithJob("import.legacy"); // with a tag of your choice ``` - `WithJobsFromAssembly(assembly)` and `WithJobsFromAssemblyOf()` register the concrete classes derived from `Job` or `JobAsync` in an assembly. The list is made when the project compiles, by MassiveJobs' source generator, so nothing is scanned at runtime. Private nested classes can't be listed (warning MJ0005): make them internal. - `WithJob()` registers one class, a plain one too. A class with `Perform` methods for several argument types needs `WithJob()`. A class that can't be a job is a compile error, not a runtime surprise: see the [diagnostics](https://massivejobs.net/docs/trimming-and-aot/#diagnostics). ### Tags Every job is registered under a **tag**, the name its messages carry: the tag given to `WithJob`, else the class's `[JobTag("...")]`, else its full class name (namespace and class). ```csharp [JobTag("email.welcome")] public class SendWelcomeEmail : JobAsync { ... } ``` With an explicit tag you can rename or move the class freely; without one, a rename changes the tag, and messages already in the queues no longer match. Apps that publish a job and apps that run it must register it under the same tag. A worker that gets a tag it doesn't know holds the message back for a while (for an app that knows it), then moves it to the failed queue: see [unknown jobs](https://massivejobs.net/docs/failures-and-retries/#unknown-jobs). ## Publishing ### With `IJobPublisher` Inject `IJobPublisher` (it's scoped) and publish. The call completes when RabbitMQ has confirmed the messages: ```csharp await publisher.PublishAsync(new ResizeArgs(path, 320)); await publisher.PublishAsync(); // no arguments await publisher.PublishAsync( // many at once paths.Select(p => new ResizeArgs(p, 320))); ``` Every method has a synchronous twin, `Publish`, which blocks a thread until the broker has confirmed: for code that can't `await` (constructors, synchronous interfaces, call chains that aren't async). Prefer `PublishAsync`. To run a job later, pass a `TimeSpan` or a UTC time: see [Scheduling](https://massivejobs.net/docs/scheduling/). ### The static API Classes derived from `Job`/`JobAsync` also have static `PublishAsync` and `Publish` methods, with the same overloads, so any code can publish without injecting anything: ```csharp await ResizeImage.PublishAsync(new ResizeArgs(path, 320)); await ResizeImage.PublishAsync(new ResizeArgs(path, 320), TimeSpan.FromMinutes(5)); await ResizeImage.PublishAsync(new ResizeArgs(path, 320), cancellationToken); ResizeImage.Publish(new ResizeArgs(path, 320)); // blocks until the broker has confirmed ``` They publish through `MassiveJobsMediator.DefaultInstance`, the same publisher you'd inject. The host sets it up before any hosted service starts and clears it after all have stopped, so your hosted services can publish when they start and stop. (On a host older than 8.0, which doesn't have those lifecycle events, it's set up when MassiveJobs itself starts, so a hosted service registered before `AddMassiveJobs` can't publish in its `StartAsync` yet.) What to keep in mind: - It's one instance per process: two hosts in one process (parallel integration tests, for example) share it, and the last one started wins. Inject `IJobPublisher` there. - Code that publishes through it doesn't show the dependency, and a unit test can't swap it for a fake. - Plain job classes (registered with `WithJob`, not derived from `Job`/`JobAsync`) don't have these methods. Every static method also takes an `IJobPublisher` explicitly: `ResizeImage.PublishAsync(args, publisher)`. ### Several jobs together `JobBatch` collects the jobs published with the static methods and sends them in one go when the batch ends. Inside a batch, `PublishAsync` returns at once, and every job goes out through the batch's publisher, even one published with an explicit publisher. The batch flows across `await`, and a nested batch joins the outer one: ```csharp await JobBatch.DoAsync(async () => { foreach (var order in await LoadOrdersAsync()) { await SendInvoice.PublishAsync(order.Id); } }); ``` `IJobPublisher.PublishAsync` with a list of jobs does the same without the static API. ### Publishing isn't transactional Publishing to RabbitMQ doesn't take part in your database transaction. Publish after the data the job needs is committed, or publish just before the commit and let a failed publish (it throws) roll the transaction back. Either way there's a window where one happened and the other didn't: see [Guarantees](https://massivejobs.net/docs/guarantees/). ## Timeouts and cancellation The `CancellationToken` a job gets is cancelled when: - **its timeout is over.** A job published with a timeout (`jobTimeoutMs`, a positive number of milliseconds) that hasn't finished by then is abandoned a second later and counts as failed (it's retried). Its task keeps running until it notices the cancellation, and its services (its DI scope) stay usable until it ends. - **the default 5 seconds are over**, for a job published without a timeout. That's only a signal: such a job isn't abandoned, and isn't failed for running longer. - **the app is stopping** and the job didn't finish in time: see [stopping](https://massivejobs.net/docs/failures-and-retries/#stopping). ```csharp // may take a few minutes: give it a timeout, and it runs in the long-running queues await publisher.PublishAsync(reportId, jobTimeoutMs: 10 * 60 * 1000); ``` Jobs published with a timeout of 10 seconds or more (`LongRunningThreshold`) go to the **long-running queues**, so they don't hold up short jobs. Pass the token to everything you await: a job that ignores it can't be stopped. A synchronous job (`Job<…>`, or a plain class with a synchronous `Perform`) runs on the thread pool. Past its timeout it's abandoned like any other. A `Job<…>` gets no token, though, so nothing can stop it early: if it may need stopping, make it a `JobAsync<…>`, or a plain class whose `Perform` takes a `CancellationToken`. --- # Guarantees Source: https://massivejobs.net/docs/guarantees/ ## At least once A job's message stays in RabbitMQ until a worker has run the job and acknowledged it. If the worker's app dies, loses its connection or is stopped first, the broker delivers the message again, to that app or another. So **every published job runs at least once**, and sometimes more than once: - **The app dies right after a job finished.** Finished jobs are acknowledged in batches, at most about 100 ms later. A crash in between runs them again. - **A job ignores its cancellation token during a shutdown.** The app stops without it; its message is redelivered when the connection closes, while the old run may still be going. - **A periodic job's consumer fails over.** The next app to take over the periodic queue may run the current run again. - **A publish is retried.** If the connection breaks while RabbitMQ confirms a publish, the publisher can't tell whether the message arrived, and publishing again can make a copy. Write jobs so that running one twice does no harm (idempotent): check whether the work is already done before doing it, use unique keys, make external calls with idempotency keys where the other side supports them. ```csharp public override async Task Perform(int orderId, CancellationToken cancellationToken) { var order = await db.Orders.FindAsync([orderId], cancellationToken); if (order is null || order.InvoiceSentAt != null) return; // already done await mailer.SendInvoiceAsync(order, cancellationToken); order.InvoiceSentAt = DateTime.UtcNow; await db.SaveChangesAsync(cancellationToken); } ``` Even then there's a window: the email can go out and the save fail. Jobs with external side effects are at least once; only work done entirely in one database transaction can be exactly once. ## Nothing silently dropped A job leaves the queues only by finishing, or by landing in the **failed queue**: - it failed and ran out of retries (25 by default); - its message couldn't be read (a corrupt body, arguments that don't deserialize); - no app registered its tag for 30 minutes (`UnknownJobTimeout`); - RabbitMQ delivered it 20 times without an acknowledgement (a job that crashes the process). Nothing consumes the failed queue: [`IFailedJobs`](https://massivejobs.net/docs/failures-and-retries/#the-failed-queue) shows what's there, and requeues or purges it. The exceptions are periodic runs, which are dropped on purpose when no app defines their job any more (see [Periodic jobs](https://massivejobs.net/docs/periodic-jobs/)), and a full queue: publishing to a queue at its `MaxQueueLength` (50,000 by default) fails, so the publisher knows. ## Not transactional with your data MassiveJobs publishes to RabbitMQ, which doesn't take part in your database transaction. If you publish a job and then roll back, the job still runs; if you commit and the publish fails, there's no job. Two patterns cover most cases: - **Publish last.** Do the work, publish, then commit. A failed publish throws before the commit, so the transaction rolls back. A crash between the publish and the commit leaves a job without its data: the job should check that its data exists. - **Publish after the commit.** If losing the job is worse than a job without data, commit first and publish after, with a sweep that publishes whatever was missed. If a job must exist exactly when your data does, you need it in the same transaction: an outbox table, or a job library that stores jobs in your database, like [XactJobs](https://github.com/XactJobs/XactJobs). ## Order There's no order between jobs. They're spread over several queues, run in parallel by several apps, and a failed job comes back later. A job that must run after another should be published by it, at its end. --- # Scheduling Source: https://massivejobs.net/docs/scheduling/ Pass a `TimeSpan` or a UTC `DateTime` when you publish: ```csharp // in 15 minutes await publisher.PublishAsync(cartId, TimeSpan.FromMinutes(15)); // at a time (UTC) await publisher.PublishAsync(issueId, issue.SendAtUtc); // or with the static API, without injecting a publisher (see Jobs) await RemindAbandonedCart.PublishAsync(cartId, TimeSpan.FromMinutes(15)); ``` A `TimeSpan` is counted from the publisher's clock (`IJobPublisher.TimeProvider`, the system clock unless you register another `TimeProvider`). A time in the past runs now. A local `DateTime` (`DateTime.Now`, `DateTimeKind.Local`) is converted to UTC; one without a kind (`DateTimeKind.Unspecified`) is taken as UTC. ## Where the job waits In RabbitMQ. The message is published at once, to the queue it will run from, with its delivery time (`x-opt-delivery-time`): the quorum queue stores it and delivers it when it's due. No app holds it in memory, and nothing polls for due jobs, so: - **a scheduled job survives restarts and deployments** of every app; - **it runs in whichever app is consuming its queue then**, not in the one that published it; - **it's on time to the broker's clock**, not the apps'. Keep the broker's clock synchronised. Retries work the same way: a failed job is published again with its next retry time, to the same kind of queue. :::caution[RabbitMQ 4.4 and quorum queues] Delayed delivery is a feature of quorum queues, new in RabbitMQ 4.4. A classic queue, or a quorum queue on an older server, ignores the delivery time and delivers at once. MassiveJobs declares its queues as quorum queues and refuses to connect to RabbitMQ older than 4.4. ::: ## Which queue The publisher decides, from the job's timeout: - with a timeout of `LongRunningThreshold` (10 s) or more: a **long-running queue**; - otherwise: an **immediate queue**. Jobs are spread round robin over the queues of their kind. See [Queues and workers](https://massivejobs.net/docs/queues-and-workers/). ## Cancelling a scheduled job A published job can't be taken back. To cancel one, make the job check whether it's still wanted when it runs (the cart was bought, the newsletter was withdrawn) and return. ## Recurring jobs For something that runs on a schedule, use [periodic jobs](https://massivejobs.net/docs/periodic-jobs/), defined in code, rather than a job that publishes itself again. --- # Periodic jobs Source: https://massivejobs.net/docs/periodic-jobs/ Put `[PeriodicJob]` on a job class, and every app that registers the class runs it on that schedule. One app runs each run, however many apps define it. ```csharp // every 5 minutes, and every day at 06:00 in Sarajevo [PeriodicJob("cleanup.sessions", 300)] [PeriodicJob("report.daily", "0 0 6 * * ?", TimeZone = "Europe/Sarajevo")] public class Housekeeping(AppDbContext db) : JobAsync { public override Task Perform(CancellationToken cancellationToken) => ...; } ``` There's nothing to publish: a periodic job starts when the first app that defines it starts. ## The attribute | | | |---|---| | `id` | The periodic job's name: the same in every app, unique among the app's periodic jobs. | | `cronExpression` | Six fields, with seconds first: `second minute hour day-of-month month day-of-week`. `0 */15 * * * *` is every 15 minutes, `0 0 3 * * MON-FRI` 03:00 on weekdays. | | `intervalSeconds` | Instead of a cron expression: runs at multiples of the interval since 1970-01-01 UTC, so `60` runs at every full minute and `3600` at every full hour. | | `TimeZone` | The cron expression's time zone: UTC if not set. IANA (`Europe/Sarajevo`) or Windows ids on .NET; only Windows ids on .NET Framework. | | `Config` | A string passed to the job's argument. The job then takes a string: `JobAsync`. | | `TimeoutMs` | The job's timeout, as when publishing it. 10 s or more runs it in the long-running queues. | | `DisableConcurrentExecution` | Skips runs while the job of an earlier run hasn't finished. Needs a `TimeoutMs`. See [Runs that don't overlap](#runs-that-dont-overlap). | A class can have several attributes, e.g. one per config: ```csharp [PeriodicJob("sync.eu", "0 */10 * * * *", Config = "eu")] [PeriodicJob("sync.us", "0 */10 * * * *", Config = "us")] public class SyncRegion(IRegionSync sync) : JobAsync { public override Task Perform(string region, CancellationToken cancellationToken) => sync.RunAsync(region, cancellationToken); } ``` Invalid attributes (a bad cron expression, an unknown time zone, a `Config` on a job without a string argument, a duplicate id) fail at startup. In a time zone with daylight saving time, the expression matches the zone's local times, like Hangfire and Quartz.NET: - **Clocks go forward:** the local times they skip run once, at the end of the gap. A job at 02:30 runs at 03:00 that day. - **Clocks go back:** a local time that occurs twice runs the first time. If the expression has an interval in its seconds, minutes or hours (`*/15`, `1-3`), it runs both times, so the interval goes on: `0 */30 * * * *` still runs every 30 minutes. ## How it runs Each run is a message in the **periodic queue**, delivered by RabbitMQ at the run's time. The app consuming the queue publishes the next run, then the job (an ordinary job, retried if it fails), then acknowledges the run. Between runs no app holds anything. - **One consumer at a time.** The periodic queue has a single active consumer: of the apps that define periodic jobs, one gets the runs, and another takes over if it goes away. - **Same run times everywhere.** Run times depend only on the schedule, never on when an app started, so every app computes the same ones. Every app with workers also checks every minute (`PeriodicSeedInterval`) that the next run of each of its periodic jobs is in the broker, and publishes it otherwise. The copies this makes have the same time, and the consumer drops all but one. - **Late runs run once.** If no app ran for a while, the first run that comes due runs; the runs missed meanwhile are skipped, not caught up. A run can happen twice after the consumer fails over (it remembers the runs it handled in memory), like any job: periodic jobs should be idempotent too. See [Guarantees](https://massivejobs.net/docs/guarantees/). ## Runs that don't overlap A run publishes the job whether or not the job of the run before it has finished. A report every 5 minutes that once takes 12 minutes runs alongside the next two. With `DisableConcurrentExecution`, those runs are skipped instead: ```csharp [PeriodicJob("report.orders", "0 */5 * * * *", DisableConcurrentExecution = true, TimeoutMs = 30 * 60_000)] public class OrdersReport(ReportBuilder reports) : JobAsync { public override Task Perform(CancellationToken cancellationToken) => reports.BuildAsync(cancellationToken); } ``` :::caution[You might want to change the max retries] Runs are skipped while the job waits for a retry. With the default 25 retries, a job that keeps failing blocks its runs for about three weeks before it goes to the failed queue. Give it fewer retries, and shorter delays, with `[JobRetry]` (see [Retries of one job](https://massivejobs.net/docs/failures-and-retries/#retries-of-one-job)): ```csharp [PeriodicJob("report.orders", "0 */5 * * * *", DisableConcurrentExecution = true, TimeoutMs = 30 * 60_000)] [JobRetry(2, new[] { 30, 120 })] public class OrdersReport(ReportBuilder reports) : JobAsync { ... } ``` ::: The job still runs in the immediate or long-running queues, on any app's worker. When it has finished, it reports back to the periodic queue. Until then, the runs that come due publish only the run after them. - **Finished means succeeded, or out of retries.** A job that failed and waits for a retry hasn't finished: the runs stay skipped until the retry succeeds, or the job goes to the failed queue. - **The timeout is required.** If the report is lost, the job counts as finished once all its attempts could have run: each attempt's timeout, plus the delays between the retries (about three weeks with the default 25 retries). - **Stop on cancellation.** When a job runs past its timeout, the worker stops waiting for it, and it counts as failed. A job that ignores its cancellation token then runs on, and can overlap the next run. - **Failover.** Each run carries until when the job may still run, so an app that takes over the periodic queue skips the same runs. It can skip one run too many, if the job's report went to the app before it. ## Changing and removing periodic jobs A periodic job's **version** is a hash of its tag, schedule, config, timeout and `DisableConcurrentExecution`. Change the attribute and you have a new version: once the new code is deployed, runs of the old version are dropped when they come due, and the chain continues with the new one. During a rolling deployment the old and new apps drop each other's runs; the chain comes back within a minute (`PeriodicSeedInterval`) once one version is left. Runs in that window can be skipped. To stop a periodic job, remove its attribute. Its pending run is dropped when it comes due. :::caution[Every app with periodic jobs must define the same ones] Whichever app consumes the periodic queue drops the runs of periodic jobs it doesn't define. Apps that define periodic jobs should register the same job classes; apps that define none don't consume the queue and don't matter. ::: --- # Continuations Source: https://massivejobs.net/docs/continuations/ A continuation is a job that starts when another job has finished. It can have continuations of its own: ```csharp var import = JobInfo.For(fileId); import.ContinueWith(JobInfo.For()) .ContinueWith(JobInfo.For()); await publisher.PublishAsync(import); ``` `ContinueWith` returns the continuation, so a chain reads in order: the import, then the reports, then the mail. Publish the first job with `IJobPublisher`; the continuations go with it. The first job can be scheduled. Its continuations wait with it, and start when it has finished: ```csharp var import = JobInfo.For(fileId, DateTime.UtcNow.AddHours(2)); // runs in 2 hours import.ContinueWith(JobInfo.For()); // runs once the import has finished await publisher.PublishAsync(import); ``` ## Conditions By default a continuation runs if the job succeeded. It can also run on failure, or either way: ```csharp var import = JobInfo.For(fileId); import.ContinueWith(JobInfo.For()); import.ContinueWith(JobInfo.For(fileId), JobContinuation.OnFailure); import.ContinueWith(JobInfo.For(fileId), JobContinuation.OnFinish); ``` | Condition | Runs when the job | |---|---| | `OnSuccess` (default) | succeeded | | `OnFailure` | failed | | `OnFinish` | finished, whether it succeeded or failed | - **A job has finished** when it succeeded, or when it failed and went to the failed queue: out of retries, or a message that couldn't be read. A failed attempt that will be retried doesn't count: a job that succeeds on its second attempt succeeded, and its continuations start then. - **A continuation whose condition isn't met is skipped**, logged and counted (`massivejobs.continuation.skipped`). A skipped continuation counts as failed, so in a chain of `OnSuccess` continuations a failure skips the rest of the chain, and an `OnFailure` continuation further down still runs. ## Delays A continuation can wait after its job has finished: ```csharp var import = JobInfo.For(fileId); import.ContinueWith(JobInfo.For(), delay: TimeSpan.FromHours(1)); // an hour after the import import.ContinueWith(JobInfo.For(fileId), JobContinuation.OnFailure, TimeSpan.FromMinutes(5)); // 5 minutes after it failed ``` - **The delay counts from the job's finish**, not from its publish: a job that waits for retries delays its continuations too. - **In a chain, each delay counts from its own job.** In import → (1 hour) → report → (10 minutes) → mail, the mail goes out 10 minutes after the report has finished. - The broker holds the continuation until then, like a scheduled job. A delay is in whole milliseconds (rounded), at most ten years; zero runs it at once. ## How it works There's no state to keep anywhere: a continuation travels inside its job's message, and in the messages of its retries. When the job has finished, the worker that ran it publishes the continuations whose condition is met, then acknowledges the job. A continuation runs as an ordinary job, in the immediate or long-running queues by its timeout, on any app's worker. - **Register every job in every app that runs jobs, continuations included.** The apps share the queues, so a continuation can reach any of them. An app that doesn't register it delays it for one that does, and after `UnknownJobTimeout` sends it to the failed queue, as with any job (see [Unknown jobs](https://massivejobs.net/docs/failures-and-retries/#unknown-jobs)). The app that publishes the job needs its continuations registered too. - **The continuation is published as it was written,** from the tag and the JSON the job's message carries. A job never fails because its app doesn't know one of its continuations. - **At least once.** If publishing the continuations fails, the job goes back to its queue and runs again. - **A continuation that can't be read** (a corrupt message) goes to the failed queue as it is, with the reason; its job is done. - **A job requeued from the failed queue** (`IFailedJobs.RequeueAsync`) starts over without its continuations: they ran, or were skipped, when it failed. - **Retries per job** apply to continuations like to any job (see [Retries of one job](https://massivejobs.net/docs/failures-and-retries/#retries-of-one-job)). ## Limits - **Continuations start when their job has finished**, or a delay after it. A continuation can't have a run time of its own (the first job can), and a run of a periodic job can't have continuations. - **Add continuations before publishing the job.** They're part of its message; a published message can't change. - **The default serializer only.** An app that replaces `IJobSerializer` can't publish continuations. - **Upgrading from 1.0:** a 1.0 app ignores continuations. If it runs or retries a job with continuations, they're lost. Publish continuations once every app that runs jobs is on 1.1. --- # Failures, retries and stopping Source: https://massivejobs.net/docs/failures-and-retries/ ## Retries A job fails when `Perform` throws, or when it runs past an explicit timeout. MassiveJobs then publishes it again, delayed: the broker holds it until its retry time, and any app's worker runs it then. The delays grow with each retry, like Sidekiq's: _retries⁴ + 15 s_, plus some randomness. | Retry | About | |---|---| | 1st | 15 to 45 seconds | | 5th | 6 minutes | | 10th | 2 hours | | 20th | 1.5 days | | 25th | 4 days | With the default `MaxRetries` of 25 a job runs at most 26 times, over about three weeks, before it goes to the failed queue. Set `MaxRetries = 0` to send failed jobs there at once. The app that runs the job decides. ### Retries of one job `[JobRetry]` on a job class sets its own retries, and optionally its own delays, in place of `MaxRetries` and the delays above: ```csharp [JobRetry(3, new[] { 10, 60, 300 })] // up to 3 retries: after 10 seconds, a minute, then 5 minutes public class ExportInvoice(IExporter exporter) : JobAsync { public override Task Perform(int invoiceId, CancellationToken cancellationToken) => exporter.ExportAsync(invoiceId, cancellationToken); } [JobRetry(0)] // no retries: a failure goes to the failed queue at once public class SendSms(ISmsSender sms) : JobAsync { public override Task Perform(string text, CancellationToken cancellationToken) => sms.SendAsync(text, cancellationToken); } ``` - **The delays are in seconds**, one per retry; the last one repeats for the retries beyond the list. Without them, the growing delays above apply. - **Plain job classes** registered with `WithJob()` can have it too, and derived job classes inherit it. - **The app that runs the job decides**, as with `MaxRetries`: apps that share a job register the same class, so they agree. - Negative retries or delays fail at startup. The job's last error and its retry count travel with it. MassiveJobs logs every failure at error level, with the exception and the retry count. :::tip[Errors that won't go away] A job that can never succeed (the order doesn't exist any more) should return rather than throw, or it will be retried for three weeks. ::: ## The failed queue Jobs that ran out of retries end up in the failed queue (`{prefix}massivejobs.failed`), together with messages that couldn't be read as a job, jobs no app registered, and messages RabbitMQ gave up on. Nothing consumes it. Inject `IFailedJobs` to look at it and act on it, e.g. from an admin endpoint: ```csharp var failed = app.MapGroup("/admin/failed-jobs"); failed.MapGet("/", async (IFailedJobs jobs) => (await jobs.PeekAsync(50)) .Select(f => new { f.JobTag, f.Error, f.OriginalQueue, Retries = f.Job?.Retries })); failed.MapGet("/count", (IFailedJobs jobs) => jobs.CountAsync()); // once the bug is fixed failed.MapPost("/requeue", (IFailedJobs jobs, string? tag) => jobs.RequeueAsync(f => tag == null || f.JobTag == tag)); failed.MapDelete("/", (IFailedJobs jobs, string tag) => jobs.PurgeAsync(f => f.JobTag == tag)); ``` | Method | | |---|---| | `CountAsync()` | How many messages are there (approximate while others look at them). | | `PeekAsync(maxCount)` | The oldest ones, with the job, its arguments, the error and the queue it came from. They stay. | | `RequeueAsync(filter)` | Publishes them again and removes them. A job starts over: it runs now, with a fresh retry count. | | `PurgeAsync(filter)` | Deletes them. | A message the app can't read (a tag it doesn't register, a corrupt body) goes back unchanged to the queue it came from, if that's known. A requeued run of a periodic job runs once, as an ordinary job. A queue has no random access: each call reads the messages from the front, and holds the ones it reads until it returns. Meanwhile, other calls don't see them. ## Unknown jobs During a rolling deployment the new version of an app can publish a job that the old version, still running, doesn't register. A worker that gets a tag it doesn't know **delays** the message (5 seconds, growing to a minute) so that an app that knows the job gets it, and after `UnknownJobTimeout` (30 minutes) moves it to the failed queue. So deploy apps that run a new job before, or together with, apps that publish it. Apps whose workers share queues should register the same jobs. ## Stopping When the host stops, the workers stop taking jobs at once and let the running ones finish: 1. The running jobs get `ShutdownTimeout` (20 s) to finish. They're acknowledged as usual. 2. Then their cancellation token is cancelled, and the workers wait at most 5 seconds more. 3. A job still running then is left behind. Its message goes back to the queue when the app's connection closes, so it can run twice. A job cancelled by the shutdown **doesn't count as failed**, whatever it throws: no retry, no failed queue. It runs again from the start, in this app or another. The host has its own limit, `HostOptions.ShutdownTimeout` (30 s by default), after which it cancels the stop and with it the running jobs. Make `ShutdownTimeout` plus 5 seconds fit in it: ```csharp builder.Services.Configure(o => o.ShutdownTimeout = TimeSpan.FromSeconds(60)); builder.Services.AddMassiveJobs(o => o.ShutdownTimeout = TimeSpan.FromSeconds(45)); ``` Messages a worker had received but not started go back to the queue at once. RabbitMQ counts each such return as a delivery: a message returned 20 times goes to the failed queue, from where you can requeue it. --- # Queues and workers Source: https://massivejobs.net/docs/queues-and-workers/ ## The queues With the defaults, MassiveJobs uses these queues on RabbitMQ (all quorum queues, bound to one direct exchange, `massivejobs.direct`): | Queue | For | Consumed by | |---|---|---| | `massivejobs.immediate.00` … `.03` | jobs, scheduled jobs and their retries | a worker in every app that runs workers | | `massivejobs.long-running.00`, `.01` | jobs published with a timeout of 10 s or more | a worker in every app that runs workers | | `massivejobs.periodic` | the runs of periodic jobs | one app at a time, among those that define periodic jobs | | `massivejobs.failed` | jobs that ran out of retries, unreadable and unknown messages | nobody: see `IFailedJobs` | `NamePrefix` goes in front of every name (`shop.massivejobs.immediate.00`), so separate systems can share a broker or a virtual host. ## Publishing: round robin A publisher sends each job to the next queue of its kind, in turn. The queues fill evenly, whichever app publishes. That's why **apps that share jobs must use the same queue counts** (`ImmediateWorkersCount`, `LongRunningWorkersCount`) **and the same `NamePrefix`**. An app with 4 immediate queues publishes to `.00` … `.03`; an app configured with 2 consumes only `.00` and `.01`, and the jobs in the other two wait for an app that consumes them. The defaults agree; if you change a count, change it everywhere. ## Workers: one per queue, in every app Each app that runs workers (`StartWorkers`, true by default) has a worker per queue: 4 immediate and 2 long-running. On RabbitMQ several consumers of one queue take turns, so with three apps running, every queue has three consumers, and adding an app adds capacity to every queue. A worker runs `MaxDegreeOfParallelismPerWorker` jobs at once: **1 by default**. So an app runs, by default, up to 4 immediate and 2 long-running jobs at the same time. - **More queues** raise the throughput of short jobs, and spread a burst over more consumers. On the drain benchmark, 4 queues × 1 job emptied a backlog of no-op jobs at about 95,000 jobs/s; 2 × 2 at 72,000; 1 × 4 at 44,000. - **More jobs per worker** help jobs that mostly wait: on HTTP calls, the database, the disk. With `MaxDegreeOfParallelismPerWorker = 8`, an app runs up to 32 immediate jobs at once without new queues. Changing the parallelism is local to an app; changing the queue counts is not (see above). ## Prefetch and acknowledgements An immediate worker holds up to `BatchSize` messages (**250** by default, so 1,000 per app with the defaults): received from the broker and not acknowledged yet. That keeps workers busy without asking for every job. Finished jobs are acknowledged together, half a batch at a time, or after 100 ms. Messages a worker holds are invisible to other apps until it acknowledges or returns them. If an app dies, RabbitMQ gives them to another one; the jobs it had finished but not yet acknowledged run again. A smaller batch means fewer jobs held by one app, at some cost in throughput. Long-running workers hold twice their parallelism, so long jobs don't wait behind each other in one app while another is idle. ## Full queues Each job queue holds at most `MaxQueueLength` messages (50,000 by default; `QueueLength.NoLimit` for no limit). Publishing to a full queue fails: the publisher throws. Scheduled jobs and retries count, since they wait in the queues. ## Apps that only publish Set `StartWorkers = false` in an app that publishes jobs but shouldn't run them. It needs the same queue counts and prefix as the apps that run the jobs, and the same jobs registered. ```csharp builder.Services.AddMassiveJobs(o => o.StartWorkers = false) .WithJobsFromAssemblyOf() .UseRabbitMq(o => o.ConnectionString = builder.Configuration.GetConnectionString("RabbitMq")); ``` --- # Metrics, traces and health Source: https://massivejobs.net/docs/observability/ ## Traces and metrics MassiveJobs records on an `ActivitySource` and a `Meter`, both named `MassiveJobs`. Collect them with OpenTelemetry: ```csharp builder.Services.AddOpenTelemetry() .WithTracing(t => t.AddSource(MassiveJobsTelemetry.ActivitySourceName)) .WithMetrics(m => m.AddMeter(MassiveJobsTelemetry.MeterName)); ``` Nothing is recorded while nothing listens. ### Traces Each run of a job is an activity (a span of kind consumer), named by the job's tag. It's **linked to the trace that published the job**: the publisher puts the current W3C `traceparent` in the message, so the run of a job published while handling a request points back to that request. The job's own activities (HttpClient's, EF Core's) are inside the run's. A retry published by a run links to that run. On .NET Framework without OpenTelemetry's SDK, activity ids aren't W3C by default; set `Activity.DefaultIdFormat = ActivityIdFormat.W3C` and `Activity.ForceDefaultIdFormat = true` at startup to get the links. ### Metrics | Metric | Type | | |---|---|---| | `massivejobs.job.attempts` | counter | Runs, by `massivejobs.outcome`: `completed`, `retried`, `failed` (to the failed queue), `interrupted` (by a shutdown). | | `massivejobs.job.duration` | histogram (s) | Run time, by outcome. | | `massivejobs.job.running` | up-down counter | Jobs running now, per queue. | | `massivejobs.job.published` | counter | Jobs published. | | `massivejobs.message.unknown_tag` | counter | Messages with a tag the app doesn't register. | | `massivejobs.message.unreadable` | counter | Messages that couldn't be read as a job. | | `massivejobs.periodic.runs` | counter | Runs of periodic jobs, by what happened to them. | | `massivejobs.continuation.skipped` | counter | Continuations not published: the job's outcome didn't meet their condition. | The tags are `massivejobs.queue`, `massivejobs.job.tag` and `massivejobs.outcome`. The job tag is always a registered one (except on `massivejobs.message.unknown_tag`, which is rare), so stray messages can't blow up the cardinality. ## Health check `MassiveJobsHealthCheck` reports whether this app's workers are consuming: ```csharp builder.Services.AddHealthChecks().AddCheck("massivejobs"); app.MapHealthChecks("/health"); ``` - **Healthy:** every worker is connected and consuming, or the app runs no workers. - **Degraded:** a worker is connecting, or waiting to reconnect after it lost its channel. - **Unhealthy** (the registration's failure status): a worker has been without a connection for a minute, e.g. the broker is down. The result's data has each queue's state. Publishing isn't checked: it connects on demand, and a failed publish throws. ## Logs MassiveJobs logs through `Microsoft.Extensions.Logging`, under its classes' names (`MassiveJobs.Core.*`, `MassiveJobs.RabbitMqBroker.*`). Each message has a stable event id: 1–38 in Core, 1001–1012 in the RabbitMQ broker. Failed jobs are logged as errors, with the exception; a lost connection as a warning; connections, worker restarts, starts and stops as information. --- # Testing Source: https://massivejobs.net/docs/testing/ ## The in-memory broker `UseInMemoryBroker()` replaces RabbitMQ with queues in the test's process. Jobs are published, routed, retried and delayed as on RabbitMQ, but nothing leaves the process. ```csharp var services = new ServiceCollection(); services.AddLogging(); services.AddSingleton(orders); // whatever your jobs need services.AddMassiveJobs() .WithJobsFromAssemblyOf() .UseInMemoryBroker(); await using var provider = services.BuildServiceProvider(); var jobs = MassiveJobsMediator.Initialize(provider); await jobs.StartAsync(); try { await jobs.PublishAsync(42); await WaitUntil(() => orders.Get(42).InvoiceSent); } finally { await jobs.StopAsync(); MassiveJobsMediator.Deinitialize(); } ``` `MassiveJobsMediator` is an `IJobPublisher` too, so tests can publish without a scope. The jobs run on other threads: wait for their effect with a timeout (a loop that checks a condition), not a fixed sleep. `MassiveJobsMediator.Initialize` sets the static instance the static `PublishAsync`/`Publish` methods use, so tests that start MassiveJobs this way can't run in parallel with each other. ## Fake time MassiveJobs reads the clock and waits only through the `TimeProvider` in DI: scheduled jobs, retries, timeouts, periodic runs, the in-memory broker's delays. Register a `FakeTimeProvider` (package `Microsoft.Extensions.TimeProvider.Testing`) and move time yourself: ```csharp var time = new FakeTimeProvider(new DateTimeOffset(2026, 1, 5, 9, 0, 0, TimeSpan.Zero)); services.AddSingleton(time); services.AddMassiveJobs().WithJobsFromAssemblyOf().UseInMemoryBroker(); // ...start as above await jobs.PublishAsync(7, TimeSpan.FromMinutes(15)); time.Advance(TimeSpan.FromMinutes(14)); Assert.IsFalse(reminders.Sent(7)); // not due yet time.Advance(TimeSpan.FromMinutes(1)); await WaitUntil(() => reminders.Sent(7)); // due: it runs ``` A delay starts when its message reaches the broker. Advance the clock only after that: for a job you published, once `PublishAsync` returned; for a retry, once the failed run is over (wait for it, e.g. for the job's own record of the attempt). Time advanced before a timer exists doesn't count for it. The same works for retries (advance past the backoff), job timeouts and [periodic jobs](https://massivejobs.net/docs/periodic-jobs/) (advance to the next run time). ## Testing a job on its own A job is a class: construct it with fakes and call `Perform`. That covers its logic; the in-memory broker covers its registration, arguments and wiring. --- # Trimming and Native AOT Source: https://massivejobs.net/docs/trimming-and-aot/ MassiveJobs never looks for jobs by reflection. A **source generator**, shipped in the MassiveJobs.Core package, runs in every project that references it and writes the code that registers and calls its jobs. So: - both libraries are free of trimming and AOT warnings on .NET, and apps that use them can be trimmed or compiled with Native AOT; - a class that can't be a job is a compile error, not a startup failure; - nothing scans assemblies at startup. The generator needs a C# compiler from the .NET 8 SDK or Visual Studio 2022 17.8 on. The code it writes is C# 7.3, so .NET Framework projects work too. ## What the generator sees - **Classes derived from `Job` or `JobAsync`.** Every concrete, non-generic one in the project, listed for `WithJobsFromAssembly`. They run through their base class. - **Plain classes passed to `WithJob()`.** For each, the generator writes the call to its `Perform`. Only calls it can see at compile time count: `WithJob()` with a concrete type, in your code. If you wrap `WithJob` in a generic method of your own, mark its type parameter with `[JobTypeArgument]` (and an arguments type parameter with `[JobArgsTypeArgument]`): the generator then looks at the calls of your method instead. ```csharp using System.Diagnostics.CodeAnalysis; using MassiveJobs.Core; using MassiveJobs.Core.Generated; public static class JobRegistrations { public static MassiveJobsBuilder WithAuditedJob< [JobTypeArgument, DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TJob>( this MassiveJobsBuilder builder) where TJob : class => builder.WithJob(); } ``` `DynamicallyAccessedMembers` tells the trimmer to keep the job's constructors, which MassiveJobs calls. ## Diagnostics | Id | Severity | | |---|---|---| | MJ0001 | error | The class can't be a job: no public `Perform` method of a supported shape. | | MJ0002 | error | `Perform` methods for several argument types: register it with `WithJob()`. | | MJ0003 | error | No `Perform` method for the arguments type given to `WithJob()`. | | MJ0004 | error | The job type is a type parameter the generator can't follow: pass a concrete type, or mark the parameter `[JobTypeArgument]`. | | MJ0005 | warning | A private or protected nested job class: `WithJobsFromAssembly` can't register it. Make it internal or public. | | MJ0006 | error | A private or protected class passed to `WithJob`: make it internal or public. | | MJ0007 | warning | A method's `[JobTypeArgument]` type parameter can be inferred from its arguments. The generator sees only calls that name it (`AddJob(…)`): name it in every call. | ## Arguments under Native AOT The arguments are serialized with System.Text.Json. Without reflection it needs metadata for their types: list them in a `JsonSerializerContext` and give it to MassiveJobs. ```csharp [JsonSerializable(typeof(ResizeArgs))] [JsonSerializable(typeof(InvoiceArgs))] internal partial class JobsJsonContext : JsonSerializerContext { } builder.Services.AddMassiveJobs(o => o.JsonTypeInfoResolver = JobsJsonContext.Default) .WithJobsFromAssemblyOf() .UseRabbitMq(); ``` Strings and other primitive types need no metadata. MassiveJobs checks at startup that every registered job's arguments type has some, and fails with the names of those that don't. Without a resolver, reflection-based serialization is used where it's enabled. --- # Using MassiveJobs with AI agents Source: https://massivejobs.net/docs/ai-agents/ Coding assistants know MassiveJobs from its older releases, whose API is different. Point them at the current docs: - [`/llms.txt`](/llms.txt): an index of these pages, with a line on each. - [`/llms-full.txt`](/llms-full.txt): every page as plain markdown, in one file. Give it to an agent as context, or put it in your repository's agent instructions as a link. A line like this in your `AGENTS.md` or `CLAUDE.md` is usually enough: ```markdown Background jobs use MassiveJobs 1.1 (RabbitMQ). Its docs, as markdown: https://massivejobs.net/llms-full.txt Don't use the 0.4x API (JobsBuilder, PublishPeriodic, MassiveJobs.*.Hosting packages). ``` Working on MassiveJobs itself? The repository's [`AGENTS.md`](https://github.com/enadzan/massivejobs/blob/master/AGENTS.md) has the build, the tests, the architecture and the rules for changes. --- # Configuration Source: https://massivejobs.net/docs/configuration/ Both sets of options are standard .NET options (`IOptions`, `IOptions`): set them in code, bind them from configuration, or both. They're validated when MassiveJobs starts; invalid options stop the host from starting. ```csharp builder.Services.AddMassiveJobs(o => { o.NamePrefix = "shop."; o.MaxDegreeOfParallelismPerWorker = 4; }) .WithJobsFromAssemblyOf() .UseRabbitMq(o => o.ConnectionString = builder.Configuration.GetConnectionString("RabbitMq")); ``` ## From configuration ```csharp builder.Services.AddOptions().BindConfiguration("MassiveJobs"); builder.Services.AddOptions().BindConfiguration("RabbitMq"); ``` ```json { "MassiveJobs": { "NamePrefix": "shop.", "MaxDegreeOfParallelismPerWorker": 4, "ShutdownTimeout": "00:00:45" }, "RabbitMq": { "ConnectionString": "amqps://shop:secret@rabbit.example.com/shop" } } ``` `BindConfiguration` comes from `Microsoft.Extensions.Options.ConfigurationExtensions`, which ASP.NET Core and worker service apps already have. MassiveJobs itself doesn't depend on configuration. ## `MassiveJobsOptions` Options marked **shared** must be the same in every app that shares the jobs. | Option | Default | | |---|---|---| | `NamePrefix` | `""` | Prefix of the queue and exchange names. **Shared.** | | `StartWorkers` | `true` | Whether this app runs workers. `false` for an app that only publishes. | | `ImmediateWorkersCount` | `4` | Immediate queues, each with a worker in every app that runs workers. **Shared.** | | `LongRunningWorkersCount` | `2` | Long-running queues. **Shared.** | | `MaxDegreeOfParallelismPerWorker` | `1` | Jobs a worker runs at once (at most 65,535). | | `BatchSize` | `0` (250) | Messages an immediate worker holds unacknowledged (the prefetch). | | `PublishBatchSize` | `100` | The most messages sent in one call when publishing many jobs. | | `MaxQueueLength` | `50,000` | The most messages a queue holds; publishing to a full queue fails. `QueueLength.NoLimit` (-1) for none. | | `MaxRetries` | `25` | Retries of a failed job before the failed queue. `0`: none. `[JobRetry]` on a job class sets its own. | | `LongRunningThreshold` | `10 s` | Jobs published with at least this timeout go to the long-running queues. | | `ShutdownTimeout` | `20 s` | How long running jobs get to finish when the app stops. | | `UnknownJobTimeout` | `30 min` | How long a job with a tag no app knows is delayed before the failed queue. | | `PeriodicSeedInterval` | `1 min` | How often each app checks that the next run of each of its periodic jobs is in the broker. | | `JsonTypeInfoResolver` | `null` | System.Text.Json metadata for the jobs' arguments, e.g. a `JsonSerializerContext`. Needed under trimming and Native AOT. | The queue names are read-only properties: `ImmediateQueueNameTemplate`, `LongRunningQueueNameTemplate`, `PeriodicQueueName`, `FailedQueueName`. ## `RabbitMqOptions` Set either `ConnectionString` or the connection properties, not both. Without either, MassiveJobs connects to localhost as `guest`. | Option | Default | | |---|---|---| | `ConnectionString` | | An AMQP URI: `amqp://user:password@host:port/vhost`, `amqps://` for TLS. Percent-encode special characters; the default vhost `/` is `%2F`, or left out. | | `HostNames` | `localhost` | The nodes, tried in order until one accepts the connection. | | `Port` | `-1` | 5672, or 5671 with TLS. | | `VirtualHost` | `/` | | | `Username`, `Password` | `guest` | RabbitMQ accepts `guest` only from localhost. | | `SslEnabled` | `false` | | | `SslServerName` | the host name | The name the server's certificate must have. | | `SslClientCertPath`, `SslClientCertPassPhrase` | | A client certificate, for TLS with client authentication. | The prefetch count is `MassiveJobsOptions.BatchSize`. See [RabbitMQ](https://massivejobs.net/docs/rabbitmq/) for what MassiveJobs declares on the broker. ## Other services `AddMassiveJobs` registers its services with `TryAdd`, so you can replace them by registering your own first. The one worth knowing is `TimeProvider`: MassiveJobs reads the clock and waits only through it, which is how [tests](https://massivejobs.net/docs/testing/) run scheduled jobs on fake time. --- # RabbitMQ Source: https://massivejobs.net/docs/rabbitmq/ ## Version MassiveJobs needs **RabbitMQ 4.4 or later**, and checks it when it connects: on an older server it refuses to start. 4.4 added delayed delivery to quorum queues (`x-opt-delivery-time`), which scheduled jobs, retries and periodic jobs rely on. No plugin is needed. ## Connecting The simplest is a connection string, an AMQP URI: ```csharp .UseRabbitMq(o => o.ConnectionString = "amqps://shop:secret@rabbit.example.com/shop") ``` Or the properties, e.g. for a cluster: ```csharp .UseRabbitMq(o => { o.HostNames = ["rabbit-1.internal", "rabbit-2.internal", "rabbit-3.internal"]; o.VirtualHost = "shop"; o.Username = "shop"; o.Password = builder.Configuration["RabbitMq:Password"]; o.SslEnabled = true; }) ``` Each app opens one connection, named `MassiveJobs.NET/{your app's assembly}` in the management UI, with channels for publishing and for each worker. A lost connection is re-established: each worker restarts on its own, with a backoff of 1 to 60 seconds, and publishing reconnects on demand. Meanwhile the [health check](https://massivejobs.net/docs/observability/#health-check) reports the workers as degraded. ## What MassiveJobs declares At its first connection, an app declares (idempotently) the exchange and the queues it uses, with `NamePrefix` in front: - the direct exchange `massivejobs.direct`, each queue bound to it by its own name; - the job queues (immediate, long-running, periodic): quorum queues with - `x-dead-letter-exchange` and `x-dead-letter-routing-key`: the failed queue, - `x-dead-letter-strategy = at-least-once`, `x-overflow = reject-publish`, - `x-max-length` = `MaxQueueLength`, unless it's `NoLimit`, - and on the periodic queue `x-single-active-consumer`; - the failed queue: a quorum queue with `x-delivery-limit = -1`, so that looking at it doesn't use up its messages' deliveries. The user needs the `configure`, `write` and `read` permissions on these in its virtual host. Quorum queues have a delivery limit of 20: a message delivered 20 times without being acknowledged (the job crashes the process every time, or the app keeps returning it while stopping) goes to the failed queue. RabbitMQ refuses to declare an existing queue with other arguments (`PRECONDITION_FAILED - inequivalent arg`). After changing `MaxQueueLength` on a running system, delete the queues first, or use a new `NamePrefix`. ## Running it locally ```bash docker run -d --name rabbit -p 5672:5672 -p 15672:15672 rabbitmq:4-management ``` The management UI is on [localhost:15672](http://localhost:15672), user and password `guest`. Quorum queues are stored on disk: `docker rm -fv rabbit` removes the container with its data. ## Other brokers MassiveJobs.Core also has an in-memory broker (`UseInMemoryBroker()`), for [tests](https://massivejobs.net/docs/testing/) and for single-process apps: jobs run in the process that published them, and are lost when it stops. --- # Throughput and benchmarks Source: https://massivejobs.net/docs/throughput/ The repository has a benchmark, `drain`: it publishes a backlog of no-op jobs, starts the workers, and measures how fast they empty the queues. No-op jobs measure MassiveJobs and the broker, not your jobs: real jobs are usually slower than the machinery around them, and then the parallelism you give them matters more. ## Results 100,000 no-op jobs, MassiveJobs' defaults (4 immediate queues, 1 job per worker, batches of 250), one app, RabbitMQ 4.4 in a container on the same 4-vCPU machine: | Broker | Jobs per second | Allocated per job | |---|---|---| | RabbitMQ 4.4 | about 95,000–100,000 | 1.7 KB | | In memory | about 800,000 | 0.7 KB | The job is a `JobAsync` that finishes at once, so these numbers are MassiveJobs' own overhead. A synchronous job (`Job<…>`, or a plain class with a synchronous `Perform`) runs on the thread pool, so that an explicit timeout can abandon it: that costs about 0.7 KB more per job, and on RabbitMQ about 15% more CPU per job at the same throughput. Single runs on RabbitMQ vary by up to 15%. Compare setups in alternating rounds, on the same machine. ## The queue layout The same 4 jobs at once, arranged differently (RabbitMQ, same machine): | Queues × jobs per worker | Jobs per second | |---|---| | 4 × 1 (the default) | about 95,000 | | 2 × 2 | about 72,000 | | 1 × 4 | about 44,000 | For short jobs, the queues set the throughput: each queue is consumed in order, and more queues spread the work over more of the broker. For jobs that mostly wait, more jobs per worker are the cheaper lever. See [Queues and workers](https://massivejobs.net/docs/queues-and-workers/). The batch size (the prefetch) matters too. In an earlier measurement, on an older layout, a batch of 1 drained 500 jobs/s, 8 drained 3,000, 200 drained 40,000 and 1,000 drained 65,000: with a small batch the workers wait for the broker between jobs. Acknowledging finished jobs together rather than one by one added about a third. ## Run it ```bash git clone https://github.com/enadzan/massivejobs && cd massivejobs docker run -d --name mj-rabbit -p 5672:5672 -e RABBITMQ_DEFAULT_VHOST=massivejobs.tests rabbitmq:4-management dotnet build MassiveJobs.Benchmarks -c Release dotnet MassiveJobs.Benchmarks/bin/Release/net10.0/MassiveJobs.Benchmarks.dll drain --rabbitmq dotnet MassiveJobs.Benchmarks/bin/Release/net10.0/MassiveJobs.Benchmarks.dll drain --runs 7 # in memory docker rm -fv mj-rabbit ``` `--jobs`, `--runs`, `--workers`, `--parallelism` and `--batch-size` change the setup. --- # Upgrading from 0.45 Source: https://massivejobs.net/docs/upgrading/ 1.0 is a breaking release, and doesn't share queues with 0.4x apps: upgrade every app that shares jobs together, onto empty queues. The full list of changes is in the [changelog](https://github.com/enadzan/massivejobs/blob/master/CHANGELOG.md). ## Before you start - **RabbitMQ 4.4 or later.** 1.0 refuses older servers: it needs the quorum queues' delayed delivery. - **Empty queues.** 1.0 declares quorum queues, and has no scheduled, error or stats queues. RabbitMQ won't redeclare a classic queue as a quorum queue: let the 0.4x apps drain their queues and delete them, or give 1.0 a new `NamePrefix` or virtual host. Messages of 0.4x aren't migrated, scheduled and periodic ones included. ## Packages Use `MassiveJobs.Core` and `MassiveJobs.RabbitMqBroker`. Remove: - `MassiveJobs.Core.Hosting` and `MassiveJobs.RabbitMqBroker.Hosting`: Core does the hosting now. - `MassiveJobs.Logging.Log4Net`, `.NLog`, `.Serilog`: MassiveJobs logs through `Microsoft.Extensions.Logging`; plug your logger in there. - `MassiveJobs.SqlServerBroker`: removed. ## Configuration `JobsBuilder.Configure()…Build()` and `services.AddMassiveJobs().UseRabbitMqBroker()` become one way for every app: ```csharp // 0.45 JobsBuilder.Configure() .WithRabbitMqBroker(s => { s.HostNames = new[] { "rabbit.example.com" }; s.Username = "massive"; s.Password = "secret"; }) .Build(); // 1.0 services.AddMassiveJobs() .WithJobsFromAssemblyOf() .UseRabbitMq(o => o.ConnectionString = "amqp://massive:secret@rabbit.example.com/"); ``` | 0.45 | 1.0 | |---|---| | `MassiveJobsSettings` | `MassiveJobsOptions`, standard .NET options | | `RabbitMqSettings` | `RabbitMqOptions`, with `ConnectionString` | | `Build(startWorkers: false)` | `o.StartWorkers = false` | | `JobsBuilder.DisposeJobs()` | the host stops it; without one, `StopAsync` and `MassiveJobsMediator.Deinitialize()` | | `RabbitMqSettings.PrefetchCount` | `MassiveJobsOptions.BatchSize` | | `ScheduledWorkersCount`, `PeriodicWorkersCount` | gone: no scheduled queues, one periodic queue | | `*WorkersBatchSize` | `BatchSize` | Without a host, start MassiveJobs once the service provider is built: `await MassiveJobsMediator.Initialize(provider).StartAsync()`. The defaults changed too: 4 immediate queues (was 2) and 2 long-running (was 1), each running one job at a time (was 2). An app still runs 4 immediate jobs at once. ## Jobs - **Register them.** Only registered jobs are published and run: `WithJobsFromAssemblyOf()` for the `Job`/`JobAsync` classes of a project, `WithJob()` for others. Messages carry the job's tag instead of .NET type names: the class's full name by default, or `[JobTag("...")]`. See [Jobs](https://massivejobs.net/docs/jobs/#registering-jobs). - **Private nested job classes** must become internal: the source generator can't call them. - **The job's constructor** is chosen by `ActivatorUtilities`, every parameter from the job's scope. - **Timeouts are enforced** for jobs published with one: a job that runs past it is abandoned and retried. - **`MaxRetries` counts retries**: with 25 a job runs at most 26 times (it was 25). ## Periodic jobs `PublishPeriodic` and `CancelPeriodic` are gone. Periodic jobs are defined in code, with an attribute on the job class: ```csharp // 0.45, at startup CleanupJob.PublishPeriodic("cleanup", "0 0 3 * * ?"); // 1.0 [PeriodicJob("cleanup", "0 0 3 * * ?")] public class CleanupJob : Job { ... } ``` To stop one, remove the attribute. See [Periodic jobs](https://massivejobs.net/docs/periodic-jobs/). ## Publishing The static `Publish` methods still work, and gained async twins: `await MyJob.PublishAsync(args)`. `IJobPublisher` gained `PublishAsync`, and every `Publish` extension method has an async twin: prefer them. `JobBatch.Do` gained `DoAsync`, and batches can be nested.