Dynamic workloads: autoscaling Resque workers with Jennifer

Jennifer

A controller that watches a Resque queue, launches workers on Docker™, VirtualBox™, Proxmox™ or VMware™ when the backlog grows, and drains them when it is gone.

November 2026, by @mplx.
Based on Jennifer 0.27.0

Powered by Jennifer's Cantrip - Markdown into slide decks, https://github.com/jennifer-language/cantrip
1 / 24

The problem: bursty load, idle cost

Fixed pool of 5Fixed pool of 1Autoscaled 0 to 5
60 jobs of 1.5 s arrivedone in about 20 sdone in 90 sabout 20 s, after a 1 s start
Quiet hours5 idle workers1 idle workernothing runs
Costthe peak, all daythe average, slow at peaksroughly the work done
2 / 24

The pieces

PieceVersionUsed for
resque.j + redis.j (bundled)0.27.0queue lengths, the worker loop
@deckyard/docker0.2.0containers, by label
@deckyard/virtualbox0.1.0VBoxManage: linked clones, ACPI
@deckyard/proxmox0.2.0API token, clone, start, shutdown
@deckyard/vmware0.3.0vCenter™ REST: clone, guest shutdown
log.j (bundled)0.27.0one logfmt record per decision
jvc add @deckyard/docker      # ... and proxmox, virtualbox, vmware
jvc install                   # copies their src/ into vendor/
3 / 24

Measuring demand

func waitingJobs(db as redis.Session) {
    def total as int init 0;
    for (def q in QUEUES) {   # ["high", "thumbs"]
        $total = $total + resque.queueLength($db, $q);
    }
    return $total;
}
4 / 24

The oldest job's age, by convention

# producer: args[1] is the enqueue time in Unix ms
def stamp as string init convert.toString(time.unixMillis(time.now()));
resque.enqueue($db, $queue, "Thumbnail", ["photo-{$i}.jpg", $stamp]);
# controller: look at the head of the list without popping it
def r as redis.Reply init redis.command($db,
    ["LINDEX", "resque:queue:" + $q, "0"]);
if ($r.kind == "string") {
    def v as json.Value init json.decode($r.str);
    def age as int init (nowMs() -
        convert.toInt(json.asString($v, "/args/1"))) // 1000;
}
4.0 s  scale up waiting=60 oldest=1s have=0 want=5 launch=3
5 / 24

The rule: how many workers?

func desired(waiting as int) {
    def want as int init
        ($waiting + JOBS_PER_WORKER - 1) // JOBS_PER_WORKER;
    return math.min(math.max($want, MIN_WORKERS), MAX_WORKERS);
}
waiting0110113960
desired (10 per worker, 0 to 5)011245
6 / 24

Up fast, down slowly

if ($want > $have) {                  # up at once, a few per tick
    $st.lowSince = 0;
    def n as int init math.min(math.min($want - $have,
        MAX_LAUNCH_PER_TICK), math.min($budget, $room));
    ...
}
if ($want < $have) {                  # down only after a while
    if ($st.lowSince == 0) { $st.lowSince = nowMs(); }
    def low as int init nowMs() - $st.lowSince;
    def calm as int init nowMs() - $st.lastLaunch;
    if ($low >= GRACE_MS and $calm >= COOLDOWN_MS) { ... }
}
7 / 24

The worker drains itself

os.catchSignal("term");
while (true) {
    if (os.gotSignal("term")) { return 0; }   # only between jobs
    def job as resque.Job init
        resque.reserveBlocking($db, QUEUES, POLL);
    if ($job.class == "") {
        $idle = $idle + POLL;
        if ($idle >= IDLE_LIMIT) { return 0; }   # 30 s without work
        continue;
    }
    $idle = 0;
    ...   # perform, or resque.fail; both exits print a last line
}
8 / 24

Never kill a busy worker

BackendDrain requestThe worker sees
DockerkillContainer(c, id, "SIGTERM")SIGTERM, as PID 1
VirtualBoxacpiShutdown(h, vm)systemd stops the service: SIGTERM
Proxmoxshutdown(c, g, 0)ACPI, then the same
VMwareshutdownGuest(c, vm)VMware Tools shutdown, the same
9 / 24

