Skip to content

Request context ​

The request context is a small map of ambient facts that travels with a job: tenant_id, request_id, traceparent, locale. A handler in another process, or another language, reads it to look up what differs per tenant (a database, a mail sender, a feature flag) without the producer passing those things in the payload. It is the counterpart of Rails' CurrentAttributes.

It is not the job's input (that is the payload), not a secret store and not configuration. Neither the server nor an SDK gives a key a meaning: tenant_id and traceparent are conventions of your application.

Attach it when you enqueue ​

Every call that creates work takes a context: enqueue, enqueue_job, start, start_workflow and create_batch (spelled per language). Most SDKs also take a context provider on the client, a function called on every call whose result is the base the call's own context is laid over, key by key, the call's keys winning. Rust and Elixir have no provider: pass the context on each call.

LanguageOn the callProvider on the clientIn a handler
Pythoncontext={...}JoobQClient(url, token, context_provider=fn)ctx.context
TypeScript{ context: {...} }new JoobQClient(url, token, { contextProvider })ctx.context
Rubycontext: {...}JoobQ::Client.new(gateway_url:, token:, context_provider:)ctx.context
GoEnqueueOptions.Context (EnqueueJobInput.Context)client.ContextProvider = func(context.Context) map[string]anyec.Meta
RustEnqueueOptions.context (a Map)nonectx.context
Javanew EnqueueOptions().context(map)new JoobQClient(url, token, supplier)ctx.context()
PHP['context' => [...]]third constructor argument, a callable$ctx->context
.NETnew EnqueueOptions(Context: ...)contextProvider: of the constructorctx.Context
Elixircontext: %{...}nonejob.context

The same job, with tenant_id and request_id from the provider and locale on the call (send_invoice is a job defined as in Jobs):

python
client = JoobQClient(
    gateway_url, token,
    context_provider=lambda: {"tenant_id": current_tenant(), "request_id": current_request_id()},
)
client.enqueue(send_invoice, {"order": 42}, context={"locale": "de"})
ts
const client = new JoobQClient(gatewayUrl, token, {
  contextProvider: () => ({ tenant_id: currentTenant(), request_id: currentRequestId() }),
})
await client.enqueue(sendInvoice, { order: 42 }, { context: { locale: 'de' } })
ruby
client = JoobQ::Client.new(
  gateway_url: gateway_url, token: token,
  context_provider: -> { { "tenant_id" => current_tenant, "request_id" => current_request_id } }
)
client.enqueue(SendInvoice, { order: 42 }, context: { "locale" => "de" })
go
client := joobq.NewClient(gatewayURL, token)
client.ContextProvider = func(ctx context.Context) map[string]any {
	return map[string]any{"tenant_id": tenantFrom(ctx), "request_id": requestIDFrom(ctx)}
}
_, err := sendInvoice.Enqueue(ctx, client, map[string]any{"order": 42},
	joobq.EnqueueOptions{Context: map[string]any{"locale": "de"}})
rust
let client = JoobQClient::new(gateway_url, token);
let mut options = EnqueueOptions::default();
options.context.insert("tenant_id".into(), json!("acme"));
options.context.insert("request_id".into(), json!("req-1"));
options.context.insert("locale".into(), json!("de"));
client.enqueue(&send_invoice, json!({"order": 42}), options)?;
java
var client = new JoobQClient(gatewayUrl, token,
    () -> Map.of("tenant_id", currentTenant(), "request_id", currentRequestId()));
client.enqueue(sendInvoice, Map.of("order", 42), new EnqueueOptions().context(Map.of("locale", "de")));
php
$client = new JoobQClient(
    $gatewayUrl, $token,
    fn () => ['tenant_id' => currentTenant(), 'request_id' => currentRequestId()],
);
$client->enqueue(SendInvoice::class, ['order' => 42], ['context' => ['locale' => 'de']]);
csharp
var client = new JoobQClient(gatewayUrl, token,
    contextProvider: () => new() { ["tenant_id"] = CurrentTenant(), ["request_id"] = CurrentRequestId() });
