Skip to content

Scheduler

The Scheduler Module provides background job execution, recurring cron scheduling, multi-queue prioritization, automated crash recovery, and a pluggable queue architecture.

Kirak currently launches with an initial set of 3 foundational backends (Database, Redis, and RabbitMQ), with additional queue brokers and cloud queue adapters continuously being developed by the core team and community contributors. Custom backends can be registered seamlessly via Kirak’s modular provider architecture.


Install backend extras as needed:

Terminal window
# Database backend uses existing DB connection (no extra packages needed)
pip install "kirak[scheduler-redis]" # Redis backend (redis-py)
pip install "kirak[scheduler-rabbitmq]" # RabbitMQ backend (aio-pika)
pip install "kirak[all-scheduler]" # All queue backends

Enable the module in kirak.json:

{
"modules": ["scheduler"]
}

Architectural State Machine & Job Lifecycle

Section titled “Architectural State Machine & Job Lifecycle”

Every enqueued job is cryptographically signed with an HMAC anti-tamper signature before being handed to the backend. The worker manages executions, leases, and retry backoffs through a robust state machine:

flowchart TD
Enqueue["kirak.scheduler.enqueue(task, payload)"] --> SignJob["Cryptographic Signing<br/>Generate HMAC-SHA256 signature (_kirak_signature)"]
SignJob --> HookBeforeEnq["Execute before_enqueue Hook"]
HookBeforeEnq --> BackendStore["Store into Queue Backend<br/>(DB / Redis / RabbitMQ)"]
BackendStore --> Pending["State: PENDING<br/>(Waiting for run_at or worker availability)"]
Pending --> WorkerPickup["Worker Claims Job<br/>(Acquires Semaphore Slot)"]
WorkerPickup --> VerifySig{"Verify HMAC<br/>Signature"}
VerifySig -- "Invalid / Forged" --> RejectForged["Raise ForgedJobError<br/>Mark FAILED permanently (No retries)"]
VerifySig -- "Valid" --> ResolveIdent["Resolve Task Identity<br/>(system, caller, or guest)"]
ResolveIdent --> HookBeforeJob["Execute before_job Hook"]
HookBeforeJob --> RunTask["Execute async Task Function<br/>(Enforce job_timeout)"]
RunTask -- "Completed Successfully" --> AckJob["Acknowledge Job (backend.ack)<br/>Execute after_job Hook"]
AckJob --> StateDone["State: DONE"]
RunTask -- "Timeout or Exception" --> HookFail["Execute on_job_failure Hook"]
HookFail --> AttemptsCheck{"attempts < max_retries?"}
AttemptsCheck -- "Yes" --> CalcBackoff["Calculate Exponential Backoff<br/>wait = retry_backoff * attempts"]
CalcBackoff --> NackRetry["backend.nack(retry_at)<br/>Requeue into .delay / future slot"]
NackRetry --> Pending
AttemptsCheck -- "No (Max reached)" --> DeadLetter["Permanent Failure<br/>Mark FAILED / Move to q.failed"]

Kirak supports two operational modes: Loops Mode (continuous internal worker loops) and Tick Mode (stateless external HTTP triggers for serverless environments).

flowchart LR
subgraph LoopsMode["Loops Mode (Default)"]
direction TB
DB_Queue["Database Backend<br/>- Polling (poll_interval)<br/>- Strict SQL Priority<br/>- Lease Recovery (timeout + 30s)"]
Redis_Queue["Redis Backend<br/>- Polled Sorted Sets<br/>- Second-level Priority<br/>- Stale Requeue (timeout + 60s)"]
RMQ_Queue["RabbitMQ Backend<br/>- Push-based Consumer<br/>- FIFO Ordering<br/>- q.delay & q.failed queues"]
end
subgraph TickMode["Tick Mode (Serverless / Cloud Run)"]
direction TB
ExternalTrigger["External Cron / Host Trigger<br/>POST /_kirak/scheduler/tick"] --> TokenGate["HMAC Token Verification<br/>X-Kirak-Tick-Token"]
TokenGate --> BudgetLoop["Run Due Work Within Budget<br/>(Max 20s job_timeout)"]
BudgetLoop --> NextDueHeader["Return X-Kirak-Next-Due<br/>& Post Webhook Notification"]
end

kirak.json lists the active queue backends as provider instances and designates the default provider. Multiple backends can run concurrently (e.g. database for audit tasks and Redis for high-throughput jobs).

