Introducing a new way to review your PRs.

Read the announcement

capsoftware / cap

Open source Loom alternative. Beautiful, shareable screen recordings.

View on GitHub

31 documents · Updated Nov 23, 2026

docs / render-farm-service-and-workers

Render-farm service and workers

The render farm turns a Studio export into parallel video and audio work for a fleet of GPU workers. The TypeScript service plans and tracks the export. A Rust runtime renders and encodes each assigned piece. The service also builds the final MP4, publishes early HLS playback, and resumes work after a process or worker failure. See Render-farm processing for the wider system view.

System boundary

The service has a coordinator role and a worker role. The RF_ROLE setting selects the role. The coordinator owns export state and work assignment. Workers execute assigned work. The Rust runtime sits below the worker boundary and does not own scheduling or final-file assembly.

Coordinator role

The coordinator is the control point for an export. It accepts requests, probes the project, creates video and audio work, assigns that work, accepts one result for each required piece, and reports job state. It can also run local audio lanes when coordinator CPU capacity is available.

References: apps/…/coordinator.ts• L83-155 apps/…/coordinator.ts• L2747-3253

Worker role

Each worker provides video slots and CPU audio lanes. A slot keeps a warm Rust engine so later tasks do not pay the full startup cost. The worker fetches task inputs, runs the task, uploads media, and reports progress while it works. Transcode work uses a slot-local media process when a source needs preparation before ordinary rendering.

References: apps/…/worker.ts• L31-100 apps/…/worker.ts• L856-972

Runtime boundary

The Rust runtime uses one JSON request per input line and one JSON response per output line. It supports project probing plus video, audio, warm-up, and health operations. Progress and GOP events let the worker detect stalls and publish HLS before a task ends.

References: crates/…/main.rs• L27-75 crates/…/main.rs• L116-179 apps/…/engine.ts• L60-129

Process startup

Bootstrapping starts the selected service role and prepares the worker's engine slots. The service image packages the TypeScript service with the Rust runtime and the media and GPU libraries needed to run it. It configures the worker for required GPU use and launches the boot layer. A worker warms its GPU engines before the first task. The boot process also forwards termination signals so a worker can stop taking work and drain active tasks.

References: apps/…/boot.ts• L101-114 apps/…/worker.ts• L82-100 apps/…/worker.ts• L834-855 apps/…/Dockerfile• L3-53 apps/…/Dockerfile.dockerignore• L1-9

Export lifecycle

An export moves from a durable request receipt to a plan. It then moves through parallel media work, MP4 assembly, output checks, and a final summary. The coordinator keeps video and audio work separate while they share one output timeline.

The diagram shows how a request crosses the TypeScript service, workers, Rust runtime, and object storage.

flowchart LR
    Request[Export request] --> Receipt[Durable request receipt]
    Receipt --> Index[Index sources and project]
    Index --> Plan[Plan video chunks and audio sections]
    Plan --> Queue[Shared work queue]
    Queue --> Worker[Worker slots or local audio lanes]
    Worker --> Materialize[Materialize task inputs]
    Materialize --> Runtime[Rust runtime or transcode process]
    Runtime --> Result[Video and audio results]
    Result --> Coordinator[Coordinator acceptance]
    Coordinator --> HLS[Progressive HLS playlist]
    Coordinator --> MP4[MP4 header and media assembly]
    MP4 --> Verify[Playable-output check]
    Verify --> Summary[Ready or failed summary]

Request acceptance

POST /jobs validates the request and checks the requested output key before it starts planning. The coordinator writes a request receipt first. This makes an accepted request recoverable even if the process stops during planning. The receipt can point to product media while the farm keeps its journal in a separate bucket.

References: apps/…/coordinator.ts• L3136-3187 apps/…/validate.ts• L3-116 apps/…/s3.ts• L44-59

Planning stage

Planning indexes the recording manifest and source MP4s before it probes the prepared project. The Rust project loader prepares the project timeline in the same form used by a single-machine export. It supplies frame count, output size, source spans, and audio cut points. Source spans include every clip touched by a frame range, including both sides of a transition. Audio cuts mark changes in timeline mapping so an audio section can restart without changing the result.

The planner sizes chunks by expected render work and aligns boundaries to usable video units. When HLS is enabled, a short lead-in chunk reduces time to the first playable segment.

Audio is split into packet-aligned sections. The planner prefers clip boundaries because audio processing can restart there with less risk of a seam. Each later section carries pre-roll so stateful audio processing can reach the correct state.

