AI video API worker leases: Prevent stale worker writes

Nov 8, 2026·9 min read

Your video worker pauses after sending a generation request. Another worker takes over, then the original process resumes and saves an outdated status. AI video API worker leases address this ownership race by giving each worker a temporary, application-owned right to update a job. They do not prove that a paid generation failed, and they do not authorize another paid submission.

For a GenRelay integration, keep generation requests in the provider-facing layer and ownership rules in your local scheduler. This guide builds a deterministic lease model, tests stale-worker rejection, and explains where database enforcement must replace the demonstration.

How do worker leases prevent conflicting job updates?

A worker lease prevents conflicting updates when every authoritative write checks current ownership, lease validity, and an increasing ownership version.

A lease is a time-limited ownership record stored by your application. A fencing token is an increasing number issued whenever ownership is acquired; it distinguishes an earlier worker attempt from the current one. Expiry is the instant at which the lease stops granting write authority, even if no replacement worker has arrived.

Store the job identifier, owner identifier, lease deadline, fencing token, workflow state, and provider job identifier together or behind a consistent transactional boundary. Worker identifiers should identify process instances, not reusable hostnames. Tokens must survive restarts and must not reset when a job is archived and restored.

Ownership and generation progress are separate facts. A job can remain externally running while its local lease expires repeatedly. The GenRelay video API belongs to the generation layer; leases described here belong to your scheduler, not to an assumed provider API feature.

What should happen when a worker lease expires?

Expiry should permit another worker to acquire local ownership and inspect existing evidence, not automatically submit another generation.

The dangerous interval is between an external service accepting a request and your application durably saving its identifier. A timeout during that interval means the outcome is unknown. Neither a dead process nor an expired lease establishes that the service rejected the request.

Use a recovery sequence that preserves this distinction:

  1. Atomically acquire an expired or unowned job and increment its token.
  2. Read the persisted submission record and any known provider job identifier.
  3. If an identifier exists, recover that existing job using documented provider capabilities.
  4. If submission may have occurred but no identifier exists, preserve an uncertain state for reconciliation.
  5. Submit again only after a separate retry policy establishes that doing so is safe, using documented idempotency support when available.

Idempotency means repeated requests representing the same operation do not create additional operations within a documented scope. Do not assume every model or endpoint supports it. Persist submission intent before making the call, but recognize that this record alone cannot make the database and external service act as one transaction. See AI video API job recovery for the broader recovery path.

How can you test lease expiry without timing-dependent failures?

Use a trusted logical clock and explicit time advancement so ownership boundaries are reproducible without sleeps.

A logical clock is a controlled counter rather than wall-clock time. In this example, the test harness is its trusted authority; worker methods cannot supply their own timestamps. The code uses Python's standard library and performs no network requests. It is a single-process demonstration, NOT production concurrency control: method bodies stand in for atomic storage operations, but contain no database transaction or cross-process synchronization.

from dataclasses import dataclass

class LogicalClock:
    def __init__(self):
        self.now = 0

    def advance(self, ticks):
        if ticks < 0:
            raise ValueError("clock cannot move backward")
        self.now += ticks

@dataclass
class Job:
    owner: str = ""
    token: int = 0
    deadline: int = 0
    state: str = "pending"
    provider_id: str = ""

class LeaseStore:
    def __init__(self, clock):
        self.clock = clock
        self.job = Job()

    def claim(self, owner, ttl):
        if not owner or ttl <= 0:
            raise ValueError("owner and positive ttl required")
        j = self.job
        if j.state == "complete" or j.deadline > self.clock.now:
            return None
        j.owner, j.token = owner, j.token + 1
        j.deadline = self.clock.now + ttl
        return j.token

    def valid(self, owner, token):
        j = self.job
        return (j.owner == owner and j.token == token
                and j.deadline > self.clock.now
                and j.state != "complete")

    def renew(self, owner, token, ttl):
        if ttl <= 0:
            raise ValueError("positive ttl required")
        if not self.valid(owner, token):
            return False
        self.job.deadline = self.clock.now + ttl
        return True

    def write(self, owner, token, expected, new_state):
        if not self.valid(owner, token) or self.job.state != expected:
            return False
        self.job.state = new_state
        return True

clock = LogicalClock()
store = LeaseStore(clock)
a = store.claim("worker-a", 5)
assert a == 1
assert store.claim("worker-b", 5) is None
clock.advance(5)
assert not store.renew("worker-a", a, 5)
assert not store.write("worker-a", a, "pending", "running")
b = store.claim("worker-b", 5)
assert b == 2
assert not store.write("worker-a", a, "pending", "running")
assert store.write("worker-b", b, "pending", "running")
assert not store.write("worker-b", b, "pending", "complete")
assert store.renew("worker-b", b, 5)
print("lease boundary tests passed")