{
"scheduler": {
"default_provider": "db",
"mode": "loops",
"poll_interval": 5,
"concurrency": 4,
"job_timeout": 3600,
"max_retries": 3,
"retry_backoff": 60,
"job_retention_days": 7,
"default_queue": "default",
"queues": ["emails", "reports", "high-priority"],
"providers": {
"db": { "type": "database" },
"redis": { "type": "redis" },
"rmq": { "type": "rabbitmq", "consumer_timeout": 1800 }
}
}
}
View Backend Comparison & Settings
Built-in type Extra Install Mechanics & Settings
database None Uses the application’s existing database. Zero additional infrastructure. Uses polling (poll_interval). Requires the scheduler_jobs table. At most one database provider instance is permitted.
redis kirak[scheduler-redis] Polling against Redis sorted sets. Setting: redis_ssl (default false). Connection URL read from KIRAK_SCHEDULER_<INSTANCE>_URL (default redis://localhost:6379).
rabbitmq kirak[scheduler-rabbitmq] Push-based delivery (no polling). Declares <queue>, <queue>.delay, and <queue>.failed. Setting: consumer_timeout (default 1800 seconds). Connection URL read from KIRAK_SCHEDULER_<INSTANCE>_URL (default amqp://guest:guest@localhost/). Loops mode only: it needs a long-lived consumer connection, so tick mode refuses it at startup. It has no job records, so /scheduler/jobs routes, job cancel, database schedules and job_retention_days do not apply (those routes answer 400). reset_stale does nothing: the broker redelivers unacknowledged messages. A delayed job can run late, never early, because the broker holds it in <queue>.delay. Nothing consumes or replays <queue>.failed: a job that failed for good stays there until an operator moves it.

All scheduler settings and each backend’s settings:

scheduler key Type Description
mode string loops: the process runs its own cron and queue loops. tick: no background loops; an external caller drives the scheduler through POST /_kirak/scheduler/tick. Default loops.
min_interval_seconds integer Tick mode only: the shortest gap in seconds between two firings of any cron, registered in code or created at runtime; a cron that fires closer together is refused (at startup, or with 422 on a schedule write). Default 900.
next_due_webhook_url string Tick mode only: a URL the scheduler POSTs {“next_due”: T} to after each schedule or enqueue write, with the tick token in X-Kirak-Tick-Token. Tried twice within 2 s in total; a failure is logged, not returned. Empty (default): no notify.
default_provider string Instance name used when a call names no provider. Must be one of the instances under providers.
providers object Queue provider instances (types database, redis, rabbitmq, or a custom type), by instance name. At most one database entry.
poll_interval integer Seconds between queue polls (database and redis providers). Default 5.
concurrency integer Maximum jobs run in parallel per provider. Default 4.
default_queue string Queue used when enqueue() is given none. Always consumed. Default “default”.
queues array Extra queues to consume besides default_queue. Default [].
job_timeout number Seconds a job may run before the worker stops and retries it; fractions allowed (e.g. 0.25). In tick mode a job starts only if its timeout fits the remaining tick budget, and the timeout must be at most 20 s. Default 3600 in loops mode and 20 in tick mode.
max_retries integer Default maximum retry attempts per job. Default 3.
retry_backoff integer Base delay between retries in seconds, multiplied by the attempt number. Default 60.
job_retention_days integer Days a finished (done or failed) job is kept before it is removed: database rows by a daily cleanup, Redis job records by an expiry. 0 keeps them forever. Pending, running and retrying jobs are never removed. Default 7.
max_jobs_per_tick integer Tick mode only: the most jobs one tick starts, whatever budget is left. Jobs not started stay due for the next tick. Unset: no cap.

<INSTANCE> is the provider instance’s name in kirak.json, upper-cased: an instance named main reads ..._MAIN_....

database (no extra install) – Queue in the app’s own database. No extra install. At most one per project.

No settings or secrets.

redis (pip install "kirak[scheduler-redis]") – Queue in Redis (sorted sets).

Credential check (check()): Connect and PING.

Name Where Required / default Description
redis_ssl kirak.json default False Connect over TLS.
KIRAK_SCHEDULER_<INSTANCE>_URL environment Redis URL. Default redis://localhost:6379.

rabbitmq (pip install "kirak[scheduler-rabbitmq]") – Queue in RabbitMQ. Loops mode only: no job records, job listing or cancel, or database schedules.

Credential check (check()): Connect and open a channel.

Name Where Required / default Description
consumer_timeout kirak.json default 1800 The broker’s consumer_timeout in seconds. Jobs on this provider are stopped 60 s before it, if that is below job_timeout.
KIRAK_SCHEDULER_<INSTANCE>_URL environment AMQP URL. Default amqp://guest:guest@localhost/.

[!NOTE] Provider Support Across HTTP Endpoints:

  • All Providers (Database, Redis, RabbitMQ): POST /scheduler/enqueue (job submission) and GET /scheduler/registered (introspection of registered tasks, crons, and active providers) work with any configured backend.
  • Database Only: Querying past jobs (GET /scheduler/jobs, GET /scheduler/jobs/{id}), cancelling pending jobs (DELETE /scheduler/jobs/{id}), and managing dynamic schedules (/scheduler/schedules/*) strictly require a configured database provider because they read and write records in the scheduler_jobs SQL table.

Changing default_provider (for example from database to redis) affects where new jobs and cron locks go. It does not move anything already stored. Do it as a cutover:

  1. Keep the old provider configured until its queue is empty. Every connected provider is drained, so its queued jobs still run while it is listed under providers. Removing it while it has pending jobs strands them: nothing reads that store.
  2. Stop the old instances before starting the new config. A cron without an explicit provider claims its slot on the default provider. During a rolling deploy with different defaults, an old and a new instance can claim the same minute and both fire the cron.
  3. Pin provider on a cron that must fire exactly once across a switch. A cron with an explicit provider keeps its lock on that provider, whatever the default is.

Kirak protects workers from unauthorized job injection. Whenever a job is submitted via kirak.scheduler.enqueue() or through /scheduler/enqueue, Kirak computes an HMAC-SHA256 signature over the task name, payload, and enqueuing identity using KIRAK_AUTH_JWT_SECRET_KEY, storing it in _kirak_signature.

If an attacker gains access to your database or Redis server and directly inserts a raw job record without the HMAC signature, the worker traps it immediately:

  • It raises ForgedJobError.
  • It marks the job failed permanently without attempting retries.
  • It logs a security warning.

All tasks and cron routines must be registered in your application’s on_kirak_ready callback before the scheduler worker boots.

def on_kirak_ready(kirak):
@kirak.scheduler.task("send_welcome_email", run_as="system")
async def send_welcome_email(payload: dict) -> None:
user_id = payload["user_id"]
user = await kirak.fetch("users", {"id": user_id})
email = user["data"][0]["email"]
await kirak.notifications.send_email({
"to": email,
"template_name": "welcome",
})

Background tasks execute asynchronously outside the context of an incoming HTTP request. The run_as parameter dictates permission boundaries during execution:

run_as Execution Identity & Access Rules
"system" Runs with Kirak system identity. Bypasses row-level ownership checks; allowed only where model access lists {"role": "system"}.
"caller" Runs as the specific authenticated user who enqueued the job. Kirak records the caller ID at enqueue time and re-verifies the user when the job runs. If the user account was deactivated or their role changed, the job fails. Enqueueing requires a signed-in user (CALLER_REQUIRED 400 if enqueued as guest/system).
omitted Runs as Guest. Subject to public access permissions.
# Task running as the caller who submitted it:
@kirak.scheduler.task("generate_monthly_report", run_as="caller")
async def generate_monthly_report(payload: dict) -> None:
# Only fetches invoices the enqueuing user is authorized to view:
invoices = await kirak.fetch("invoices", {"month": payload["month"]})
...

Cron tasks run recurring scheduled logic using standard 5-field syntax:

def on_kirak_ready(kirak):
# Run every weekday at 09:00 UTC as system
@kirak.scheduler.cron("0 9 * * 1-5", run_as="system")
async def morning_digest(payload: dict) -> None:
...
# Run every 15 minutes on a dedicated Redis queue
@kirak.scheduler.cron("*/15 * * * *", provider="redis", queue="reports")
async def sync_inventory(payload: dict) -> None:
...

Cron Run-As Restriction: Crons do not have an originating HTTP request caller. Therefore, @kirak.scheduler.cron supports run_as="system" or omitted (guest), but rejects run_as="caller" with a ValueError at registration time.

Distributed Cron Deduplication Across Clusters

Section titled “Distributed Cron Deduplication Across Clusters”

In multi-instance production deployments (e.g. 5 Kubernetes pods or Cloud Run instances running the same app), Kirak prevents duplicate cron firings:

  • Database Backend: Uses the scheduler_cron_locks table (name, locked_until). The first instance to check the slot acquires the lock for that minute; other instances skip it.
  • Redis Backend: Atomically sets an expiring lock key.
  • RabbitMQ Backend: Acquires an exclusive lock queue (kirak.cron-lock.<name>.<minute>).

# Enqueue from an API route or lifecycle hook:
result = await kirak.scheduler.enqueue({
"task": "send_welcome_email",
"payload": {"user_id": 42},
"queue": "emails", # Optional: target named queue (default: "default")
"priority": 10, # Optional: higher number = picked up first
"run_at": int(time.time()) + 300, # Optional: Unix epoch seconds for deferred execution (5 min delay)
"max_retries": 5, # Optional: override default max attempts
"provider": "redis", # Optional: target specific provider instance
})
job_id = result["data"]["job_id"]
Parameter Type Default Description
task str Required Name of registered @kirak.scheduler.task. Missing key raises KeyError.
payload dict {} JSON-serializable dictionary passed to the task. Protected against secret leakage.
queue str default_queue Target queue name. Emits a warning if enqueued to a queue this worker does not consume.
priority int 0 Scheduling priority. On Database: ORDER BY priority DESC, run_at ASC. On Redis: clamped to [-999, 999]. On RabbitMQ: ignored (FIFO).
run_at int now Epoch second for deferred execution.
max_retries int max_retries (3) Maximum total attempts (1 initial run + retries).
provider str default_provider Backend instance name.

If a worker node crashes or is killed by the OS while executing a job, Kirak guarantees recovery without leaving jobs stranded in running:

  1. Time Limits (job_timeout): Every job has an execution deadline (job_timeout, default 3600 seconds in loops mode and 20 in tick mode). If a task coroutine exceeds this duration, Kirak cancels it and marks it as a timeout failure (Task '<task>' exceeded job_timeout (3600s)), triggering a backoff retry.
  2. Database Leases: When a database worker claims a job, it holds a lease valid for job_timeout + 30 seconds. If the worker process dies, a background recovery check runs every 60 seconds (reset_stale), resetting expired leases back to pending.
  3. Redis Stale Job Recovery: Redis jobs remaining in running status for longer than job_timeout + 60 seconds are recovered by reset_stale. A job with attempts left goes back to pending. A job that has used all its attempts fails with error lease_expired, as on the database provider.
  4. RabbitMQ Consumer Cap: RabbitMQ automatically requeues unacknowledged messages when a worker connection drops. To avoid running duplicate jobs when tasks approach the broker’s timeout, Kirak automatically stops jobs 60 seconds before consumer_timeout (default 1800s), ensuring the task fails cleanly before the broker reassigns it.

In serverless hosting environments (such as AWS Lambda, Google Cloud Run, or Knative), running continuous background polling loops is impractical or cost-prohibitive.

Setting "mode": "tick" disables background polling. Instead, work is driven externally via HTTP requests to POST /_kirak/scheduler/tick:

{
"scheduler": {
"mode": "tick",
"default_provider": "db",
"providers": { "db": { "type": "database" } },
"job_timeout": 20,
"min_interval_seconds": 900
}
}

Tick Route Specification (POST /_kirak/scheduler/tick)

Section titled “Tick Route Specification (POST /_kirak/scheduler/tick)”
  • Security Gate: Requires the X-Kirak-Tick-Token header matching the environment variable KIRAK_SCHEDULER_TICK_TOKEN. Without the variable set, the endpoint returns 404 Not Found. Incorrect tokens return 401 Unauthorized with constant-time comparison.
  • Rate Limit: Throttled to 6 requests per minute per process (returns 429 Too Many Requests). This is a per-process backstop, not a tenant quota: each app process keeps its own window, so the real limit belongs in front of the app (for example at the host’s gateway). Requests with a wrong token have their own window of the same size, so a flood of guesses cannot use up the window that a valid tick needs.
  • Budget Parameter: ?budget_s=25 specifies the maximum time (clamped between 0.1s and 25.0s, default 25.0s) the tick may spend running jobs before returning. The housekeeping before the jobs (stale-job reset, cron firing, schedule check) is not counted against it.
  • Job Timeout Constraint: In tick mode, job_timeout cannot exceed 20 seconds; longer values are rejected when Kirak is built. Where the host builds Kirak when the app is imported, that is at import, so the deploy fails instead of the first request.
  • Provider Restriction: Tick mode runs on the database and redis providers. RabbitMQ is loops-only and is refused at startup. Tick works with Redis alone; database schedules (/scheduler/schedules) need a database provider.
  • Next-Due Hints: Responses include {"ok": true, "next_due": <epoch_timestamp>}, telling external orchestrators exactly when the next work is scheduled.

Dynamic Schedules (Runtime HTTP-Managed Crons)

Section titled “Dynamic Schedules (Runtime HTTP-Managed Crons)”

In addition to code-based crons, Kirak supports dynamic schedules managed through REST API endpoints (/scheduler/schedules). This allows non-developer administrators to create and manage scheduled tasks without redeploying code.

Dynamic schedules are stored in scheduler_jobs (with cron_expression populated) and execute in-process HTTP calls via the built-in api_call task using httpx.ASGITransport:

Terminal window
POST /scheduler/schedules
Content-Type: application/json
Authorization: Bearer <admin_token>
{
"name": "daily-sales-report",
"cron_expression": "0 2 * * *",
"method": "POST",
"path": "/reports/generate-daily-sales",
"headers": {}
}

A schedule is stored in plain text and sent again on every firing, so it cannot carry credentials. A create or update with Authorization, Proxy-Authorization, Cookie, X-Api-Key or X-Kirak-Tick-Token headers (any letter case) answers 422 and stores nothing. A scheduled call therefore reaches only routes that need no caller identity. The admin API signs each schedule over its cron expression, queue and payload, with a key derived from KIRAK_AUTH_JWT_SECRET_KEY. Each tick verifies the signature before it fires a schedule. A row changed in the database without the key is not fired and is logged as an error each tick. Rotating the JWT secret stops every schedule until it is recreated, as it does for queued jobs.


All endpoints require the admin or system role:

Method Path Description Provider Support
POST /scheduler/enqueue Enqueue a background task for immediate or delayed execution All Backends (DB, Redis, RabbitMQ)
GET /scheduler/registered List registered tasks, cron expressions, and configured providers All Backends (DB, Redis, RabbitMQ)
GET /scheduler/jobs Query recent jobs by status, queue, or schedule_id Database only
GET /scheduler/jobs/{id} Inspect details and execution state of a specific job Database only
DELETE /scheduler/jobs/{id} Cancel a pending job (sets status to failed) Database only
GET /scheduler/schedules List runtime dynamic schedules Database only
POST /scheduler/schedules Create a dynamic schedule Database only
GET /scheduler/schedules/{id} Retrieve dynamic schedule details Database only
PUT /scheduler/schedules/{id} Update dynamic schedule expression, path, or status Database only
DELETE /scheduler/schedules/{id} Delete a dynamic schedule Database only
POST /scheduler/schedules/{id}/run Trigger an immediate on-demand execution of a schedule Database only
POST /_kirak/scheduler/tick Drive work in serverless tick mode (X-Kirak-Tick-Token required) Database or Redis provider

# 1. Modify or validate job before it reaches the backend queue
@kirak.scheduler.hook("before_enqueue")
async def route_high_priority_jobs(payload):
# payload["data"] contains: task, payload, queue, priority, run_at, max_retries, provider
if payload["data"]["priority"] >= 10:
payload["data"]["queue"] = "high-priority"
return payload
# 2. Intercept after job is stored
@kirak.scheduler.hook("after_enqueue")
async def notify_job_enqueued(payload):
job_id = payload["data"]["job_id"]
return payload
# 3. Before task execution
@kirak.scheduler.hook("before_job")
async def prepare_job_context(payload):
# payload is the task's input payload dictionary
return payload
# 4. After task completion
@kirak.scheduler.hook("after_job")
async def audit_job_completion(payload):
return payload
# 5. On failure (fires on every retry attempt and final failure)
@kirak.scheduler.hook("on_job_failure")
async def alert_job_failure(payload):
job = payload.get("job", {})
error = payload.get("error", "")
if job.get("attempts", 0) >= job.get("max_attempts", 3):
# Permanent failure alert:
print(f"CRITICAL: Job {job.get('id')} failed permanently: {error}")
return payload