References: apps/…/coordinator.ts• L728-1001 apps/…/planning.ts• L19-99 apps/…/coordinator.ts• L1041-1096 crates/…/project.rs• L22-95 crates/…/project.rs• L146-177

Parallel media work

The coordinator places video chunks and audio sections on one shared queue. A worker materializes the files named by its task and asks the runtime to render them. Video results contain encoded sample data and layout information. Audio results contain AAC packets on the shared packet grid.

References: apps/…/coordinator.ts• L1003-1096 apps/…/worker.ts• L491-619 apps/…/worker.ts• L621-710

Output assembly

The coordinator waits until every video chunk and audio section has an accepted result. It combines sample sizes, keyframes, track runs, and codec data into the MP4 header. Workers have already placed the media payload in the multipart upload, so assembly does not copy the full video again.

The service can verify the completed object before it reports readiness. It can also run that check in the background so the output becomes available sooner while the job still records the verification result.

References: apps/…/coordinator.ts• L2306-2434 apps/…/mp4.ts• L636-799 apps/…/coordinator.ts• L2602-2639

Job protocol

The job protocol describes work and results at the service boundary. It does not expose worker engine state as the contract. Each work item names the media range, the output or result identity, and the data needed for safe acceptance.

Video tasks

A video task names a frame range and the source byte ranges needed for that range. It also names the multipart upload range for that dispatch. The result reports encoded sample sizes, keyframes, codec data, track runs, and uploaded parts. The coordinator uses these values both to build the MP4 index and to check that the result belongs to the active dispatch.

References: apps/…/protocol.ts• L15-53 apps/…/coordinator.ts• L2172-2249

Audio tasks

An audio task names a section and its pre-roll. The worker returns packet sizes, codec data, and AAC bytes. The coordinator stores the result before it makes those packets available to video workers or MP4 assembly.

References: apps/…/protocol.ts• L55-67 apps/…/coordinator.ts• L2253-2300 apps/…/worker.ts• L621-710 crates/…/project.rs• L146-177

Transcode tasks

A transcode task prepares a source that cannot support reliable random access. The target key identifies the reusable output. The coordinator shares one task for a target across jobs. A worker probes the source first. If it is already H.264 with suitable pixel format, frame order, and keyframe spacing, the worker remuxes it. Otherwise, it creates a seekable H.264 MP4 with regular keyframes. Both paths enforce the source-size and decode limits used for untrusted recordings.

Completion is accepted only from the active worker attempt. The coordinator also checks that the stored object exists and has the reported size. This prevents a stale report or partial output from unblocking planning.

References: apps/…/protocol.ts• L69-83 apps/…/transcode.ts• L1-159 apps/…/coordinator.ts• L1551-1645 apps/…/worker.ts• L714-800

Media materialization

Media materialization means creating the local project files that a task can read. Workers do not download every source file in full for every video chunk. The cache creates files with the expected size and fetches only the byte ranges that the task needs.

Source ranges

The Rust project model groups source-time spans by clip for each output frame range. It includes both sources during a transition and joins repeated uses of the same clip. The coordinator widens these spans to include decoder start points and clip timing before it selects the source bytes for a task. Project metadata and audio inputs use broader ranges because their processing needs a complete or differently indexed view.

References: apps/…/coordinator.ts• L755-776 apps/…/coordinator.ts• L884-927 apps/…/materialize.ts• L55-81 crates/…/project.rs• L91-135

Local cache

The cache shares fetched pieces between tasks from the same job. It limits concurrent range requests and removes job data after the job ends. It rejects unsafe paths before it creates local files, so a manifest cannot write outside its job directory. Closing the cache stops new fetches and prevents an in-flight fetch from writing after its files are closed. A failed piece can be fetched again while the cache remains open.

References: apps/…/materialize.ts• L35-50 apps/…/materialize.ts• L69-89 apps/…/materialize.ts• L91-128 apps/…/materialize.ts• L130-183 apps/…/worker.ts• L101-127

Transcoding

Transcoding creates a seekable H.264 MP4 for a source that lacks a useful index or enough keyframes. The output key is the shared identity. An existing valid object is reused, and concurrent jobs wait for the same work instead of starting duplicate encodes.

Source preparation

The coordinator checks the target before it queues a transcode. It reuses a stored target when one exists. Otherwise it checks the source size and dispatches the work to a video-capable slot before ordinary chunks that depend on it.

