Your web handler has just spent nine seconds emailing three hundred users, and the request timeout is ten. Every Python team eventually hits the same wall: some work is too slow, too flaky, or too bursty to live inside a request/response cycle. The heavyweight frameworks answer with brokers, configuration DSLs, and result backends wired into your ORM. RQ takes the opposite bet: it assumes you already run Redis, it stores everything in ordinary Redis hashes and lists, and its entire public surface fits on one screen. Queue a function, run a worker, read a result.
Then the second wave of pain arrives, and it is quieter. Jobs start vanishing. A worker gets OOM-killed mid-task and the job is stuck in started forever. Another job hangs on a dead socket and blocks its queue for twenty minutes. A crashed worker leaves queue state nobody can explain. These are not bugs you fix with a try/except; they demand process isolation, heartbeats, and garbage collection. This is exactly where RQ’s design gets interesting: every job executes in a forked child process, the parent watches that child with wait4, timeouts are enforced with SIGALRM, and every state transition lands in a Redis sorted set that a cleanup pass can inspect.
This post is a source tour of the real rq/rq checkout on master — RQ 3.0.1, whose layout changed in the 3.x line (the worker is now a package, rq/worker/, and the cron machinery is new). Every claim below was checked against the code, and each bullet carries a line-anchored link. Two diagrams anchor the tour: an overview of the moving parts, and a detail map of the enqueue/dequeue/execute loop.
RQ at a glance: the public API, the queueing layer over Redis lists, the job model, the worker family, the registries, and the CLI that glues them together.
Reading the overview from left to right, these are the load-bearing symbols, each verified in the master tree:
- Queue.enqueue_call, L732 — the real entry point behind
enqueue(); it resolves a function reference, applies defaults, then hands off to the persistence step. - Queue.enqueue_job, L1254 — rate-limit checks, dependency setup, and the push of the job id onto the queue’s Redis list; deferred jobs are held back.
- JobStatus, L56 — eleven lifecycle states, including newer ones like
rate_limitedandready_to_enqueue. - BaseWorker.work, L612 — the main loop: bootstrap, install signal handlers, then dequeue, execute, heartbeat, repeat.
- Worker.fork_work_horse, L60 — the actual
os.fork()at L68; the child callsos.setpgrp()and never returns. - Worker.monitor_work_horse, L79 — the parent’s watch loop; it kills the horse once
working_timeexceedsjob.timeout + 60. - UnixSignalDeathPenalty, L61 — inside the horse,
signal.alarmturns an overrunning job into aJobTimeoutException. - BaseRegistry.requeue, L202 — moves a failed job back onto its queue, the mechanism behind the
rq requeueCLI command. - Result.Type, L18 — five result kinds, from
SUCCESSFULtoMAX_RETRIES_EXCEEDED, stored as compressed payloads.
The detail map: how an enqueued job id reaches a forked work horse, how the parent monitors it, and which registries record each outcome.
How a Job Becomes a Redis Hash
Enqueueing looks like one call, but it is a short relay. Queue.enqueue_call resolves whatever you passed — a plain function, a string import path, or a decorated callable — into a Job. Job.create then freezes the important decisions into the object: the function reference, args and kwargs, the timeout, result TTL, retry policy, callbacks, and webhooks. Only after that does control reach enqueue_job, which runs the pre-flight checks (a rate-limited namespace, unique=True rules, and the rule that rate-limited jobs cannot ride a caller’s batching context) and finally pushes the id with RPUSH.
Two details in that relay deserve attention. First, dependencies: enqueue_job calls setup_dependencies, and if the job depends on unfinished parents, its status becomes DEFERRED and the id is not pushed yet. The child id sits in the parents’ dependents_key set until a parent finishes; Dependency.get_jobs_with_met_dependencies in rq/dependency.py computes who is free to go, and Queue.move_dependents_to_ready moves them. Second, the pop itself is not a plain pop. On Redis 6.2+ with a single queue, dequeue_any uses LMOVE to atomically move the popped id onto an intermediate list at <queue>:intermediate, and IntermediateQueue records a first_seen timestamp per job. If the worker dies between pop and execution, that staged id is still visible, and IntermediateQueue.cleanup fails any job stuck there for more than a minute. Indefinite blocking is refused outright — a timeout of 0 raises a ValueError, because a worker that waits forever also stops sending heartbeats.
The job record itself is an ordinary Redis hash under rq:job:<id>; statuses live in one field validated against JobStatus, and ids allow only letters, digits, underscores and dashes. In 3.x, executions use composite keys of the form job_id:execution_id, which parse_job_id splits apart — one job can carry multiple execution records without a second data model.
The Work Horse: fork() as Fault Isolation
The work loop in BaseWorker.work is deliberately boring: check suspension, run maintenance when due, dequeue with a timeout, call execute_job, heartbeat, and stop when max_jobs or max_idle_time says so. The interesting part is what execute_job means. In the default Worker class it is three steps: prepare_execution, fork_work_horse, and monitor_work_horse. The parent never runs your function. It forks, and the child — the “work horse” — enters main_work_horse, reseeds the RNG so it does not inherit the parent’s random sequence, ignores SIGINT (Ctrl-C belongs to the parent, which shuts down gracefully), runs perform_job, and exits through os._exit so no deferred cleanup code runs in the child.
Inside the horse, perform_job wraps Job.perform in the configured death_penalty_class — by default UnixSignalDeathPenalty, which arms signal.alarm(timeout) and raises JobTimeoutException from the signal handler when the job overruns. This is why RQ timeouts are real even when the job is stuck in C code or a blocking syscall: the kernel interrupts the process. On platforms without SIGALRM, get_default_death_penalty_class falls back to TimerDeathPenalty, which injects an exception into the worker thread via PyThreadState_SetAsyncExc — a much more fragile trick that only works in pure-Python frames, one of the honest limits below.
Meanwhile the parent is not idle. monitor_work_horse loops on wait_for_horse (os.wait4, so it also collects rusage), refreshing heartbeats every job_monitoring_interval seconds; if the horse’s working_time exceeds job.timeout + 60, the parent kills the whole process group with kill_horse (via os.killpg, which is why the child called os.setpgrp()). If the horse dies unexpectedly — segfault, os._exit(1), OOM kill — the parent checks the job status and, unless the horse already recorded success or failure, writes the failure itself with the message Work-horse terminated unexpectedly; waitpid returned .... The result is a system where a crashed job still reaches a terminal state, which is the property most home-grown queues never achieve.
The family around the base class exists for constrained environments. SimpleWorker skips the fork entirely and calls perform_job in the worker process — cheap, and the right choice on Windows or in-process test runners, at the cost of losing memory isolation. SpawnWorker replaces os.fork() with os.posix_spawn() for platforms where fork is unsafe (macOS is the documented motivation), and because the child can no longer rely on copy-on-write memory, it pickles the worker configuration up front and refuses to start with classes defined in __main__, since they cannot be imported by the horse. HerokuWorker adapts shutdown to the platform’s 30-second SIGRTMIN grace window.
Registries, Results and the Dependency DAG
Every state change lands in a registry — a Redis sorted set with a timestamp score. StartedJobRegistry and FinishedJobRegistry track running and completed work; FailedJobRegistry holds failures (with a one-year default expiry — see the numbers below); DeferredJobRegistry holds dependency-blocked ids; ScheduledJobRegistry scores each id by the epoch second it becomes due; CanceledJobRegistry and ReadyJobRegistry round out the newer statuses. Because entries expire, cleanup is garbage collection: registries expose expired ids by score, and the worker runs maintenance every ten minutes. BaseRegistry.requeue is the operational escape hatch — it re-enqueues a failed job, optionally at the front — and the CLI’s rq requeue --all simply drains the registry through it.
Results are a separate, append-only model. Result.Type distinguishes SUCCESSFUL, FAILED, STOPPED, RETRIED, and MAX_RETRIES_EXCEEDED, so a retried job keeps its history instead of overwriting it. Payloads are compressed with zlib and base64-encoded, and an unserializable return value is replaced with a sentinel string rather than crashing the worker after the work is done. Job.latest_result and Result.fetch_latest (with a blocking timeout) give consumers a poll-or-wait API on top.
Scheduling ties registries and workers together. RQScheduler is a separate process started with work(with_scheduler=True); it acquires per-queue locks, heartbeats independently, and periodically promotes due ids from ScheduledJobRegistry onto their queues. The 3.x cron machinery (rq/cron.py and its registries) builds on the same lock-and-heartbeat pattern for recurring jobs.
From SIGALRM to posix_spawn: Build Facts
Concrete numbers in the code explain RQ’s runtime behavior:
- Worker heartbeat TTL:
DEFAULT_WORKER_TTL = 420seconds inrq/defaults.py(L53); the CLI exposes it as--worker-ttl. - Result retention:
DEFAULT_RESULT_TTL = 500seconds (L64), while failures persist forDEFAULT_FAILURE_TTL = 31536000— one year (L71). - The monitor’s grace window: a horse is killed only after
job.timeout + 60seconds, hard-coded atrq/worker/worker_classes.pyL101, with heartbeats refreshed everyDEFAULT_JOB_MONITORING_INTERVAL = 30seconds. - Maintenance cadence:
DEFAULT_MAINTENANCE_TASK_INTERVAL = 10 * 60(L105); the intermediate queue fails stuck jobs after one minute (rq/intermediate_queue.pyL81). - Click-driven CLI:
rq/cli/cli.pybuildsempty,requeue,infoand friends on click —rq workerinrq/cli/workers.pyalone defines more than twenty flags, and it warns thatRoundRobinWorker/RandomWorkerclasses are deprecated in favor of--dequeue-strategy. - Process mechanics: the fork path uses
os.fork()plusos.setpgrp()plusos.wait4(); the spawn path pickles a config tuple includingdeath_penalty_classand exception handlers beforeposix_spawn. - Context tracking:
rq/local.pyis a vendored copy of Werkzeug’s context-locals module — its 2011 copyright header is still there — using greenlets when available soget_current_job()works across async contexts.
A worker pool (rq/worker_pool.py) rounds this out: one process spawns and supervises a configured mix of worker classes.
Honest Limits
The fork model is POSIX-only; on Windows you fall back to Enjoyed this post? Never miss out on future posts by following us SimpleWorker and give up memory isolation. The SIGALRM death penalty cannot interrupt C extensions holding the GIL — hence the sixty-second grace before the parent resorts to kill_horse — and the thread-based fallback uses an async-exception trick best described as inherently unreliable. Because the horse inherits memory at fork time, a job that mutates shared objects silently diverges from the parent, and any connection objects rebuilt in children must drop runtime-only kwargs — exactly what rq/connections.py does. Rate-limited jobs, for now, refuse custom key prefixes and cannot be enqueued through a caller’s batching context. When a horse hangs rather than dies, a sampling profiler is your fastest answer — point py-spy at the horse process while monitor_work_horse holds the watch. None of these are disqualifying; they are the edges you should know before an incident, not during one.