One interface, four backends

export def enum Backend {
    Docker {
        c as docker.Client, image as string, network as string,
        bind as string, env as map of string to string
    },
    Proxmox { c as proxmox.Client, template as int },
    Vbox { h as virtualbox.Host, template as string,
        snapshot as string },
    Vmware { c as vmware.Client, template as string,
        placement as vmware.Placement }
};
export def struct Instance {
    id as string, name as string, state as string };
10 / 24

Dispatch with match

export func drain(b as Backend, inst as Instance) {
    match ($b) {
        when Docker(d) {
            docker.killContainer($d.c, $inst.id, "SIGTERM"); }
        when Proxmox(p) {
            proxmox.shutdown($p.c, pveGuest($p.c, $inst.id), 0); }
        when Vbox(v) { virtualbox.acpiShutdown($v.h, $inst.id); }
        when Vmware(w) { vmware.shutdownGuest($w.c, $inst.id); }
    }
}
11 / 24

Docker: labels find our own containers

def spec as docker.ContainerSpec init docker.containerSpec($d.image);
$spec = docker.withCmd($spec, ["run", "/app/worker.j"]);
$spec = docker.withEnv($spec, $env);   # REDIS_HOST, WORKER_NAME
$spec = docker.withLabels($spec, {POOL_LABEL: $prefix});
$spec = docker.withBind($spec, $d.bind, "/app", true);
$spec = docker.withNetworkMode($spec, $d.network);
docker.startContainer($d.c, docker.createContainer($d.c, $name, $spec));
# listing: the label filter, then the name prefix as well
docker.containers($c, true, ["label=autoscale.pool=" + $prefix]);
academy-scale-w-1   Up 5 seconds    academy-scale-w-
academy-scale-w-manual   Up 10 seconds
12 / 24

VirtualBox: linked clones from a snapshot

def h as virtualbox.Host init virtualbox.open(
    virtualbox.withBinary(virtualbox.local(), os.getEnv("VBOXMANAGE")));
virtualbox.linkedClone($v.h, $v.template, $v.snapshot, $name);
virtualbox.start($v.h, $name);           # headless
virtualbox.acpiShutdown($v.h, $inst.id); # drain
virtualbox.delete($v.h, $inst.id);       # reap
VBoxManage clonevm worker-template --snapshot base --options link
  --name academy-scale-w-1 --register
VBoxManage startvm academy-scale-w-1 --type headless
VBoxManage controlvm 00000000-0000-4000-8000-000000000003 acpipowerbutton
VBoxManage unregistervm 00000000-0000-4000-8000-000000000001 --delete
13 / 24

Proxmox: an API token, a clone task

def c as proxmox.Client init proxmox.withToken(
    proxmox.client(os.getEnv("PVE_URL")),
    os.getEnv("PVE_TOKEN_ID"), os.getEnv("PVE_SECRET"));
def id as int init proxmox.nextId($p.c);
def upid as string init proxmox.linkedClone($p.c,
    proxmox.guest($p.c, $p.template), $id, $name);
def t as proxmox.Task init
    proxmox.waitTask($p.c, $upid, CLONE_TIMEOUT_MS);
if ($t.exitStatus != "OK") { throw Error{kind: "scale", ...}; }
proxmox.start($p.c, proxmox.guest($p.c, $id));
POST /api2/json/nodes/pve1/qemu/9000/clone
GET  /api2/json/nodes/pve1/tasks/UPID:...:qmclone:9000:.../status
POST /api2/json/nodes/pve1/qemu/101/status/start
14 / 24

VMware: boot time and the warm pool

vmware.cloneVm($w.c, $w.template, $name, $w.placement, true);
# WARM=1: reap keeps one stopped clone, scale-up starts it first
if ($k < len($warm) and $k < $st.warm) {
    backend.start($b, $warm[$k]);   # vmware.powerOn
}
 20.2 s  drained name=academy-scale-w-1 took=4082ms
 20.2 s  drained name=academy-scale-w-2 took=4085ms
 20.2 s  removed name=academy-scale-w-2
 28.2 s  scale up waiting=5 oldest=0s have=0 want=1 launch=1
 28.2 s  started name=academy-scale-w-1
15 / 24