The worker probes the source before choosing the least costly safe path. A compatible H.264 source is copied into an indexed MP4. Other supported sources are decoded and encoded with regular keyframes so the planner can seek near chunk boundaries. The encoder can use the worker's configured GPU path or a CPU path. Source dimensions and pixel allocation stay within the farm's limits.

References: apps/…/coordinator.ts• L1574-1634 apps/…/coordinator.ts• L1722-1741 apps/…/coordinator.ts• L2934-2955 apps/…/worker.ts• L714-800 apps/…/transcode.ts• L1-159

Transcode recovery

Transcode progress is part of worker liveness. The worker reports progress while it probes and encodes. If the worker or the process stops reporting, the coordinator requeues the task with backoff. A worker can cancel a stalled probe or encoder. The coordinator accepts the final report only after it checks the target object.

References: apps/…/coordinator.ts• L1675-1720 apps/…/worker.ts• L138-142 apps/…/worker.ts• L714-800 apps/…/worker.ts• L1040-1050 apps/…/coordinator.test.ts• L918-1007

Scheduling

Scheduling balances early playback with fair progress across active exports. The coordinator chooses each job's next unfinished work first. It then considers running-task count, request age, and timeline position so one long export does not block newer jobs.

Queue dispatch

Workers use long-poll requests to ask for work and state which task kinds their slots can accept. Transcodes take priority when they block planning. A video slot can reserve its next ordinary task near the end of the current task so source fetching overlaps the final render and upload work.

References: apps/…/scheduler.ts• L28-85 apps/…/coordinator.ts• L1459-1482 apps/…/worker.ts• L856-895

Straggler handling

When queued work is empty, the coordinator can start a second copy of a video chunk that is frozen or projected to finish much later than a fresh copy. The first valid result wins. The duplicate has its own upload range, and the losing worker receives a cancellation request.

References: apps/…/coordinator.ts• L1784-1863 apps/…/coordinator.ts• L1866-1883 apps/…/coordinator.test.ts• L796-815

Storage and output

Object storage holds source media, final media, HLS objects, job journals, and temporary chunk stashes. The media bucket may belong to the product. The farm bucket holds coordinator state and can hold the temporary data needed to assemble small output pieces.

Multipart media layout

Workers upload encoded payload directly into reserved parts of the final MP4 multipart upload. Each chunk also stores its opening bytes as a stash. The coordinator joins the MP4 header with small stashes and copies a standalone stash server side when storage permits. This avoids padding short chunks and avoids moving all media through the coordinator.

The part layout leaves separate ranges for the first attempt, retries, and a hedge. A chunk result is usable only when its stash, parts, sizes, and part range match the active dispatch.

References: apps/…/stitch.ts• L3-13 apps/…/stitch.ts• L33-127 apps/…/worker.ts• L393-487 apps/…/coordinator.ts• L2436-2567

Progressive HLS output

Workers publish short fragmented MP4 segments as complete GOPs become available. The coordinator exposes only the contiguous segment prefix in an event playlist. This lets playback start while later chunks are still rendering. A failed playlist write keeps the cursor dirty and retries it.

References: apps/…/worker.ts• L204-329 apps/…/coordinator.ts• L1974-2055 apps/…/coordinator.ts• L2234-2246

Storage access and callbacks

The service signs storage requests and can use either configured keys or temporary EC2 instance-role credentials. With instance-role credentials, it refreshes them before expiry and shares one bounded refresh across callers. Invalid or expired credentials do not replace the last valid set. The client retries transient storage failures before it reports an error. It can use separate media and journal buckets. When the media bucket has another owner, new objects use the bucket-owner access rule. Job reads return fresh signed URLs. An allowed callback receives the final job result with an HMAC over the exact JSON body.

References: apps/…/s3.ts• L26-59 apps/…/s3.ts• L78-174 apps/…/s3.ts• L311-371 apps/…/coordinator.ts• L2064-2129 apps/…/coordinator.ts• L3190-3212

Validation

Validation limits the work accepted by the coordinator and protects shared object storage. It checks request shape, source scope, path form, manifest size, source bytes, export length, output keys, and callback hosts before work can spread to the fleet.

Request and source scope

Manifest paths must stay relative. Manifest keys must stay inside the recording scope or an explicitly allowed shared prefix. Cached source indexes are checked again against the current request scope. This prevents a valid cache entry from granting one job access to another recording.

References: apps/…/coordinator.ts• L575-607 apps/…/coordinator.ts• L609-681 apps/…/coordinator.test.ts• L1149-1179

