AI video API circuit breaker: Stop Failures, Keep Job Recovery
Your submission workers keep timing out, but several video jobs are already rendering. An AI video API circuit breaker should pause new submissions after repeated transport or service failures without abandoning those existing jobs. The difficult part is separating admission control from recovery: a timeout can mean a generation request was accepted even though your worker never received its identifier.
A circuit breaker is an application component that temporarily stops requests to a failing dependency. This article describes a control you implement around your own client, not a claimed GenRelay feature. When integrating the GenRelay video API, verify current request contracts separately; the example below makes no network requests and creates no paid generations.
What should an AI video API circuit breaker protect?
Protect admission of new generation submissions, not every operation associated with video production. Admission control means deciding whether a request may start before sending it to the service.
Use three states:
- Closed: eligible submissions proceed and relevant outcomes update the failure counter.
- Open: new submissions wait or receive an application-level unavailable response.
- Half-open: a limited, safe diagnostic checks whether reopening is justified.
Keep a separate lane for polling, which reads the status of an existing job, and recovery, which reconciles uncertain or interrupted work. Give these lanes their own concurrency limits, timeouts, and retry budgets. An open submission circuit must not discard job identifiers, cancel accepted work, or mark every pending video as failed.
Separate lanes do not mean unrestricted polling during an outage. Use bounded retries with increasing delays and randomized timing, as described in video API polling backoff. If status reads also fail, defer them durably rather than increasing traffic or deleting jobs.
Which failures should open the circuit?
Count repeated dependency transport and service failures within the affected scope; do not interpret tenant-specific mistakes as a shared outage. A tenant is an isolated customer or account using your application.
| Observation | Submission-circuit treatment | Separate action |
|---|---|---|
| Repeated connection failures or relevant service errors | Count within the affected dependency scope | Preserve diagnostic evidence |
| Authentication or permission rejection | Exclude from shared outage counter | Pause the affected credentials and alert their owner |
| Invalid prompt parameters or unsupported input | Exclude from shared outage counter | Return validation feedback |
| Account balance or account quota rejection | Isolate to that account | Request account correction |
| Rate limiting | Apply documented scope and retry guidance | Reduce concurrency; respect Retry-After when supplied |
| Accepted job later fails rendering | Do not automatically count as submission failure | Classify the job failure separately |
A scope might include service, region, model route, and operation, but choose dimensions supported by actual failure isolation. Excessively broad grouping blocks healthy workloads; excessively narrow grouping hides correlated failures. Do not infer a global outage from one account's errors.
The sample uses consecutive relevant failures for clarity. Its threshold and cooldown are illustrative configuration, not measured GenRelay behavior. Production policies may use failure ratios over bounded windows with minimum sample counts. Monitor excluded errors too: exclusion from an outage counter does not make a broken credential harmless.
Why must ambiguous submissions stay outside automatic retries?
Never automatically repeat an ambiguous generation POST simply because its response timed out or the circuit later closed. An ambiguous submission is one whose acceptance you cannot determine from the available evidence.
Before sending, persist a local operation identifier, request fingerprint, and submission status. If a response supplies a job identifier, record it durably before acknowledging the task to your queue. A queue is the durable list of work awaiting processing; its redelivery behavior can otherwise submit the same request twice.
If the connection fails after transmission may have begun, mark the operation as acceptance unknown. Reconcile through documented lookup mechanisms or human investigation. An idempotency key, where explicitly supported, is a service-recognized identifier intended to make repeated requests represent one operation; do not assume its existence, retention period, or behavior.
Circuit reopening authorizes fresh, eligible work. It does not resolve acceptance-unknown records. Follow a separate video API job recovery process, and keep uncertain operations quarantined from automatic submission queues until their status is resolved.
How can you test the state machine without generating videos?
Use a deterministic state machine with explicit timestamps and outcome inputs, then exercise its transitions with assertions. A state machine represents behavior as named states and permitted transitions between them.
This Python example models serialized decisions for one scope. It has no networking, dependencies, credentials, or paid calls. Its epoch is a version number for rejecting stale outcomes after state changes, not a Unix timestamp.
from dataclasses import dataclass
from typing import Optional
import math
@dataclass
class Breaker:
threshold: int = 3
cooldown: float = 10.0
state: str = "closed"
failures: int = 0
epoch: int = 0
until: float = 0.0
last_time: float = float("-inf")
def __post_init__(self):
if self.threshold < 1 or not math.isfinite(self.cooldown) or self.cooldown <= 0:
raise ValueError("invalid policy")
def _time(self, now: float):
if not math.isfinite(now) or now < self.last_time:
raise ValueError("time must be finite and nondecreasing")
self.last_time = now
def _open(self, now: float):
self.state = "open"
self.epoch += 1
self.until = now + self.cooldown
def admit_submission(self, now: float) -> Optional[int]:
self._time(now)
return self.epoch if self.state == "closed" else None
def record_submission(self, token: int, outcome: str, now: float):
self._time(now)
if outcome not in {"success", "dependency_failure", "excluded"}:
raise ValueError("unknown outcome")
if self.state != "closed" or token != self.epoch:
return
if outcome == "excluded":
return
self.failures = self.failures + 1 if outcome == "dependency_failure" else 0
if self.failures >= self.threshold:
self._open(now)
def claim_probe(self, now: float) -> Optional[int]:
self._time(now)
# A missing probe result expires; stale completion cannot close us.
if self.state == "half-open" and now >= self.until:
self._open(now)
return None
if self.state != "open" or now < self.until:
return None
self.state = "half-open"
self.epoch += 1
self.until = now + self.cooldown
return self.epoch
def finish_probe(self, token: int, healthy: bool, now: float):
self._time(now)
if self.state != "half-open" or token != self.epoch:
return
if now >= self.until or not healthy:
self._open(now)
return
self.state = "closed"
self.failures = 0
self.epoch += 1
b = Breaker()
token = b.admit_submission(0.0)
assert token == 0 # Zero is valid: test `is None`, not truthiness.
b.record_submission(token, "excluded", 0.0)
assert b.failures == 0
for now in (1.0, 2.0, 3.0):
b.record_submission(b.admit_submission(now), "dependency_failure", now)
assert b.state == "open"
assert b.claim_probe(12.999) is None
assert b.admit_submission(13.0) is None
probe = b.claim_probe(13.0)
assert probe is not None
assert b.claim_probe(13.0) is None
b.record_submission(token, "success", 13.0)
assert b.state == "half-open"
b.finish_probe(probe, True, 14.0)
assert b.state == "closed"
b.record_submission(token, "dependency_failure", 14.0)
assert b.failures == 0
c = Breaker(threshold=1)
c.record_submission(c.admit_submission(0.0), "dependency_failure", 0.0)
p = c.claim_probe(10.0)
c.finish_probe(p, True, 20.0) # Exact lease expiry is too late.
assert c.state == "open"
p2 = c.claim_probe(30.0)
c.finish_probe(p, True, 30.0)
assert c.state == "half-open"
c.finish_probe(p2, False, 31.0)
assert c.state == "open"
p3 = c.claim_probe(41.0)
assert p3 is not None
assert c.claim_probe(51.0) is None # Lost probe expires.
assert c.state == "open"
try:
c.admit_submission(50.0)
except ValueError:
pass
else:
raise AssertionError("backward time accepted")
print("All circuit breaker assertions passed")
Save the block as breaker_demo.py and run python3 breaker_demo.py. The counter follows completion order, not request-start order. Epoch checks prevent responses from an older circuit generation from resetting a newly opened circuit, but they cannot cancel requests already admitted.
How should half-open checks and distributed state work?
Use a documented, non-mutating health diagnostic and an atomic shared transition when multiple workers participate. A successful paid generation is not an acceptable default health probe.
Do not invent a health endpoint. A diagnostic must provide relevant evidence about the affected submission dependency; a reachable website or unrelated successful status read may prove too little. If no suitable diagnostic exists, require operator review rather than silently spending money to test availability. After approval, restore fresh submissions gradually with a separate concurrency limit.
Atomic means that competing workers cannot partially apply or simultaneously win the same state transition. The Python object does not provide this property across threads, processes, or hosts. Production admission, counter updates, probe claims, and token validation need a transactional shared store or equivalent serialized coordinator. Use expiring probe ownership and fencing tokens: monotonically changing versions that make obsolete owners' writes ineffective.
Use monotonic elapsed time locally, not adjustable wall-clock time. Never persist a process-local monotonic timestamp and compare it after restart or on another host. Distributed leases need one authoritative time basis and a defined clock-skew policy. Specify equality boundaries explicitly: this example permits a probe at the cooldown deadline but rejects its result at the lease deadline. Prevent version reuse after resets so delayed results cannot match a new circuit epoch accidentally.
What do developers frequently ask about circuit breakers?
Keep these operational decisions explicit before enabling the breaker in production.
Does an open circuit stop existing video jobs?
No. It stops your application from admitting new submissions in that scope. Existing jobs retain their identifiers and continue through bounded polling and reconciliation.
Can an authentication failure open the shared circuit?
It should not by default. Isolate the affected account or credentials, and investigate a shared authentication incident separately if broader evidence supports it.
Is a circuit breaker enough to prevent duplicate charges?
No. It limits requests during failures, not duplicate intent. Durable operation records and documented acceptance reconciliation remain necessary, especially when a submission response is missing.
Should queued work resume immediately after a healthy probe?
No. Release fresh work under a concurrency cap, check expiration and cancellation, and leave acceptance-unknown submissions out of that queue. Observe submission outcomes before increasing throughput.