Reconciliation after a restart

--- t=12 s: kill -9 controller A
--- t=15 s: controller B starts
  0.0 s  start backend=docker ghcr.io/jennifer-language/jennifer:0.26.0
  0.0 s  adopt name=academy-scale-w-5 state=running
  ...
  0.0 s  adopt name=academy-scale-w-1 state=running
  0.0 s  below waiting=29 have=5 want=3
16 / 24

When the controller stays dead

--- t=6 s: kill -9 controller A
--- t=50 s: docker ps
academy-scale-w-3   Exited (0) 1 second ago
...
--- t=51 s: controller B starts
  0.0 s  adopt name=academy-scale-w-3 state=stopped
  0.1 s  said name=academy-scale-w-3 last="academy-scale-w-3:
         idle 30 s, exit after 10 jobs"
  0.1 s  removed name=academy-scale-w-3
17 / 24

Limits and safety

if (redis.command($db, ["EXISTS", HOLD_KEY]).num == 1) {
    note($st, "hold", {"waiting": convert.toString($waiting)});
    return $st;                         # the kill switch
}
$st.launches = recent($st.launches);    # launches in the last hour
def budget as int init LAUNCHES_PER_HOUR - len($st.launches);
def room as int init MAX_WORKERS - len(lists.filter($all, isUp));
18 / 24

When the backend API fails

Case (from one test run)KindStatus
docker: image missingdocker404
docker: API unreachablenet-
proxmox: no such templateproxmox0 (a local check)
proxmox: no tokenproxmox401
vmware: no such VMvmware404
vmware: session expiredvmware401
virtualbox: no such VMvirtualboxVBOX_E_OBJECT_NOT_FOUND
19 / 24

Retry what is transient, stop on the rest

} catch (e) {
    def status as int init -1;   # -1: no HTTP status at all
    match ($e.kind) {
        when "docker" { def d as docker.DockerError init $e; ... }
        ...   # $status = $d.status; ProxmoxError, VmwareError alike
    }
    if (not transient($e.kind, $status)) { ... return 1; }
    $pause = math.min($pause * 2, MAX_BACKOFF_MS);
}
  6.1 s  retry kind=net status=-1 in=4000ms
 10.1 s  retry kind=net status=-1 in=8000ms
20 / 24

Observability: log every decision

def lg as log.Logger init log.toFile("logfmt", "info", "decisions.log");
log.info($lg, $event, $fields);   # inside note(), next to the console
time=2026-11-19T14:13:57.031Z level=info msg="scale up" waiting=60
  oldest=1s have=0 want=5 launch=3
time=2026-11-19T14:14:13.328Z level=info msg=retry kind=net
  status=-1 in=4000ms
21 / 24

A full run on Docker, part 1

--- t=3 s: burst of 60
  4.0 s  scale up waiting=60 oldest=1s have=0 want=5 launch=3
  4.3 s  launched name=academy-scale-w-1
  4.5 s  launched name=academy-scale-w-2
  4.9 s  launched name=academy-scale-w-3
  6.9 s  scale up waiting=54 oldest=4s have=3 want=5 launch=2
  7.2 s  launched name=academy-scale-w-4
  7.4 s  launched name=academy-scale-w-5
--- t=12 s: kill -9 controller A
--- t=15 s: controller B starts, adopts 5, waiting=29 want=3
--- t=20 s: Docker API proxy stopped, t=27 s: started
22 / 24

A full run on Docker, part 2

 18.2 s  drain name=academy-scale-w-1      (... w-2 to w-5)
 20.3 s  said name=academy-scale-w-5 last="academy-scale-w-5:
         SIGTERM, drained after 11 jobs"
 20.6 s  removed name=academy-scale-w-1
--- t=50 s: burst of 8 on high
 36.7 s  scale up waiting=8 oldest=1s have=0 want=1 launch=1
 49.9 s  below waiting=0 have=1 want=0
 60.1 s  drain name=academy-scale-w-6
 64.2 s  said ... "academy-scale-w-6: SIGTERM, drained after 8 jobs"
 64.2 s  idle, stopping
23 / 24

Checklist

Code: code/ beside this talk. Decks: docker, virtualbox, proxmox, vmware

24 / 24