Render and output checks

The runtime checks task ranges and result coverage. The coordinator checks that video runs cover all frames, audio runs cover all packets, and all chunks agree on codec data. The final object is checked for expected size, duration, frame count, and playable MP4 structure. Transcode probing also rejects recordings whose dimensions exceed the supported pixel or side limits.

References: apps/…/coordinator.ts• L2313-2391 apps/…/coordinator.ts• L2602-2639 apps/…/transcode.ts• L3-7 apps/…/transcode.ts• L83-94 crates/…/video.rs• L189-264 crates/…/video.rs• L347-400

Recovery and shutdown

Recovery treats durable journal records and accepted upload parts as facts. The coordinator can rebuild a job after restart, reuse its multipart upload, and requeue only work whose result is missing. Worker heartbeats let it distinguish work that may still be running from work that must be retried.

Durable job state

The coordinator journals the request receipt, plan, dispatch reservations, accepted video and audio results, assembly intent, and terminal state. A receipt-only job replays planning. A planned job restores its task attempts and upload ranges. The current journal format is versioned. An incompatible journal is not resumed against a new upload layout.

References: apps/…/coordinator.ts• L1098-1166 apps/…/coordinator.ts• L1217-1448 apps/…/README.md• L36-47 apps/…/README.md• L61-65

Retry boundaries

Failed tasks retry with backoff and attempt identity. Each video chunk has six disjoint upload ranges. The coordinator never wraps around to an old range. Once the range budget is exhausted, the export fails rather than risking a live part collision. Accepted results are persisted before the coordinator uses them for assembly or acknowledges dependent work.

References: apps/…/recovery.ts• L4-29 apps/…/coordinator.ts• L1485-1520 apps/…/coordinator.ts• L2172-2289 apps/…/coordinator.ts• L3020-3057

Worker liveness

Workers heartbeat every few seconds and list tasks in every phase. The coordinator requeues work from a quiet worker or work that a live worker stops listing. It can reattach a task that was still running when the coordinator restarted. Watchdogs kill stalled video engines and stalled transcode processes so the coordinator can recover the task.

References: apps/…/worker.ts• L1040-1096 apps/…/coordinator.ts• L2810-2901 apps/…/coordinator.ts• L1919-1956

Shutdown behavior

Shutdown stops new polls and lets active tasks finish until the drain deadline. A dead engine is replaced. Repeated GPU-path degradation causes the worker process to restart so the boot layer can create a clean runtime.

References: apps/…/worker.ts• L891-955 apps/…/worker.ts• L832-855 apps/…/boot.ts• L101-114

Change checklist

When these files or sections are changed, remember to consider these:

  • Changes to apps/…/protocol.ts must stay aligned with coordinator result acceptance and the Rust request and response messages.
  • Changes to chunk count, part layout, or stash rules must preserve S3 part limits and all six retry and hedge ranges.
  • Changes to apps/…/stitch.ts must preserve final-plan stability for parts written ahead of assembly.
  • Changes to audio section boundaries must preserve the shared packet grid used by planning, worker fetches, HLS muxing, and MP4 assembly.
  • Changes to HLS segment cuts must keep worker object keys, coordinator cursor state, and restart reconstruction consistent.
  • Changes to journal records must preserve version checks and durable reservations before dispatch.
  • Changes to source or output paths must keep request validation, bucket ownership, conditional writes, and signed URL contracts aligned.
  • Changes to transcode completion must preserve target-key sharing, active-attempt checks, stored-size checks, and source-index reuse.
  • Changes to transcode probing or encoder selection must preserve the source pixel limits, remux safety checks, regular keyframes, and seekable output contract.
  • Changes to S3 credential or bucket selection must preserve separate media and journal access, refresh temporary credentials before signing, and keep owner access for cross-account media writes.
  • Changes to project-cache shutdown must preserve the barrier that prevents queued or in-flight range fetches from writing after local files close.
  • Changes to project timeline loading must keep frame counts, source spans, transition coverage, and audio cut points consistent with the single-machine export and the TypeScript planner.
  • Changes to the service image or build context must keep the Rust runtime, TypeScript boot entry point, media libraries, GPU libraries, and required source inputs available together.

Important failure modes

