Task queue and parallel workers
New in 1.7.0 Status: phases 0 to 4 are in: the queue runs every job, manage.py run_workers replaced
qcluster, django-q2 is gone (its tables stay one release for the upgrade), Scan Faces fans out, and the width
follows PARALLEL_WORKERS and the capacity check at runtime (api/jobs/parallel.py, GET/PATCH /api/parallel-workers/ for admins), shown in the site settings. What is left is in
the last paragraph below.
This page is the plan for #3073: a queue that LibrePhotos owns, so that the number of parallel workers can follow what the machine (or the container) really has, and so that parallel lanes do their work once.
Why not keep django-q2
Every enqueue already goes through one seam, apps/backend/api/jobs/queue.py. Behind it, LibrePhotos
works around django-q2 in many places:
| Need | Today | Where |
|---|---|---|
| A task of a dead cluster runs again | a broker subclass with a renewed 10-minute lease (#2852, #2876) | api/jobs/broker.py |
| An old container must not run the new release's tasks | the same subclass checks for unknown migrations before each dequeue (#2848) | api/jobs/broker.py |
| A task whose function moved fails once, not forever | a tolerant unpickler and a hand-written failure record (#2945) | api/jobs/broker.py |
| Stuck-job cleanup knows which jobs are alive | unpickles every queued payload (held_job_ids, #2879) | api/jobs/queue.py |
| Cancel drops the queued tasks of a job | unpickles every queued payload (remove_queued_tasks) | api/jobs/queue.py |
| Nominatim gets at most one request per second | a file-locked SQLite database per host (django-q2#350 stalled) | api/geocode/rate_limit.py |
| How many workers | cpu_count() of the host, ignoring a container limit; 2 in the standalone build | settings/production.py, settings/standalone.py |
| Memory | max_rss and recycle, checked only between tasks | Q_CLUSTER |
Payloads are pickles: 37 enqueue sites pickle a whole User, a moved function breaks the queue, and
nothing can be read from a queued task without unpickling it. A chain continues after a cancelled or failed
step, which is how a cancelled Generate Face Embeddings started four Find Similar Faces at once (#3073).
The queue below is about 1,000 lines with tests, replaces broker.py and rate_limit.py, and keeps the
seam's functions, so the ~49 call sites do not change.
Tables
All in the api app, written only by api/jobs/ (the models hold data and queries, as everywhere).
api_queuedtask, one row per task:
| Column | Type | Meaning |
|---|---|---|
id | bigint pk | claim order within a priority |
func | varchar(200) | dotted path of the function, resolved with pydoc.locate when the task runs |
args, kwargs | JSON | the arguments, encoded by api/jobs/payload.py (below) |
queue | varchar(32) | default, heavy (faces, captions, tags, OCR), geocode |
priority | smallint | higher first; follow-ups of a running job get +1 so its tail is not starved |
status | varchar(10) | waiting (behind a chain step or a group), queued, running, failed, cancelled |
run_after | timestamp | not claimed before; also the retry backoff |
lease_until, worker | timestamp, varchar | the running task's lease and who holds it |
attempts, max_attempts | smallint | a task is retried until max_attempts (default 3), then failed |
after | fk self, null | chain: this row is waiting until that one ends |
continue_on_error | bool | run even when after failed or its job was cancelled (today's chains need it) |
group | fk api_taskgroup, null | member of a barrier group, or (with status=waiting) its follow-up |
dedupe_key | varchar(200), null | unique among waiting/queued/running rows (partial unique index) |
job_id | varchar(36), null, indexed | the LongRunningJob the task belongs to, read from its job_id argument |
error | text | the last failure, for the admin and the error report |
created_at, started_at, finished_at | timestamps |
A task that succeeds is deleted in the transaction that ends it; failed and cancelled rows are kept
for 7 days (the daily old-job cleanup deletes them). Indexes: (status, queue, priority desc, id)
partial on status='queued', (job_id), (status, lease_until) partial on status='running'.
api_taskgroup: id, total, ended (counter), fired (bool). api_taskschedule: name
(unique, null), func, args, kwargs, schedule_type (O once, I minutes, H hourly, D daily:
the letters django-q2 used), minutes, next_run, intended_date_kwarg, last_run.
api_workerprocess: one row per live worker (name, host, pid, slot, started_at,
heartbeat_at, rss_mb, task_id, recycled_for): the admin's Workers panel reads it.
api_throttle: key (pk), next_at.
Payloads
api/jobs/payload.py encodes None, bool, int, float, str, lists, tuples, dicts with string keys,
UUID, datetime, date, and a model instance as {"__model__": "api.user", "pk": 1}. The worker loads
the instance again when the task runs, so a task works on the row as it is then, not on a copy from when
it was queued, and call sites keep passing user. Anything else is a TypeError at enqueue time, in the
request that queued it, not in the worker.
Not released yet (comes after 1.7.0) The enqueue_* functions and
start_job take Queueable arguments, so mypy refuses such a call before it runs.
Claiming
A worker claims one task per transaction. On PostgreSQL:
UPDATE api_queuedtask
SET status = 'running', worker = %(worker)s, attempts = attempts + 1,
started_at = now(), lease_until = now() + interval '10 minutes'
WHERE id = (SELECT id FROM api_queuedtask
WHERE status = 'queued' AND run_after <= now() AND queue = ANY(%(queues)s)
ORDER BY priority DESC, id
LIMIT 1
FOR UPDATE SKIP LOCKED)
RETURNING id, func, args, kwargs, job_id, attempts;
SKIP LOCKED lets N workers claim in parallel without waiting for each other. SQLite has no row locks:
there the same SELECT ... LIMIT 1 and UPDATE ... WHERE id = ? AND status = 'queued' run in one
BEGIN IMMEDIATE transaction (transaction_mode=IMMEDIATE, settings/_sqlite.py), which takes the
database's write lock first, so claims are serialised and never double. Both go through the ORM
(select_for_update(skip_locked=True), which Django leaves out on SQLite).
The queues a worker asks for depend on the caps: heavy only while fewer than heavy_width heavy tasks
run, geocode while none runs. The count and the claim share the transaction; on PostgreSQL a
pg_advisory_xact_lock per capped queue makes the count exact across hosts.
Leases. Each worker renews lease_until of its task every minute from a thread. The supervisor
requeues the task of a worker it saw die at once; any supervisor requeues a running row whose lease
ran out (a host that went away) within a minute. A requeued task with attempts >= max_attempts becomes
failed, so a photo that kills its worker every time stops after three tries instead of looping.
Quitting costs no attempt. Not released yet (comes after 1.7.0) When the workers are asked to stop, a task ends at its next
checkpoint() (between two photos, or two pieces of a download) and is put back as if it had not been tried
(store.put_back); its job starts again with the next worker and goes on with what is left. A worker that reaches no
checkpoint within STOP_GRACE_SECONDS is killed, and that does not count either (store.put_back_of_worker). A worker that
crashes by itself meanwhile does count. Up to 1.7.0 a killed worker's attempt counted, so a long job failed when LibrePhotos
was closed for the third time while it ran.
The supervisor's warning about a worker that died (killed for memory by the system, say) names the task it was running, and is a warning, not an error report.
The queue promises that two live workers never run the same task at once while its lease holds. A task can still
run more than once: again from the start when its worker process dies or is paused by a stop or a memory drain,
and beside the first run when a worker is alive but could not renew its lease for ten minutes. A task's work has to
tolerate a second run.
Not released yet (comes after 1.7.0) A lease counts from the moment the claim, or the renewal, holds its database lock. Up to
1.7.0 the clock was read before the wait for that lock, so on a busy SQLite database the wait, at most the five
minutes of SQLITE_TIMEOUT_SECONDS, came off the ten.
A task's writes belong to the attempt that holds it. Not released yet (comes after 1.7.0) Every write after the
claim (succeed, fail, release, and the requeue of a dead worker's or an expired task) is one
conditional UPDATE/DELETE ... WHERE id AND status = 'running' AND worker AND started_at of the claim.
succeed locks that row first (SELECT ... FOR UPDATE on PostgreSQL; on SQLite the IMMEDIATE
transaction holds the write lock), so it releases the successors and counts the group member only while
the attempt still holds the task. The reaper's requeue also repeats lease_until < now, so a lease renewed
after the reaper listed it, or a task another supervisor already requeued and a worker claimed again,
is left alone. A worker whose renewal is refused (the task was requeued while the host slept, the
database was down or SQLite's write lock was held for longer than the lease) stops the task at its next
checkpoint() (LeaseLostError, a BaseException) and reports nothing; one that never reaches a
checkpoint finishes, and its result is dropped with a warning. Up to 1.7.0 such a stale worker deleted
the row another worker was running and counted the group member again, so a group follow-up (Scan
Faces' finish_face_scan) could finish the job while a chunk had not run.
Database errors. A worker that cannot claim a task, or record the end of one, because the database fails (locked past the timeout, a dropped connection, a damaged SQLite file) logs a warning and tries again, waiting twice as long each time up to a minute, instead of exiting. A task whose end it could not record runs again once its lease runs out. Up to 1.6.0 django-q2's pusher and monitor exited on such an error and were started again ("reincarnated pusher ... after sudden death").
Release guard. Before each claim a worker checks, with one count(*) of django_migrations, whether
anything was applied since its last look, and only then compares names (unknown_applied_migrations).
When the database has a migration this code lacks, the worker stops claiming and the old container's
tasks finish under their leases (#2848). Not released yet (comes after 1.7.0) It asks again right after a claim and puts the task back
(release, the attempt not counted) when the migration came in between, so old code never runs a task the
new release queued.
A task this release cannot run, because it does not have the function, the function takes other arguments, or
an argument names a model or an encoding it does not know, Not released yet (comes after 1.7.0) is queued again in two minutes
(store.leave_to_another_release, UNKNOWN_FUNCTION_DELAY): while two releases without a migration between
them share the queue, the one that can run it gets it. Each claim counts as an attempt, so a task
no release can run ends as failed after max_attempts, four minutes later, with its job. Up to 1.7.0 the
first worker to claim it removed it (#2945).
A task that raises takes its job with it. Not released yet (comes after 1.7.0) store.fail settles the job the task still heads in the
same transaction: an exception the job's own code did not turn into job.fail() (a user deleted while the task waited, a
database error) fails the job with the exception's last line. Up to
1.7.0 the task failed and its job stayed running until the stuck-job cleanup, refusing a new start.
A download in front of a scan has a job row from the start. Not released yet (comes after 1.7.0) enqueue_chain(prerequisites=...) takes
JobSteps and writes their rows with the chain, in its transaction, so a killed Download Models is taken
over like any job task (next paragraph). Up to 1.7.0 the task wrote a row when it ran and another one when
it was retried, and the first stayed running.
A job task retried after a kill takes over its job. Not released yet (comes after 1.7.0) The first claim of a
task with a job_id hands it the job's unstarted row (claimed_by_task), which makes it the job's head.
The head holds the job until it returns: store.succeed first lets go of it (claimed_by_task = NULL,
its own commit), then ends the head row. When a head that still holds its job is lost, _lost settles
the job in the same transaction:
- Its worker is gone (
requeue_worker, fromPool.replaceafter the process exited, also after the memory watchdog'sEXIT_MEMORY, or fromPool.shutdownafter its kill) and the job left no trace (no other task with itsjob_id, no counted item,CountedJobItem): the row'sstarted_atis cleared, so the retry'sLongRunningJob.claimsucceeds and the work starts again from the beginning. - It left a trace: the head was killed while it counted items itself. Running it again would reset the
progress and the items counted already would never count again, and leaving it would stop the job short
of its target, so the job is failed ("... before it had queued all of the job's work"). A head that
queues pieces leaves no trace until all of them are queued (
enqueue_pieces, below). - Its lease expired on a host that cannot see the holder (
requeue_expiredof another host): the head may still be running, so the job is failed ("its worker went away (lease expired)"). The retry getsNone, its chained step is cancelled, and the stalled head'scomplete(),set_result()andupdate_progress()are refused because the job has ended. - It was the last attempt: the job is failed, since nothing else would end it.
A takeover starts the job over: the reopen also clears its result and its progress counters, so the
first attempt's counts do not carry into the second.
A head that returned has let go of its job, so a kill between its return and the end of its row leaves
the job to its pieces. A head that queues pieces lets go in the transaction that queues them, so from then
on losing it changes nothing. Up to 1.7.0 every retry got None and returned, its chained step ran, and the job
stayed running, refusing a new start with job_already_running, until the stuck-job cleanup failed it
after STUCK_JOB_HOURS.
A lapsed lease of a worker that still runs its task is renewed. Not released yet (comes after 1.7.0) After a
laptop or VM suspend, or a database outage longer than the lease, the supervisor's reaper (every 30 s)
often runs before the worker's renewal (every minute). Pool.requeue_expired hands store.requeue_expired
a check (Pool.still_runs) that renews the lease instead of requeueing the task when the holder is one of
the pool's live processes and that process's WorkerProcess row, which the worker's own renewal writes
every minute under the same lock as its task, still names the task (a restarted process clears the
name when it registers). A worker that moved on (it could not record the end of a task, logged
the DatabaseError and claimed the next one) or a new process that got an old one's name no longer names
it. The reaper vouches for a task for at most VOUCH_LIMIT (three leases) without the worker's own
heartbeat moving, so a process that hangs with the interpreter lock held still loses its task. Only a
holder that is gone, moved on, hung, or runs under another host's supervisor loses its task.
Docker stops the workers without the grace period. The backend image runs entrypoint.sh under bash
as PID 1, which clears its traps before it starts uvicorn, so a docker stop never reaches
run_workers as SIGTERM, and Docker's default stop_grace_period of 10 s is shorter than the
supervisor's 25 s anyway. Pool.shutdown then neither kills nor requeues anything: the workers die with
the container, and their tasks stay running until their leases run out, about 10 minutes after the
restart. A job head among them is then failed by the expiry rule above, not taken over. A restart
outside Docker (the standalone build, run_workers by hand) goes through Pool.shutdown.
Processes
manage.py run_workers (supervisor: one per host or container)
├── scheduler thread due schedules → tasks, catch_up=False
├── reaper thread expired leases → queued / failed; leases of dead workers at once
├── capacity thread every 30 s: capacity check → width W (shared multiprocessing.Value)
└── fork server Linux: Django and the task modules loaded once (api.jobs.worker_preload)
└── worker 0 .. N_max-1 forked from it; worker i claims only while i < W
└── lease thread, memory watchdog thread
- The supervisor replaces
qcluster, its sentinel, pusher and monitor. - Not released yet (comes after 1.7.0)
run_workersstarts without Django's system checks (requires_system_checks = ()): the URL check imported every view and serializer into the supervisor, about 19 MB it never used.migrate, which runs before it, still runs them. - New in 1.7.0 On Linux, run from source (the Docker images), workers are started with
multiprocessing
forkserver: a fresh interpreter, started by the supervisor before any of its threads run, importsapi.jobs.worker_preload(django.setup(), the scan pipeline modules, its database connections closed,gc.freeze()) and forks every worker from that state. A worker is still never a fork of the supervisor (no threads, locks or connections are inherited), and the pages of Django and the imported modules are shared between the workers instead of copied into each: about 30 MB of a worker's own instead of 110 MB, and a worker starts in milliseconds. Windows, macOS and the standalone builds keepspawn(the standalone build starts its workers from thelibrephotos-workerlink). Up to 1.6.0 and in 1.7.0 previews, every platform usedspawn. - The standalone build. Nuitka leaves
sys.executablepointing at apython.exethe distribution does not have, sostandalone.run_managepointsmultiprocessing.set_executableat thelibrephotos-workerlink, or at the binary itself when the link is gone (the 1.6.0 WinError 2). A spawned worker runs the entry script again as__parents_main__without callingmain(), solibrephotos_standalone.pyandlibrephotos/standalone.pyboth callbootstrap_process()at import: the standard handles, the hidden child consoles and the console log redirect are set up in every process. Whether the process is the compiled build is read fromstandalone.py's own__compiled__, not from__main__, which in a spawned worker is multiprocessing's bootstrap. The supervisor itself and the sidecars are plainsubprocesschildren of the binary (standalone.child_command), each under its own name, so closing the launcher takes the whole application down. On Windows the launcher's job object holds all of them, also a sidecar whose starter has exited since, soown_process_idsfinds every one at shutdown. The web server stays in the launcher's own process with one uvicorn worker andWEB_THREADSthreads: more workers would need the same spawn through the binary, and one is enough for a desktop. W(the effective width) changes at runtime without a restart, from the setting, the capacity check and the memory left; at mostN_maxworkers run.- New in 1.7.0 Workers on demand. The supervisor starts a worker only for work: every
second, while fewer than
Wworkers run, it counts the tasks that are due (queuedwithrun_afterpassed; a capped queue,geocodeorheavy, counts up to its cap) plus those running on its host (store.demand), and starts workers up tomin(W, that count). A worker that found nothing to claim forTASK_WORKER_IDLE_EXIT_SECONDS(30 s) exits (EXIT_IDLE, 6, itsWorkerProcessrow turns inactive) and is not replaced until there is work again, so an idle server runs no worker, and the memory a scan left in its workers goes back 30 s after the queue drained instead of when each worker reached its recycle size. On spawn platforms (Windows, macOS, the standalone builds) slot 0 stays (keep_warm=1): starting a spawned worker costs two seconds of imports, which the minutely upload sweeper would otherwise pay every minute. Up to 1.6.0 and in 1.7.0 previews,N_maxworkers ran from the start and idled on a 1 s poll at about 110 MB each. - Not released yet (comes after 1.7.0) Free heap back to the system. glibc keeps the memory a task freed in its heaps
for the next allocation, so a worker's resident size only grows during a scan. On Linux the worker calls
malloc_trim(0)(api/runtime/heap.py) after a task at most everyheap_release_seconds(10 s, inWorkerSettings) and once when it finds nothing to claim. One worker scanning the 159-file benchmark library held 130 MB of its own at the end without it and 107 MB with it, in the same time (156 s and 157 s). A call takes about 100 ms after a task that freed a lot and 4 ms otherwise. The call is skipped on other platforms and with a libc that has nomalloc_trim(musl). - Stop. POSIX:
SIGTERM/SIGINT. Windows has noSIGTERM, so the standalone launcher starts the supervisor with--stop-file <BASE_DATA>/workers-<pid>.stopand creates that file to stop it; the supervisor looks for it every half second. The supervisor sets a shared stop event, workers finish their task, and after 25 s the rest are killed and their tasks requeued. Not released yet (comes after 1.7.0) A worker that exited during those 25 s (over its memory limit, a crash) has its task requeued as well; one that outlives its kill keeps its task under its lease rather than having its job taken over. Processes are always stopped by PID tree, never by a command-line filter. - Graceful in the task.
api.jobs.worker_runtime.checkpoint()raisesWorkerStopping(aBaseException, so a task'sexcept Exceptiondoes not swallow it) when the worker must stop or recycle. A task that calls it between items (the Scan Faces chunk, Generate Face Embeddings) is requeued without an attempt and resumes: its items are counted once (CountedJobItem), and the chunk skips photos already counted.
Chains, groups, deduplication, cancel
- Chain.
enqueue_chainwrites every step at once: the firstqueued, each next onewaitingwithafteron the previous. When a step ends, its successor becomesqueuedif the step succeeded (the task returned and its job row is neither cancelled nor failed), else it iscancelledtogether with its job row ("an earlier step did not finish") and the rest of the chain, unless the successor hascontinue_on_error. The scan's follow-ups keep today's behaviour withcontinue_on_error=True; new chains stop by default. A scan reads no model, so it never waits for a model download: while models are missing,_queue_followup_jobs(api/directory_watcher/scan_jobs.py) chains the tags, search, face and text jobs behind the download instead (verification/scanning/PhotosBeforeModels.tla). Not released yet (comes after 1.7.0) A prerequisite whose function is already queued or running is not queued again: the chain waits behind the open task.store.lock_openlocks its row until the chain is written, so the task cannot end in between and leave the chain waiting for good. - All pieces or none. Not released yet (comes after 1.7.0) A head that splits its job into pieces (the scan's file groups
and sidecars, the photos of Add Geolocation, Generate Tags, Generate Captions and Extract Text, the batches of
Apply date rules and Write metadata to files) queues them with
enqueue_pieces(job_id, pieces). The pieces go into a temporary table first, 5,000 at a time, which holds no lock of the database. One transaction then locks the job row, stops if the job was cancelled or ended, copies the pieces into the queue with oneINSERT ... SELECTand lets go of the job. A head that is stopped before that leaves no trace, so it starts again; after that everything is queued. On SQLite the write lock is held for about 1 second for 100,000 pieces and 5 seconds for 500,000 (measured on a busy laptop; preparing them takes five times as long, without the lock), and another writer waited that long at most. Up to 1.7.0 each piece was its own commit, about 150 a second: LibrePhotos closed in the middle of it failed the scan, and the files that were not queued yet stayed out until the next scan. Pieces now start when all of them are queued. A test of such a job replaces the queue withqueued_pieces(api/tests/utils.py). - Group barrier.
enqueue_group(job_id, tasks, then=step)writes ataskgroupwithtotal = len(tasks), the members, and the follow-up aswaiting. Whenever a member ends (succeeded, failed after its last attempt, or cancelled), the same transaction runsUPDATE api_taskgroup SET ended = ended + 1and reads it back; the transaction that bringsendedtototalsetsfiredand queues the follow-up. Failed and cancelled members count as ended, so the follow-up always runs exactly once; it decides itself what to do about a cancelled job. - Dedupe. A partial unique index on
dedupe_keywherestatus in ('waiting','queued','running').enqueue_followup(..., dedupe_key=...)inserts the job row and the task in a savepoint; on theIntegrityErrorit rolls both back and returns the existing job. Generate Face Embeddings and Find Similar Faces queued by Scan Faces usefaces:embeddings:<user>andfaces:cluster:<user>. - Later. Not released yet (comes after 1.7.0)
enqueue_task_at(func, *args, at=..., dedupe_key="")writes the task withrun_after = at, so no worker claims it before then. With adedupe_keyit is dropped while an open task has the same key, a running one included. The rating write-back queues a job that found its photo claimed for the end of that claim this way, withrating:<photo id>(Rating write-back). - Cancel is
UPDATE api_queuedtask SET status='cancelled' WHERE job_id = %s AND status IN ('waiting','queued'), plus the chain rule above for their successors and the group rule for their barrier. No payload is opened. A running task still checks its job row (stop_if_cancelled). - Enqueue is transactional. The task row is written in the transaction that writes the job row, so
transaction.on_commitand the "could not queue the job" failure path go away: either both exist or neither. held_job_idsfor the stuck-job cleanup isSELECT DISTINCT job_id ... WHERE status IN ('waiting','queued','running').- One job row, many writers. Every task of a fan-out job reports into the job's
resultJSON (update_job_resultinapi/directory_watcher/utils.py: errors, counts, the face service's unreachable streak;LongRunningJob._merge_resultwhen it ends). Each write reads the rowselect_for_updatein a transaction and writes it back there, so concurrent writers queue on the row lock (on SQLite, on the write lockBEGIN IMMEDIATEtakes) and none is lost or refused. New in 1.7.0 Up to 1.6.0 this was a compare-and-swap that read the row, wrote only ifresultwas still what it read, and gave up after 50 tries. When many workers wrote at once (say a Scan Faces whose face service was down, every chunk writing an error per photo), a worker could lose 50 races in a row ("gave up updating its result after 50 conflicting writes"), and the item it was counting was never counted, so the job could not reach its target.
Scheduler
api_taskschedule replaces django_q_schedule with the four types in use. The scheduler thread looks
every 5 s for next_run <= now, and fires a schedule with a conditional update (SET next_run = <next> WHERE id = %s AND next_run = <the value it read>), so two supervisors never fire it twice. catch_up is
off: the next run is the first one after now, so a minutely schedule missed for an hour runs once
(today's "catch_up": False, #2848). ONCE rows are deleted when they fire. With intended_date_kwarg
the task gets the run's due time in ISO format, as django-q2 passed it. The start_* management
commands still create the schedules at boot, through the same ensure_schedule/replace_schedule.
Not released yet (comes after 1.7.0) Both look and write in one transaction that holds hold_schedules (a PostgreSQL advisory lock until the
commit; on SQLite the IMMEDIATE transaction is enough), so two servers starting at once make one schedule.
ensure_schedule also deletes the extra rows of the same function and type that two servers made before that, and
keeps the one due first.
sync_scan_schedule reads the automatic scan's setting under the same lock, after the setting was committed,
so of two saves at once the last one is scheduled.
Throttle
New in 1.7.0 Up to 1.6.0 the geocoding rate limit was a file-locked SQLite database under
BASE_DATA (geocode_rate_limit.sqlite3), which only held on one host. That file is no longer used.
api/jobs/throttle.py wait(key, seconds): UPDATE api_throttle SET next_at = now + seconds WHERE key = %s AND next_at <= now; one row updated means go, otherwise sleep until next_at and try again. It is in
the main database, so it holds across processes and across hosts (the file lock it replaces only held on
one host). Reverse geocoding calls it per provider (Nominatim 1.1 s), and geolocation tasks run in the
geocode queue, capped at one at a time, so the other workers do other work instead of sleeping.
Memory
- Hard limit per worker. The watchdog thread reads the worker's RSS every 2 s; above
hard_limitit exits at once (EXIT_MEMORY). Not released yet (comes after 1.7.0) The supervisor requeues its task (an attempt counts) once the process is gone, then starts a new worker and recordsrecycled_for(shown in the admin). Up to 1.7.0 the watchdog requeued the task itself while the worker's main thread could still commit. - Soft limit per worker. Above
soft_limit(0.75 × hard_limit) the nextcheckpoint()raisesWorkerStopping: the task is requeued without an attempt and the worker exits to be replaced. A task without checkpoints finishes first. This covers the inside of long tasks, whichmax_rssnever did. - Idle. A worker idle for
TASK_WORKER_IDLE_EXIT_SECONDSexits and gives all of its memory back (see Workers on demand). - Machine. When the capacity check sees less than
low_wateravailable memory (the larger of 512 MB and 10 % of the limit), it lowersWby one per round, down to 1; it raises it back by one per round once there is room again. hard_limitdefaults tomax(600 MB, lane_ram)and can be set (WORKER_MEMORY_LIMIT_MB).
Capacity and the worker count
api/runtime/capacity.py has no Django imports, so sidecars can use it.
| Quantity | Linux, Docker, Kubernetes | Windows |
|---|---|---|
| RAM total | min(host, cgroup): v2 memory.max, v1 memory.limit_in_bytes | min(host, Job Object limit) (QueryInformationJobObject) |
| RAM available | min(host available, limit - (usage - inactive_file)) | host available |
| Cores | os.process_cpu_count() (affinity, --cpuset-cpus), capped by cpu.max or cfs_quota_us / cfs_period_us | os.process_cpu_count() |
| GPU, VRAM | nvidia-smi through api.runtime.binaries; unknown otherwise | same |
budget = 0.6 × available at start (0.8 for Fast), at most 0.8 × total
fixed = web 300 MB + the enabled sidecars (SIDECAR_MB) + one face service (FACE_COSTS)
(available counts what LibrePhotos' own running workers and sidecars hold, so it does not shrink as they run; a worker that stopped, idle or parked, counts nothing)
N_cpu = Gentle 1 · Balanced clamp(cores // 2, 1, 4) · Fast clamp(cores - 1, 1, 8)
N_ram = floor((budget - fixed) / lane_ram) lane_ram: 600 MB light, 750 MB heavy (CPU)
N_vram = floor((vram_free - 512 MB) / vram_per_lane) only with a GPU provider
W = max(1, min(N_cpu, N_ram, N_vram, WORKER_CONCURRENCY if set))
heavy_width = max(1, min(W, N_ram_heavy, N_vram))
On SQLite W is capped at 4: one writer, more lanes only wait for it. N never drops below 1; when even
one lane does not fit the admin sees a warning and LibrePhotos runs slowly instead of not at all.
The setting. PARALLEL_WORKERS (site setting): gentle, balanced (default), fast. Fast first
import switches itself back to Balanced once the queue has been empty for 10 minutes after a completed
library scan. WORKER_CONCURRENCY stays a hard override (also of N_max). N_max is W of Fast at
start, so switching up needs no restart unless the machine got bigger. The supervisor runs a process only for the slots below the current width: a worker whose slot falls
outside it exits once it is idle (EXIT_PARKED, 5, its WorkerProcess row turns inactive) and is started
again when the width grows, so a narrower width gives its memory back. A spawned worker (Windows, macOS,
standalone) has its own copy of Django (about 110 MB idle); a forked one on Linux about 30 MB of its own.
Where it shows. The site settings in the Admin area: what was detected ("4 cores, 8 GB (container limit), no GPU"), the three intentions with the resulting workers and memory budget each, and a warning when the choice does not fit ("4 workers need about 3 GB, this container has 2 GB; 2 will run"). Not released yet (comes after 1.7.0) The first-time setup no longer asks: a new installation starts with Balanced. The admin's server stats show the running width, the budget in use and the recycles.
Scan Faces in parallel
scan_faces lists the photos once (as today), then queues scan_faces_chunk(job_id, photo_ids) tasks of
64 photos in the heavy queue, as one group whose follow-up is finish_face_scan(job_id). Each chunk
counts its photos with an item key, so a redelivered chunk counts nothing twice. With one worker the
chunks run in listing order, which is today's order. The follow-up runs once, after the last chunk,
whatever happened to the others: when the job was cancelled it does nothing; otherwise it completes the
job and queues Generate Face Embeddings, then Find Similar Faces, as a stopping chain with the dedupe keys
above. The 20-in-a-row "face service unreachable" counter moves into the job's result, so it spans chunks.
This does not touch the clustering itself. @metamountain's fixes on faces-large-libraries (batched
pk__in for SQLite's 32,766-variable limit, counting a person once per photo) are independent of it.
Face services, one per heavy lane
New in 1.7.0 The face sidecar serves one request at a time, so N heavy lanes on one face
sidecar mostly queue. api/runtime/replicas.py (no Django) and api/runtime/sidecar_scaler.py give it
replicas; the mechanism is generic (REPLICA_KINDS), only face_recognition opts in.
- Ports. Replica
ilistens onSIDECAR_PORT_FACE_RECOGNITION + 100 × i(iup to 7). The process ismain.py --replica i(service face_recognition --replica iin the standalone build),/healthanswers itsreplicaand, once a model is loaded, itsdevice(cpu,webgpu,cuda). A port that answers as another program, or as another replica, is FOREIGN for that replica alone. Replica 0 is the sidecar as before:start_servicestarts it and the minute watchdog keeps it. - Owner. The
run_workerssupervisor of each host runs the scaler every 5 s in a thread of its own (one run at a time). It starts replicas 1.. while the heavy queue has queued or running tasks, at mostmin(plan, heavy width, open heavy tasks), waits until each answers as itself, and writes the live ports and the device to<tempdir>/librephotos-sidecars/<service>-<port>.json. A replica no longer wanted leaves that list at once and stops when it is idle (no request for 120 s, or 120 s after it was dropped; at once when the plan no longer allows it or memory is low, but never while busy). Exiting rather than unloading frees WebGPU memory and glibc's heap. On shutdown (signal or stop file) the supervisor stops them after the workers; a replica left from a killed supervisor is adopted by the next one. Start, stop and restart of a replica happen under aSidecarWatchLeasekeyed by host, service and replica. - Routing.
api.runtime.sidecars.post/getread the live list (cached for 1 s, ignored when older than 2 minutes, so a dead supervisor falls back to replica 0). A worker starts at replicaslot % live(set_laneinworker_entry), the web process atpid % live; it takes a non-blocking file lock per port (port-<port>.lock,msvcrt.locking/flock) and moves on to the next free replica, so a request never waits behind another lane's while one is free. With none free it goes to its own replica and queues there. A refused connection fails over to the next replica at once (no connect retries) and skips that one for 10 s; an error answer or a read timeout is raised as before. The drawn-box calls inviews/faces.pygo through the same client. - Plan.
plan_workers(..., load=Load(...))replacesFIXED_MB. After the workers and heavy lanes:
spare = room - W × 600 MB - heavy × 150 MB
replicas = clamp(min(heavy,
1 + spare // face_mb,
vram_budget // face_vram_mb (GPU, VRAM known),
2 (GPU, VRAM known: one GPU's queue),
1 (GPU, VRAM unknown),
FACE_SIDECAR_REPLICAS if set), 1, 8)
vram_budget = 0.8 × (nvidia-smi free + what our face services hold)
FACE_COSTS is a table per model and device (CPU vs GPU), measured (peak memory plus headroom) on
Windows and Linux (glibc) for the CPU and WebGPU on Windows. The device comes from the replicas'
/health; before any model is loaded it is unknown (GPU costs, one replica) unless ONNX_PROVIDERS
starts with the CPU or the WebGPU plugin is missing. FACE_SIDECAR_REPLICAS only lowers the result;
a higher value is logged and capped.
- At runtime. When memory is low (
low_on_memory), the scaler takes one replica away per round, down to 1, before the sizer has to pause workers. A replica abovemax(2 × cost, cost + 500 MB)is restarted; replica 0 only when idle. On the CPU, replicas 1.. start withONNX_INTRA_OP_THREADS = min(cores, physical cores) // replicasunless the variable is set; replica 0 keeps ONNX Runtime's default. - Shown in
GET /api/parallel-workers/: per planface_replicas,face_replica_mb,face_vram_mb,face_device,face_limited_by,vram_budget_mb;face_services(running, live, device, RSS, GPU memory) andface_override.
Upgrade from django-q2
- Schedules (no pickles:
funcis a dotted path,argsa Python literal) are copied intoapi_taskscheduleby a migration that readsdjango_q_schedulewith raw SQL when the table exists, keepsnext_run, maps the functions moved in 1.5.0 (#2335, what 0157 and 0158 did), and deletes what it copied. It runs before thestart_*commands, which then find their schedules and create nothing twice. - Queued tasks are signed pickles, so they are read at runtime, not in a migration: on start and every
minute while
django_q_ormqhas rows, the supervisor takes the rows whose lock has expired (a task an old cluster still holds during a rolling deploy is left to it until its lease ends), checks each signature withSECRET_KEYand the cluster name, unpickles it with the tolerant unpickler frombroker.py, encodes function, arguments and the remaining chain as a new task, and deletes the old row in the same transaction. A payload that cannot be read is dropped with a warning, and its job, if it has one that has not started, is failed with "queued before the upgrade; start it again". So nothing runs twice, and nothing is lost silently. Not released yet (comes after 1.7.0) The device date of a waiting upload, aCaptureTimein the pickle, is carried over as its local time and offset. An upgrade to 1.7.0 dropped such an upload, and its photo stayed unprocessed. - django-q2 leaves
INSTALLED_APPSand the requirements; its tables stay one release so the step above can read them, and a migration in the release after drops them (DROP TABLE IF EXISTS).
Tests
- Unit: payload codec round trip and refusal; claim order and caps; lease renewal and expiry; attempts;
chain stop and
continue_on_error; group barrier with failed and cancelled members; dedupe while queued and running; cancel without payloads; scheduler types,catch_up=False, two schedulers; release guard; throttle; capacity against fake cgroup v1/v2 trees, a Job Object stub and a fakenvidia-smi; the formula as a table. - Multi-process, on SQLite and PostgreSQL: 4 processes claim 1,000 tasks with a lease longer than the test may last, every task runs once (a failure lists the runs of each task that ran twice: worker, attempt, claim, lease and start time); a claim, a renewal and a vouched lease that wait for another connection's lock still get a whole lease; a worker killed mid-task, lease expiry, exactly one rerun; a supervisor restart while tasks run.
- Upgrade: a database with pickled
django_q_ormqtasks (withUserarguments, a chain, a moved function, a bad signature) anddjango_q_schedulerows is converted, nothing runs twice. The upgrade rehearsal does the same with a database that 1.6.0 itself made, on PostgreSQL and SQLite, and runsmanage.py run_workerson it. - Throughput and memory: a real scan of a demo library (and Scan Faces on a copy of a 100k-photo SQLite database) on django-q2 and on the new queue, one and four workers: photos per hour and peak RSS.
- CI runs the suite on SQLite; a job with a
postgresservice container runs the queue tests and the tests of the migrations since the last release on PostgreSQL.
Phases
| # | Pull request | Depends on |
|---|---|---|
| 0 | This design | |
| 1 | api/runtime/capacity.py; the admin server stats show the container's memory and cores. No behaviour change | |
| 2 | Queue core: tables, payload codec, claim, worker, supervisor, scheduler, throttle, tests (multi-process on both databases). Not wired in yet | 0 |
| 3 | Switch-over: the seam on the new queue, run_workers in every entry point, the upgrade step and migration; django-q2, broker.py, rate_limit.py and the Nuitka includes removed | 2 |
| 4 | Scan Faces chunks, group barrier, unique follow-ups, stopping chains | 3 |
| 5 | PARALLEL_WORKERS, width from capacity at runtime, heavy cap, memory watchdog | 1, 3 |
| 6 | First-time setup step, settings and admin UI, docs (Docker mem_limit, Raspberry Pi, ARM64, NAS) | 5 |
| 7 | Face services, one per heavy lane: replicas, routing, per-component budget with VRAM | 5, 6 |
Later, each with its own design: replicas for tags, OCR and captions (opt in through REPLICA_KINDS
and a cost table); hard limits
from the operating system (oom_score_adj +500 for workers and sidecars so the
kernel picks them before the web server, a per-sidecar Job Object memory limit in the standalone build);
fair sharing of lanes between users on multi-user servers (claim from the user served least recently);
one pass instead of three over a new photo (#3071, request B).