await client.EnqueueAsync(sendInvoice, new { order = 42 }, new EnqueueOptions(Context: new() { ["locale"] = "de" }));
elixir
JoobQ.enqueue("billing", "send_invoice", %{order: 42},
  context: %{tenant_id: "acme", request_id: "req-1", locale: "de"})

The samples were run against a stand-in gateway that records the request, except .NET, which was checked against the SDK source only.

Read it in a handler ​

The last column of the table is the accessor: a map of the keys the producer attached, {} when it attached none. A middleware reads it the same way, before the handler runs.

Elixir has no handler context object: perform/1 gets the JoobQ.Job, and JoobQ.Context.current() answers its context from anywhere in the handler's own process. The context lives in that process's dictionary, so a process the handler spawns (Task.async) has none: pass context: job.context to what it enqueues.

How it travels ​

  • Work started from a handler carries it on. ctx.enqueue*, ctx.start* and ctx.create_batch (in Elixir, JoobQ.enqueue, start_workflow and create_batch called in the handler's process) lay the handler's context under the one you pass: the handler's context is the base, your keys win. A provider on the worker's own client lies under both. Go has no ec.Start*: start a workflow from ec.Client and pass ec.Meta as its context.
  • A batch takes a batch-level context, merged into each member and each callback; the member's or callback's own keys win (Batch enqueue and batches).
  • A workflow run keeps the context it was started with, and every step, compensation and update of the run sees it as ctx.context. A start with an id that exists never changes a live run's context. A child workflow and the next run of a continue_as_new read their parent's or first run's, looked up through at most 8 levels (MAX_CONTEXT_HOPS); beyond that the steps see an empty context. The gateway keeps a run's context for 90 days after a step last read it.
  • Retries and delayed jobs keep it: the gateway stores the context in the job and writes the same job back for a retry or a delay.
  • A schedule has none. A job a schedule enqueues has an empty context, so a handler or middleware that needs a tenant must cope with a missing tenant_id.

For a handler whose context is {tenant_id: "acme", request_id: "r1"}, ctx.enqueue(job, payload, context={"request_id": "r2", "attempt": 2}) sends {tenant_id: "acme", request_id: "r2", attempt: 2}.

Limits and privacy ​

A context is a JSON object: string keys, any JSON values. Anything else is refused with 422. It has no size limit of its own: it counts toward the request body, which the gateway caps at 262,144 bytes (payload_too_large).

Do not put secrets in the context

The context is stored unsealed. encrypt_fields seals payload fields only, never the context, so a value in it is readable in Redis and in a backup. For a job, it is also shown in the console, on the Jobs and dead-letter pages, as part of the job. Keep passwords, tokens and keys out of it, and put an identifier in it (a tenant id) rather than the data it stands for.

The console shows a job's context with the same masking as its payload: a value is replaced by [redacted], at any depth, when its key contains password, passwd, pwd, secret, token, api_key, apikey, authorization, auth, bearer, cookie, credential, private_key or dsn (any case; - and a space count as _), and key=value secrets and DSN passwords inside a string value are masked too. That is a guard against slips, not a promise: a secret under the key session or license is shown. The SDK handler always gets the values in full. A workflow run's context is kept in Redis and handed to its steps, and no console or API view returns it. The dead-letter CSV export has no context column; its JSON export has the job, masked as above.

Look up the tenant in a middleware ​

A worker middleware wraps every task, so it is the place to turn tenant_id into the tenant's scope for the handler. Each sample uses its language's own per-task state and puts it back when the task ends:

python
from contextvars import ContextVar

current_tenant = ContextVar("current_tenant", default=None)

def tenant_scope(ctx, nxt):
    token = current_tenant.set(ctx.context.get("tenant_id"))
    try:
        return nxt()
    finally:
        current_tenant.reset(token)

worker = JoobQWorker(client, "w1", ["billing"]).use(tenant_scope)
ts
import { AsyncLocalStorage } from 'node:async_hooks'

export const currentTenant = new AsyncLocalStorage<string | undefined>()

const tenantScope: TaskMiddleware = (ctx, next) =>
  currentTenant.run(ctx.context.tenant_id as string | undefined, next)

const worker = new JoobQWorker(client, { workerId: 'w1', taskQueues: ['billing'] }).use(tenantScope)
ruby
TENANT_SCOPE = lambda do |ctx, nxt|
  previous = Thread.current[:tenant_id]
  Thread.current[:tenant_id] = ctx.context["tenant_id"]
  begin
    nxt.call
  ensure
    Thread.current[:tenant_id] = previous
  end
end

worker = JoobQ::Worker.new(client: client, worker_id: "w1", task_queues: ["billing"]).use(&TENANT_SCOPE)
go
type tenantKey struct{}

func tenantScope(ec *joobq.ExecutionContext, next func() (any, error)) (any, error) {
	tenant, _ := ec.Meta["tenant_id"].(string)
	ec.Ctx = context.WithValue(ec.Ctx, tenantKey{}, tenant)
	return next()
}

worker := joobq.NewWorker(client, "w1", []string{"billing"}).Use(tenantScope)
rust
thread_local! {
    static TENANT: RefCell<Option<String>> = RefCell::new(None);
}

fn tenant_scope(ctx: &ExecutionContext, next: &dyn Fn() -> joobq::Result<Value>) -> joobq::Result<Value> {
    let tenant = ctx.context.get("tenant_id").and_then(Value::as_str).map(str::to_owned);
    let previous = TENANT.with(|t| t.replace(tenant));
    let out = next();
    TENANT.with(|t| *t.borrow_mut() = previous);
    out
}

let worker = Worker::new(client, "w1", vec!["billing".into()]).use_middleware(tenant_scope);
java
static final ThreadLocal<Object> CURRENT_TENANT = new ThreadLocal<>();

static final Middleware TENANT_SCOPE = (ctx, next) -> {
    Object previous = CURRENT_TENANT.get();
    CURRENT_TENANT.set(ctx.context().get("tenant_id"));
    try {
        return next.call();
    } finally {
        CURRENT_TENANT.set(previous);
    }
};

var worker = new JoobQWorker(client, "w1", List.of("billing")).use(TENANT_SCOPE);
php
final class Tenant
{
    public static ?string $current = null;
}

function tenantScope(ExecutionContext $ctx, callable $next): mixed
{
    $previous = Tenant::$current;
    Tenant::$current = $ctx->context['tenant_id'] ?? null;
    try {
        return $next();
    } finally {
        Tenant::$current = $previous;
    }
}

$worker = (new JoobQWorker($client, 'w1', ['billing']))->use('tenantScope');
csharp
static readonly AsyncLocal<string?> CurrentTenant = new();

static async Task<object?> TenantScope(ExecutionContext ctx, Func<Task<object?>> next)
{
    CurrentTenant.Value = ctx.Context.GetValueOrDefault("tenant_id")?.GetValue<string>();
    return await next();
}

var worker = new JoobQWorker(client, "w1", new[] { "billing" }).Use(TenantScope);
elixir
defmodule MyApp.TenantScope do
  @behaviour JoobQ.Middleware

  @impl JoobQ.Middleware
  def call(%JoobQ.Job{context: context}, next, _opts) do
    previous = Process.put(:tenant_id, context["tenant_id"])

    try do
      next.()
    after
      if previous, do: Process.put(:tenant_id, previous), else: Process.delete(:tenant_id)
    end
  end
end

# {JoobQ, url: url, token: token, queues: ["billing"], workers: [MyApp.SendInvoice], middleware: [MyApp.TenantScope]}

Run in every language but .NET, with a stand-in task, to check the state is set for the handler and restored after.

See also ​