TriggerConsequenceGuard
A worker stops heartbeating or stops listing a taskIts task is requeued and another worker can run itWorker heartbeats and coordinator liveness checks
A retry reuses an old multipart rangeA late upload can overwrite a live attemptSix disjoint ranges per chunk and an exhausted-range failure
A short chunk is padded to satisfy the S3 part minimumThe final MP4 contains bytes that are not mediaStashes and coordinator stitching without padding
Two copies finish the same chunkA late copy can replace the accepted resultDurable first acceptance and stale-result checks
A coordinator stops during planning or assemblyIn-memory job state is lostRequest, plan, result, and assembly journal records
A source has no usable seek pointsA chunk cannot start at its planned timeProbe-based remux check and shared seekable transcode output
A source exceeds the supported pixel or side limitThe transcode task fails before unsafe decoding or encodingSource-size validation and a decode pixel limit on every media process
A transcode report names a stale worker or sizePlanning can unblock on the wrong outputActive-attempt and stored-size checks
A transcode probe or encoder stops producing progressThe worker slot can remain blocked indefinitelyProgress tracking and a watchdog that kills the child process
The render path falls back to software when GPU mode is requiredThe export can become much slowerGPU-path validation and engine replacement
HLS storage fails after a segment uploadPlayback does not list a segment that existsDirty playlist cursor and retry
Media and journal buckets use mismatched access rulesWorkers cannot read media or recovery cannot read stateSeparate S3 configuration and bucket-owner access control
Instance metadata returns invalid, expired, or failed credentialsStorage requests keep using the old credentials or fail without sending an untrusted setIMDS response validation and bounded refresh sharing
A project cache closes while range work is pendingA late fetch can fail the task or write through a closed local fileClosed-state checks before and after storage reads
Project timeline mapping changes without matching source or audio boundariesA chunk can miss transition media or restart audio with the wrong stateShared project loading, source-span discovery, and audio-cut discovery
The service image lacks a GPU library or runtime manifestThe worker cannot start the GPU path and may fall back to softwareGPU runtime image setup and required-GPU configuration

Key files

FileWhy to read it
apps/…/README.mdProduct flow, reliability guarantees, deployment boundary, and operating limits
apps/render-farm/DockerfileService image boundary, Rust runtime packaging, and GPU runtime setup
apps/render-farm/Dockerfile.dockerignoreBuild-context boundary for the service image
apps/…/coordinator.tsRequest handling, planning, dispatch, result acceptance, HLS, assembly, callbacks, and recovery
apps/…/worker.tsEngine slots, materialization, rendering, audio, HLS upload, transcode work, heartbeats, and drain behavior
apps/…/transcode.tsSource probing, remux eligibility, safe re-encode choices, and media size limits
apps/…/transcode.test.tsExecutable contracts for remux safety, encoder paths, progress parsing, and source limits
apps/…/protocol.tsContract for video, audio, transcode, result, and job messages
apps/…/planning.tsChunk boundaries, lead-in behavior, and multipart range capacity
apps/…/materialize.tsRange fetches and local project cache behavior
apps/…/materialize.test.tsProject-cache close, retry, and overlapping-range contracts
apps/…/stitch.tsStash layout, no-padding multipart assembly, and assembly concurrency limits
apps/…/mp4.tsSource indexing and final MP4 header and track layout
apps/…/recovery.tsAttempt ranges and idempotent multipart completion
apps/…/s3.tsSigned storage access, bucket separation, multipart operations, and credential refresh
apps/…/s3-imds.test.tsInstance-role credential refresh and failure contracts
apps/…/validate.tsRequest, manifest, path, source-size, and callback boundaries
apps/…/scheduler.tsFairness and playback-first task selection
apps/…/coordinator.test.tsExecutable contracts for recovery, transcode reuse, source scope, HLS, callbacks, assembly, and storage races
apps/…/stitch.test.tsContracts for stash grouping, valid S3 parts, ahead-of-assembly work, and concurrency limits
apps/…/planning.test.tsPlanner guarantees for chunk waves, lead-in chunks, and retry range capacity
apps/…/recovery.test.tsMultipart recovery guarantees for lost responses, races, and durable assembly intent
apps/…/worker.test.tsWorker guarantees for transcode cancellation, engine setup, and stash upload failure
apps/…/s3.test.tsStorage signing, key escaping, and server-side copy contracts
crates/…/main.rsRust runtime protocol and operation boundary
crates/…/project.rsProject loading, timeline normalization, frame timing, source spans, and audio cut discovery
crates/…/video.rsVideo render, encode, progress, and GPU-path contract
crates/…/audio.rsAudio sections, pre-roll, packet grid, and AAC result contract