The boundary is deliberate: a deadline equal to the current time is expired. Renewal never resurrects an expired token. The expected-state condition also rejects an out-of-order transition from the current owner. This simplified store accepts caller-selected transitions; production code should additionally enforce an explicit allowed-transition policy.

How do atomic database claims and conditional writes work?

Production claims must test eligibility and change ownership in one atomic database operation, while subsequent writes must enforce the same ownership conditions.

An atomic claim either commits the eligibility check, owner assignment, token increment, and deadline update together or changes nothing. A conditional write updates a row only when its stored values satisfy required predicates. Avoid reading an expired row and then issuing an unconditional update: two workers can both observe the same expired lease.

Implement claims with a database-supported conditional update returning the new token, or a properly isolated transaction with row locking. Treat zero affected rows as a failed claim. Use a trusted database time source with clearly defined evaluation semantics; do not compare deadlines against worker laptop clocks. Check how the database handles statement time, transaction time, and lock waits so a long wait cannot admit an already expired owner.

For renewal and state changes, require matching job identity, owner, token, an unexpired deadline, and the expected workflow state. A token check without expiry allows an abandoned owner to write before anyone takes over. An expiry check without a token can mistake a replacement owner's valid lease for the old worker's authority.

Protect related records too. Artifact pointers, billing annotations, and completion events must not be updated through an unfenced side path. Commit the authoritative state and an outbox record together when downstream delivery is needed. An outbox is a durable event record dispatched after the database transaction commits; consumers still need duplicate handling.

Why can a fenced worker still trigger an external call?

A fence can reject stale database writes, but it cannot cancel an external request or make a remote service enforce your local token.

Run this second snippet after the first in the same interpreter, or concatenate both blocks into one file. The external list is a simulated service, not a GenRelay endpoint. A counter represents paid submission attempts; none are actually sent.

clock2 = LogicalClock()
store2 = LeaseStore(clock2)
old = store2.claim("old-worker", 3)
assert store2.write("old-worker", old, "pending", "submitting")

# Simulated external acceptance before a local pause.
external_jobs = ["simulated-job-1"]
paid_submission_attempts = 1
clock2.advance(3)
current = store2.claim("new-worker", 6)
assert current == 2
assert store2.write("new-worker", current, "submitting", "uncertain")

# The remote effect survives expiry, but the old write is rejected.
assert external_jobs == ["simulated-job-1"]
assert not store2.write("old-worker", old, "uncertain", "complete")
assert store2.job.state == "uncertain"
assert store2.job.provider_id == ""

# Recovery preserves uncertainty instead of issuing another paid request.
assert paid_submission_attempts == 1
assert store2.write("new-worker", current, "uncertain", "reconciling")
assert not store2.write("old-worker", old, "reconciling", "complete")
print("external effect and stale-write tests passed")

Even checking ownership immediately before a network call leaves a gap: the process can pause after the check and resume after expiry. Local fencing cannot close that gap. Documented provider idempotency, durable submission records, and conservative handling of uncertainty address different parts of this risk; leases alone do not provide exactly-once generation.

If the old worker eventually receives a response, it must not overwrite the current job row. It may preserve evidence through a separately designed append-only channel, where records cannot assert authoritative completion. The current owner can validate that evidence against request identity and apply result reconciliation under its own fence.

What should developers know before deploying worker leases?

Deploy leases with explicit failure tests and monitoring, rather than treating a successful heartbeat as proof that the full workflow is safe.

How long should a video worker lease last?

Choose a duration based on scheduler pauses, database latency, and your recovery objective, not the expected video duration. Renew during long processing, leave operational margin, and stop authoritative writes when renewal fails. Test pauses longer than the entire lease.

Can two workers briefly process the same job?

Yes. An expired worker may still execute while its replacement runs. Fencing prevents its protected writes from succeeding; it does not prevent CPU work or remote activity. Track rejected writes and overlapping attempts to expose this behavior.

Does lease expiry mean a paid video request should be retried?

No. Expiry indicates lost local ownership, not external failure. Recover the existing provider job when known; otherwise investigate submission uncertainty before authorizing another paid request. Keep local recovery attempts separate from paid submission attempts in logs and metrics.

Are these Python examples suitable for production storage?

No. They demonstrate deterministic invariants without concurrent access, persistence, or real API behavior. Before deployment, test competing database claimants, restart durability, delayed renewal, stale completion, and response loss after acceptance against your actual storage and documented provider integration.

Related posts

Join our DiscordAI video API worker leases: Prevent stale worker writes — GenRelay