Queues
- Introduction
- Complete Example: Dispatch and Process a Job
- Creating Jobs
- Dispatching Jobs
- Unique Jobs
- Job Middleware
- Job Chaining
- Job Batching
- Running the Queue Worker
- The Queue Manager
- Dealing With Failed Jobs
- Testing
Complete Example: Dispatch and Process a Job
Use the Blog template, whose migrations and queue configuration include the database driver. Add this file:
// app/Jobs/DocumentationReceipt.cs
using DotBlaze;
namespace Blog.Jobs;
public class DocumentationReceipt : Job, IShouldQueue
{
public Guid ReceiptId { get; init; }
public override int Tries => 3;
public override int[] Backoff => [5, 15];
public override TimeSpan? Timeout => TimeSpan.FromSeconds(30);
public override async Task Handle()
{
Cancellation.ThrowIfCancellationRequested();
await Storage.Disk("local").Put(
$"documentation/{ReceiptId:N}.txt", "The documentation job completed.");
Log.Info("Documentation receipt {Id} written", ReceiptId);
}
}
public class DispatchDocumentationReceipt : Command
{
public override string Signature => "demo:queue";
public override async Task<int> Handle()
{
var id = Guid.NewGuid();
await new DocumentationReceipt { ReceiptId = id }.Dispatch()
.OnConnection("database").OnQueue("documentation");
Line($"Queued documentation/{id:N}.txt");
return 0;
}
}Run these sequentially from Blog:
dotblaze migrate
dotblaze demo:queue
dotblaze queue:work --connection=database --queue=documentation --stop-when-empty
dotblaze queue:failedExpected: dispatch prints a relative receipt path; the worker creates it under the configured private local disk (storage/app/private in the template); queue:failed has no new entry. Dispatch chooses the database connection explicitly even if the default is sync. The serialized GUID makes retries write the same receipt with the same content.
Keep the job timeout below the connection's retry_after, and configure the same storage path/driver in separate web/worker processes. Queue.Fake() proves dispatch only; it cannot prove that Handle executed. See QueueTest.cs for real worker tests.
Introduction
Queues move slow work, such as sending email or calling an external API, out of the HTTP request. DotBlaze has its own queue engine, modelled on Laravel's: jobs are serialized to JSON, stored by a queue driver, and run by a worker process.
The configuration lives in config/Queue.cs:
public class QueueConfig : ConfigFile
{
public override object Values() => new
{
@default = "database",
worker = false,
connections = new
{
sync = new { driver = "sync" },
database = new { driver = "database", queue = "default", retry_after = 90 },
redis = new { driver = "redis", connection = "default", queue = "default", retry_after = 90 },
},
};
}| Key | Description |
|---|---|
default | The queue connection used when none is given. Defaults to sync. |
worker | true runs a worker inside the web app, see below. |
worker_queues | Comma-separated queues for that in-app worker. Defaults to default. |
connections.*.driver | sync, database, or redis (package DotBlaze.Redis, see Redis). Defaults to the connection name. |
connections.*.queue | The queue jobs go to when none is given. Defaults to default. |
connections.*.retry_after | Seconds after which a reserved job counts as abandoned and is handed out again. Defaults to 90. |
connections.*.connection | database: the database connection holding the jobs table (default: the default connection). redis: the Redis connection (default: default). |
Connections vs. Queues
As in Laravel, a connection is a backend (sync, database), and a queue is a named list of jobs on that connection (default, emails). Workers can be told which queues to process and in which order.
Driver Notes and Prerequisites
Sync
The sync driver runs the job immediately, in the same request. The job still goes through JSON serialization, so payload mistakes show up during development. If the job throws, its Failed method is called and the exception is rethrown to the code that dispatched it. Tries, Backoff, and Timeout do not apply.
Database
The database driver stores jobs in a jobs table and failed jobs in failed_jobs. New applications already include this migration in database/migrations:
[Migration("0001_01_01_000001_create_jobs_table")]
public class CreateJobsTable : Migration
{
public override void Up()
{
Schema.Create("jobs", t =>
{
t.Id();
t.String("queue").Index();
t.Text("payload");
t.Integer("attempts");
t.BigInteger("reserved_at").Nullable();
t.BigInteger("available_at");
t.BigInteger("created_at");
});
Schema.Create("failed_jobs", t =>
{
t.Id();
t.String("uuid").Unique();
t.Text("connection");
t.Text("queue");
t.Text("payload");
t.Text("exception");
t.DateTime("failed_at");
});
}
public override void Down()
{
Schema.DropIfExists("failed_jobs");
Schema.DropIfExists("jobs");
}
}Workers claim a job with a conditional UPDATE rather than SELECT ... FOR UPDATE, preventing competing workers from claiming the same available reservation on every supported database including SQLite. Delivery is still at least once: a crash or expired reservation can cause a retry after side effects have already occurred. Make jobs idempotent.
Creating Jobs
Class Structure
A job extends DotBlaze.Job and implements Handle. Add the IShouldQueue marker to send it through the queue. Jobs usually live in app/Jobs:
namespace App.Jobs;
public class SendWelcomeEmail : Job, IShouldQueue
{
public required User User { get; init; }
public required string Subject { get; init; }
public override int Tries => 3;
public override async Task Handle()
{
Log.Info("Welcoming {Email}", User.Email);
// ...
}
}The job's data, its payload, is every public property with a setter or init. These are serialized to JSON when the job is dispatched and set again when it runs.
WARNING
Primary constructors are not supported: their parameters become private fields, which are not serialized. Use required properties instead. Handle takes no parameters either, because the job is recreated from JSON rather than by dependency injection.
Models in Job Payloads
A model in the payload is stored as its id only and is fetched again when the job runs, like Laravel's SerializesModels. The job therefore always sees the current data, not a stale copy:
var user = await User.Create(new { Name = "Ali", Email = "ali@example.com", Password = "secret" });
await new SendWelcomeEmail { User = user, Subject = "Welcome!" }.Dispatch();
user.Name = "Renamed before the job runs";
await user.Save();
// When the job runs, User.Name is "Renamed before the job runs".Soft deleted models are still found. If the model was deleted, the job throws a ModelNotFoundException and fails. Relationships loaded on the model are not kept; load them again in Handle.
Using Services
Facades work inside Handle, because each job runs in its own service scope. For other services, call Service<T>():
public override async Task Handle()
{
var http = Service<IHttpClientFactory>().CreateClient();
// ...
}Dispatching Jobs
Create the job and await Dispatch():
await new SendWelcomeEmail { User = user, Subject = "Welcome!" }.Dispatch();WARNING
The job is sent when the dispatch is awaited. new SendWelcomeEmail { ... }.Dispatch(); without await does nothing.
Queue.Push(job) queues a job too, and accepts the queue, delay, and connection as optional arguments.
Delayed Dispatching
await new SendReminder { User = user }.Dispatch().Delay(TimeSpan.FromMinutes(10));
await Queue.Later(TimeSpan.FromMinutes(10), new SendReminder { User = user });Customizing the Queue and Connection
await new SendWelcomeEmail { User = user, Subject = "Hi" }
.Dispatch()
.OnQueue("emails")
.OnConnection("database");Jobs That Run Immediately
A job without IShouldQueue is not queued at all: Dispatch() calls Handle right away, like Laravel's dispatch() of a non-queued job. Queue.Push always queues, with or without the marker.
Max Attempts and Backoff
By default a job is tried once. Override Tries to retry it, and Backoff for the delay in seconds before each retry; the last value is used for any further retries:
public override int Tries => 3;
public override int[] Backoff => [10, 60]; // 10s before the 2nd attempt, 60s before the 3rdA job that does not override Tries, Backoff, or Timeout uses the worker's --tries, --backoff, and --timeout (or those of its queue manager supervisor), and otherwise one try, no delay, and no time limit. Queued listeners work the same way.
Attempts tells the job which attempt is running (1 for the first):
public override Task Handle()
{
if (Attempts == 1) throw new InvalidOperationException("first attempt fails");
return Task.CompletedTask;
}Timeouts
Override Timeout to limit how long one attempt may run:
public class ImportFeed : Job, IShouldQueue
{
public required string Url { get; init; }
public override TimeSpan? Timeout => TimeSpan.FromSeconds(60);
public override async Task Handle()
{
var response = await Http.Get(Url); // stops automatically on timeout
await Storage.Put("feeds/latest.xml", response.Body);
await Task.Delay(1000, Cancellation); // pass the token to anything async
}
}.NET cannot kill running code, so DotBlaze combines .NET's cooperative cancellation with Laravel's approach:
- When
Timeoutpasses, the job'sCancellationtoken is cancelled. TheHttpclient uses it automatically; pass it to EF Core, file, and delay calls yourself. If the job stops by throwingOperationCanceledException, the attempt fails with aJobTimeoutExceptionand is retried or moved tofailed_jobsas usual, and the worker carries on. - A job that ignores the token gets a 10 second grace period. If it is still running after that,
queue:workrecords the failed attempt (it is retried later if it has tries left) and then exits with code 1, so a process supervisor can start a fresh worker. A worker inside the web app cannot exit; it moves the job straight tofailed_jobswithout retrying (it may still be running) and logs a critical message. - A worker refuses to start when any job's
Timeoutplus the grace period is not shorter than the connection'sretry_after, because the still-running job would be handed to another worker. Raiseretry_afteror lower the timeout.
Releasing a Job
Release(seconds) stops the current attempt and puts the job back on the queue, like Laravel's release(). It is not a failure, but it counts as an attempt; a job attempted more often than its Tries is moved to failed_jobs with a MaxAttemptsExceededException:
public override int Tries => 10;
public override async Task Handle()
{
if (!await Api.IsUp()) Release(30); // try again in 30 seconds
...
}Jobs and Database Transactions
A job dispatched inside a transaction may run before the transaction commits (on another worker, which cannot see the new rows yet), or after it rolled back. AfterCommit() pushes it only once the transaction commits, and drops it on rollback:
await DB.Transaction(async () =>
{
var order = await Order.Create(...);
await new SendOrderConfirmation { Order = order }.Dispatch().AfterCommit();
});Make it the default for a job with public override bool AfterCommit => true;, or for a whole connection with after_commit = true in config/Queue.cs; BeforeCommit() then opts one dispatch out. Without a transaction, the job is pushed right away.
Unique Jobs
IShouldBeUnique makes sure only one copy of a job is on the queue: while one is waiting or running, dispatching another does nothing. UniqueId says what makes two dispatches the same (default: the job type alone):
public class UpdateSearchIndex : Job, IShouldQueue, IShouldBeUnique
{
public required long ProductId { get; init; }
public override string UniqueId => ProductId.ToString();
public override int UniqueFor => 3600; // the lock lasts at most an hour (default: one day)
public override Task Handle() { ... }
}The lock is a cache lock, released when the job succeeds or fails for good; use the redis cache store so it holds across servers. With IShouldBeUniqueUntilProcessing, the lock is released as soon as the job starts, so a new one can be queued while it runs.
Job Middleware
Middleware wraps a job's Handle. Return it from Middleware():
public override IEnumerable<IJobMiddleware> Middleware() =>
[
new RateLimited($"backups:{UserId}", maxAttempts: 1, decaySeconds: 3600),
new WithoutOverlapping($"user:{UserId}").DontRelease(),
Skip.When(() => User.Unsubscribed),
];| Middleware | |
|---|---|
RateLimited(key, maxAttempts, decaySeconds) | Runs at most that many jobs with the key per window; others are released until it resets. |
WithoutOverlapping(key, releaseAfter, expireAfter) | Never two jobs with the key at once (a cache lock). An overlapping job is released after releaseAfter seconds, or dropped with .DontRelease(). |
Skip.When(condition) / Skip.Unless(condition) | Skip the job (it counts as done). |
Write your own by implementing IJobMiddleware:
public class LogDuration(ILogger log) : IJobMiddleware
{
public async Task Handle(Job job, Func<Task> next)
{
var started = Stopwatch.StartNew();
await next();
log.LogInformation("{Job} took {Ms}ms", job.GetType().Name, started.ElapsedMilliseconds);
}
}Throwing from middleware fails the attempt like an exception in Handle; throw new JobReleasedException(seconds) releases the job.
Job Chaining
A chain runs jobs one after another; each is queued when the previous one succeeds. When a job fails for good, the rest are not run and the Catch job, if any, is dispatched:
await Bus.Chain(
new ProcessPodcast { Podcast = podcast },
new OptimizePodcast { Podcast = podcast },
new ReleasePodcast { Podcast = podcast })
.OnQueue("podcasts")
.Catch(new NotifyPodcastFailed { Podcast = podcast })
.Dispatch();Job Batching
A batch runs jobs in parallel, tracks their progress, and dispatches callback jobs when they are done. Batches are stored in the job_batches table, which the application template's jobs migration creates. For an older app, add it in a migration:
Schema.Create("job_batches", t =>
{
t.String("id", 36);
t.String("name");
t.Integer("total_jobs");
t.Integer("pending_jobs");
t.Integer("failed_jobs");
t.Text("failed_job_ids");
t.Text("options");
t.BigInteger("cancelled_at").Nullable();
t.BigInteger("created_at");
t.BigInteger("finished_at").Nullable();
t.Primary("id");
});Defining and Dispatching Batches
var batch = await Bus.Batch(
new ImportCsv { Start = 1, End = 100 },
new ImportCsv { Start = 101, End = 200 })
.Named("Import CSV")
.Then(new NotifyImportDone { UserId = user.Id }) // every job succeeded
.Catch(new NotifyImportFailed { UserId = user.Id }) // the first job failure
.Finally(new CleanUpImport()) // every job has run
.OnQueue("imports")
.Dispatch();
return Redirect($"/imports/{batch.Id}");The callbacks are jobs too, queued on the batch's queue. Inside any job of the batch (or a callback), await Batch() returns the batch.
Inspecting and Cancelling Batches
var batch = await Bus.FindBatch(id);
batch.TotalJobs; batch.PendingJobs; batch.FailedJobs; batch.ProcessedJobs;
batch.Progress; // 0-100
batch.Finished; batch.Cancelled; batch.HasFailures;
await batch.Add(new ImportCsv { Start = 201, End = 300 }); // more jobs, while it has not finished
await batch.Cancel();Cancelling does not stop jobs that are already queued. Like in Laravel, jobs check it themselves:
public override async Task Handle()
{
if (await BatchCancelled()) return;
...
}Batch Failures
By default the first job that fails for good cancels the batch: Catch is dispatched, Then is not, and Finally still runs once every job has run. AllowFailures() keeps the batch going; Catch is still dispatched for the first failure. FailedJobIds contains job UUIDs, not numeric failed_jobs.id values. Use queue:failed to find the numeric ID required by queue:retry.
Running the Queue Worker
The queue:work Command
The worker processes jobs from a worker-capable driver such as database or the optional redis driver until stopped. A sync connection runs inline and cannot be consumed by queue:work:
dotblaze queue:work| Option | Description |
|---|---|
--queue=emails,default | Queues to process, in priority order. Defaults to default. |
--connection=name | Queue connection from config/Queue.cs. Defaults to the configured default. |
--sleep=3 | Seconds to wait when every queue is empty. |
--stop-when-empty | Exit once the queues are empty, instead of waiting. |
--memory=0 | Exit after a job once the process uses this many megabytes (0 = no limit). The exit code is 12. |
--max-jobs=0 | Exit after this many jobs (0 = no limit). |
--max-time=0 | Exit after this many seconds, once the current job is done (0 = no limit). |
--tries= | Tries for jobs that do not override Tries. |
--backoff= | Retry delays in seconds (10,60) for jobs that do not override Backoff. |
--timeout= | Time limit in seconds for jobs that do not override Timeout. Like a job's own timeout, it must be shorter than retry_after. |
--supervised | Used by the queue manager: stop when "stop" or the end of input arrives, and report each job's run time. |
Press Ctrl+C (or send SIGTERM) to stop: the worker finishes the current job first.
The worker is a long-running process that loads your code once. Restart it after deploying new code.
Queue Priorities
After each job, the worker starts again from the first queue in --queue, so a job from the second queue only runs when the first is empty:
dotblaze queue:work --queue=high,defaultRunning the Worker Inside the Web App
For small apps, set worker = true in config/Queue.cs to run a worker as a background service of the web app. It processes the queues in worker_queues on the default connection, checking every 3 seconds when they are empty:
public override object Values() => new
{
@default = "database",
worker = true,
worker_queues = "high,default",
connections = new { database = new { driver = "database", retry_after = 90 } },
};It stops with the app, and cannot recover from a job that ignores its timeout (see Timeouts). For anything heavier, run queue:work as a separate process.
Job Expiration
retry_after (seconds, default 90) is how long a claimed job may stay reserved. After that, DotBlaze assumes the worker died and hands the job to another worker. Keep it longer than your slowest job.
Supervisor Configuration
In production, keep queue:work running with a process supervisor (systemd, Docker's restart policy, Kubernetes, Supervisor) so it is restarted after a crash, a deploy, or the exit described in Timeouts. Run several worker processes to process jobs in parallel. For example, with systemd:
[Service]
WorkingDirectory=/var/www/app
ExecStart=/usr/bin/dotnet App.dll queue:work --queue=high,default
Restart=alwaysTo run several workers and balance them between queues automatically, use the queue manager instead.
The Queue Manager
queue:manager runs and watches many queue:work processes for you, like Laravel Horizon. For Horizon's dashboard, add the DotBlaze.Horizon package. You describe groups of workers, called supervisors, in config/Queue.cs; the manager starts them as child processes, moves workers between queues by workload, restarts workers that stop, and passes on Ctrl+C or SIGTERM so every worker finishes its current job.
Each worker is a separate process, so a job that ignores its timeout or leaks memory only takes its own worker down; the manager starts a fresh one.
Configuring Supervisors
public override object Values() => new
{
@default = "redis",
connections = new { redis = new { driver = "redis", connection = "default", retry_after = 90 } },
manager = new
{
supervisors = new Dictionary<string, object>
{
["supervisor-1"] = new
{
connection = "redis",
queue = new[] { "default" },
balance = "auto",
auto_scaling_strategy = "time",
min_processes = 1,
max_processes = 10,
balance_max_shift = 1,
balance_cooldown = 3,
memory = 512,
tries = 3,
timeout = 60,
backoff = new[] { 10, 60 },
nice = 0,
},
["supervisor-2"] = new
{
queue = new[] { "agent", "terminal" },
max_processes = 4,
},
},
},
};Supervisor names such as supervisor-1 are not valid C# names, so supervisors is a dictionary.
| Key | Default | Description |
|---|---|---|
connection | queue.default | The queue connection. It needs a worker driver (database or redis). |
queue | ["default"] | The queues, highest priority first. A comma-separated string works too. |
balance | auto | auto, simple, or off; see Balancing Strategies. |
auto_scaling_strategy | time | For auto: time or size. |
min_processes | 1 | For auto: workers each queue keeps, even when it is empty. 0 is allowed. |
max_processes | 1 | Workers of this supervisor in total. |
balance_max_shift | 1 | For auto: workers a queue gains or loses per balancing step. |
balance_cooldown | 3 | For auto: seconds between balancing steps. |
memory | 512 | A worker that uses this many megabytes is replaced after its current job (0 = no limit). An idle .NET worker uses about 130 MB. |
max_jobs | 0 | A worker is replaced after this many jobs (0 = no limit). |
max_time | 0 | A worker is replaced after this many seconds (0 = no limit). |
tries | Tries for jobs that do not override Tries. | |
timeout | Seconds a job that does not override Timeout may run. It must be shorter than the connection's retry_after. | |
backoff | Retry delays in seconds for jobs that do not override Backoff: a number or a list. | |
nice | 0 | Process priority of the workers, from -20 (highest) to 19 (lowest). A negative value needs root. On Windows, it maps to a priority class. |
sleep | 3 | Seconds a worker waits when its queues are empty. |
The keys match Horizon's options in snake_case: maxProcesses is max_processes, autoScalingStrategy is auto_scaling_strategy, and so on. balance = false is the same as "off".
The manager checks every supervisor when it starts and refuses to run with a message naming the problem, for example an unknown balance or a max_processes smaller than min_processes × queues.
Balancing Strategies
auto: each queue has its own workers. Everybalance_cooldownseconds the manager reads how many jobs wait in each queue and moves workers toward the queues with the most work, at mostbalance_max_shiftper queue per step. Each queue keepsmin_processes, the total stays withinmax_processes, and a queue never gets more workers than it has jobs. Withauto_scaling_strategytime, a queue's workload is its waiting jobs times their average run time (measured by the workers), so a queue of slow jobs gets more workers than a queue of quick ones with the same length. Withsize, only the number of jobs counts.simple:max_processesworkers split evenly between the queues, and they stay there.off:max_processesworkers that all process every queue in priority order, likequeue:work --queue=a,b.
Scaling down asks the newest workers to stop: each one finishes its current job first.
Environments
environments overrides supervisor keys per environment (the ASPNETCORE_ENVIRONMENT / DOTNET_ENVIRONMENT name; local also matches Development). When the current environment has a section, only the supervisors named in it run; otherwise every supervisor runs with its defaults:
manager = new
{
supervisors = new Dictionary<string, object>
{
["supervisor-1"] = new { queue = new[] { "default" }, max_processes = 3 },
},
environments = new
{
production = new Dictionary<string, object>
{
["supervisor-1"] = new { max_processes = 10, balance_max_shift = 2 },
},
local = new Dictionary<string, object>
{
["supervisor-1"] = new { max_processes = 2 },
},
},
},Running the Queue Manager
dotblaze queue:managerThe manager prints each worker's output prefixed with its supervisor, queues, and process id, and logs every scaling step and restart. In another terminal, queue:manager:status shows the running managers, with the workers, waiting jobs, and average run time of every queue:
dotblaze queue:manager:statusQueue manager 11732 (Production): running since 2026-11-27 08:47:30
supervisor-1 redis balance auto, max 5
default workers 4/4 pending 36 avg 1023 ms
emails workers 1/1 pending 0 avg 250 msworkers 4/3 means 4 workers are running while the target is 3: one is finishing its last job.
A worker that stops by itself, because of memory, max_jobs, max_time, or a job that ignored its timeout, is replaced at once. A worker that fails within 10 seconds of starting, for example because the database is down, is restarted after 1, 2, 4, and up to 60 seconds. If the manager itself is killed, its workers see their input close and stop after the current job, so none are left behind.
Deploying
Run queue:manager under a process supervisor, like queue:work:
[Service]
WorkingDirectory=/var/www/app
ExecStart=/usr/bin/dotnet App.dll queue:manager
Restart=always
# Give the longest job time to finish when stopping.
TimeoutStopSec=300After deploying new code, run queue:manager:terminate. Every manager of the application on that machine stops its workers after their current job and exits, and the process supervisor starts it again with the new code:
dotnet App.dll queue:manager:terminateThe manager keeps its status in storage/framework/queue-manager, so status and terminate see managers on the same machine; run them on each server.
Dealing With Failed Jobs
When a job has used up its tries, it is removed from jobs and stored in failed_jobs together with the exception and the name of the queue connection it failed on. Failed jobs are always stored in the default database connection's failed_jobs table, whichever connection the job ran on.
Cleaning Up After Failed Jobs
Override Failed to react when a job fails for good, for example to notify someone:
public override Task Failed(Exception exception)
{
Log.Error(exception, "Import of {Url} failed", Url);
return Task.CompletedTask;
}With the database driver, Failed runs once, after the last attempt; an exception thrown by Failed is logged and ignored. With sync, it runs whenever the job throws.
Retrying Failed Jobs
dotblaze queue:failed # list failed jobs
dotblaze queue:retry 5 # push failed job #5 back onto its queue connection
dotblaze queue:retry all # push all failed jobs back
dotblaze queue:flush # delete all failed jobsA retried job starts again with a fresh attempt count.
NOTE
These commands read the failed_jobs table on the default database connection. queue:retry pushes each job back onto the queue connection it failed on (the connection column of failed_jobs). queue:retry with a missing or invalid id prints the usage line and exits with 1.
Testing
Queue.Fake() records dispatched jobs instead of queueing them:
var queue = Queue.Fake();
await new SendWelcomeEmail { User = user, Subject = "Hi" }.Dispatch().OnQueue("emails");
queue.AssertPushed<SendWelcomeEmail>(j => j.User.Id == user.Id);
queue.AssertPushedOn<SendWelcomeEmail>("emails");
queue.AssertNotPushed<ImportFeed>();Bus.Fake() records chains and batches, and fakes the queue too:
var bus = Bus.Fake();
await importer.Start();
bus.AssertChained(typeof(ProcessPodcast), typeof(OptimizePodcast), typeof(ReleasePodcast));
bus.AssertBatched(b => b.Name == "Import CSV" && b.Jobs.Count == 10);
bus.AssertDispatched<SendReport>();To run queued jobs for real in a test, resolve the Worker service and call RunNext("default"), which processes one job and returns false when the queue is empty. See Fakes and Database Testing.