---
url: https://rustrak.dev/plugins/jobs/
---

# Background jobs

A route has 2 seconds to answer. Work that takes longer, or that the caller should not wait for, goes to a job: the route queues it with `ctx.enqueue` and answers, and Rustrak runs the job right after, outside the request.

The plugin `new` creates does this to clear a project's visits. `DELETE /visits` answers `204` at once, and a job does the delete:

```rust
// src/server/jobs/clear.rs
use rustrak_plugin::prelude::*;
use serde::{Deserialize, Serialize};

use crate::models::visit;

#[derive(Serialize, Deserialize)]
pub struct Clear {
    pub until: i64,
}

#[job]
fn clear_visits(ctx: &Ctx, clear: Json<Clear>) -> Result<()> {
    visit::clear(ctx, clear.0.until)
}
```

```rust
// src/server/routes/visits.rs
use crate::jobs::clear::Clear;

#[delete("/visits", requires = Perm::Visits.delete())]
fn clear(ctx: &Ctx) -> Result<NoContent> {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_err(|e| Error::Internal(e.to_string()))?;
    ctx.enqueue("clear_visits", &Clear { until: now.as_secs() as i64 })?;
    Ok(NoContent)
}
```

Jobs go in `src/server/jobs/`, and a job's name is its function's name. Put `#[job]` anywhere else and the build stops with `a job goes in src/server/jobs/`.

## Queueing a job

| `Ctx` | Queues |
|---|---|
| `ctx.enqueue(name, &payload)` | The job `name`, to run as soon as possible |
| `ctx.enqueue_after(delay, name, &payload)` | The job `name`, to run once `delay` has passed. Whole seconds, 30 days at most |

The payload is any value that implements `serde::Serialize`. Rustrak stores it as JSON, in its own database, before `enqueue` returns, so a queued job survives a restart. A route, a [task](https://rustrak.dev/plugins/tasks/) and another job can all queue one.

`enqueue` returns an error, and queues nothing, when:

- the plugin has no job with that name (`no job <name>`),
- the payload is over 64 KB,
- the delay is over 30 days,
- the plugin already has 10,000 jobs waiting.

With `?`, that error makes the route answer `500`.

A queued job does not depend on the rest of the call. If the route fails after `enqueue`, the job runs anyway.

## Running a job

A job takes `&Ctx` and `Json<T>`, the payload, in any order, and returns `Result<()>`.

It runs in the project of the call that queued it: `ctx.project_id()` is that project, and `Settings::get(ctx)` reads its values. A job queued from a task or an instance route has no project.

Rustrak runs a job within a few seconds of its time. A job can call other services with [`ctx.fetch`](https://rustrak.dev/plugins/network/), with the same hosts as the rest of the plugin.

## Failures and retries

A job that returns an `Error`, panics or runs out of time is tried again 1 minute later, then 4 minutes after that. After the third failure Rustrak drops it. Both go to Rustrak's log under the `rustrak::plugin` target:

```text
[my-plugin] job clear_visits failed, attempt 1 of 3: the plugin ran past its time budget
[my-plugin] job clear_visits dropped after 3 attempts: the plugin ran past its time budget
```

A restart in the middle of a run means the job runs again from the start. Every job runs at least once, and sometimes twice, so write it to be safe to repeat: the delete above, run twice, deletes nothing the second time.

Uninstalling a plugin drops the jobs it has waiting.

## Limits

| What | Limit |
|---|---|
| Time per run, queries and requests included | 30 seconds |
| Memory | 32 MB |
| Tasks and jobs running at once | One, across every plugin. The others wait their turn |
| Payload | 64 KB |
| Delay | 30 days |
| Jobs waiting, per plugin | 10,000 |
| Attempts | 3 |

Jobs need Rustrak 0.37.0 or later, like [scheduled tasks](https://rustrak.dev/plugins/tasks/).
