---
agent:
  instructions: "Use this search API to find relevant content across this site with keywords or natural-language queries, instead of crawling individual pages. Results are returned in Markdown."
  endpoint: "https://framesfield.com/.well-known/search?q={query}"
  method: "GET"
  documentation: "https://developers.cloudflare.com/ai-search/how-to/search-for-agents/"
title: "Fix fal.ai 504 Queue Timeouts & Expired LoRA .safetensors URLs in ComfyUI"
description: "Never call fal.run synchronously for jobs taking >20 seconds: POST to https://queue.fal.run/<endpoint>, save request_id immediately, poll status_url every 5–10 seconds until COMPLETED, fetch response_url, and download diffusers_lora_file (.safetensors) immediately into permanent cloud storage or ComfyUI/models/loras/."
canonical: "https://framesfield.com/fixes/fal-queue-timeout-and-lora-safetensors-comfyui-load-fix"
---

# Fix fal.ai 504 Queue Timeouts & Expired LoRA .safetensors URLs in ComfyUI

> Never call fal.run synchronously for jobs taking >20 seconds: POST to https://queue.fal.run/<endpoint>, save request_id immediately, poll status_url every 5–10 seconds until COMPLETED, fetch response_url, and download diffusers_lora_file (.safetensors) immediately into permanent cloud storage or ComfyUI/models/loras/.

- **Canonical URL:** https://framesfield.com/fixes/fal-queue-timeout-and-lora-safetensors-comfyui-load-fix
- **Category:** API & Batch Pipelines
- **Error Signature:** `API error: HTTP 504 Gateway Timeout / curl exit 28 on fal.run during FLUX LoRA training or Wan VACE 14B runs, OR HTTP 403/404 when loading an old .safetensors URL later`
- **Last Verified:** 2026-12-01

## Observed Symptom

You POST a 1,000-step FLUX LoRA training run ($2.00) or a 5-second Wan VACE 14B / Kling O1 V2V edit directly to https://fal.run/..., your script hangs for 60 seconds and throws a 504 timeout—even though the job kept running and billed your account. Or weeks later, a saved diffusers_lora_file URL fails to load.

## Technical Root Cause

Two architectural mistakes cause both failures: (1) https://fal.run is a synchronous gateway intended strictly for fast 2-to-15-second calls, whereas FLUX LoRA training (2–4 min) and video-to-video edits (60–180s) require asynchronous submission to https://queue.fal.run with status polling; and (2) relying on transient hosted delivery links as long-term storage instead of archiving diffusers_lora_file (.safetensors) locally or into your own object bucket.

## Under the Hood

When you hit https://fal.run/fal-ai/flux-lora-fast-training synchronously, the load balancer keeps an HTTP connection open waiting for 1,000 optimization steps to finish. Proxies, corporate NAT gateways, Python requests defaults, and edge functions routinely drop idle HTTP sockets at 60 to 120 seconds—returning a 504 error to your client while the GPU worker continues burning your $2.00 run unseen, leaving you without the final response JSON containing your trained .safetensors URL.

Submitting to https://queue.fal.run/fal-ai/<model-id> returns immediately in <300 milliseconds with a durable request_id, status_url, and response_url. Your script persists request_id to disk first (preventing duplicate double-billing on retry), polls status_url every 5–10 seconds until status == "COMPLETED", fetches response_url once, and downloads diffusers_lora_file (.safetensors) straight into permanent storage or ComfyUI/models/loras/.

For local ComfyUI users, a second subtle snag appears after downloading the file: placing the .safetensors file into ComfyUI/models/checkpoints/ instead of ComfyUI/models/loras/, or pairing a FLUX LoRA with an SDXL base checkpoint, throws tensor-key mismatch errors at render time. FLUX LoRAs must always live in ComfyUI/models/loras/ and load through LoraLoaderModelOnly or LoraLoader wired strictly to a FLUX base diffusion model.

## Before vs. After

### Broken (Broken Sync Call (Hangs Until 504 Timeout & Loses $2.00 Trained LoRA URL))

```
# WRONG: synchronous fal.run drops connection before 3-min LoRA train finishes
curl -X POST "https://fal.run/fal-ai/flux-lora-fast-training" \
  -H "Authorization: Key $FAL_KEY" \
  -H "Content-Type: application/json" \
  -d '{"images_data_url":"...","trigger_word":"ff_brand_v1","steps":1000}'
# -> HTTP 504 Gateway Timeout after 60s; $2.00 billed, response JSON lost!
```

### Verified Fix (Fixed Async Queue Pattern (queue.fal.run + Poll + Immediate Local Archive))

```
# RIGHT: submit async to queue.fal.run -> returns request_id in <300ms
SUBMIT=$(curl -sS -X POST "https://queue.fal.run/fal-ai/flux-lora-fast-training" \
  -H "Authorization: Key $FAL_KEY" -H "Content-Type: application/json" \
  -d '{"images_data_url":"...","trigger_word":"ff_brand_v1","steps":1000,"is_style":false}')
STATUS_URL=$(echo "$SUBMIT" | jq -r '.status_url')
RESP_URL=$(echo "$SUBMIT" | jq -r '.response_url')
# Poll STATUS_URL until status == COMPLETED -> fetch RESP_URL -> download .safetensors immediately!
```

Using queue.fal.run decouples HTTP socket lifetimes from multi-minute GPU jobs, eliminates blind double-billing retries, and guarantees you capture and archive the portable .safetensors file.

## Copy-Paste Fix (fal-queue-run.sh)

```bash
#!/usr/bin/env bash
set -euo pipefail
# Safe async runner for long fal.ai jobs (FLUX LoRA training, Wan VACE 14B, Kling O1 V2V, SAM 2)
# Usage: FAL_KEY=... ./fal-queue-run.sh fal-ai/flux-lora-fast-training payload.json result.json

ENDPOINT="${1:?Pass fal model path, e.g. fal-ai/flux-lora-fast-training}"
PAYLOAD_FILE="${2:?Pass JSON payload file}"
OUT_JSON="${3:-fal_result.json}"

SUBMIT=$(curl -sS -X POST "https://queue.fal.run/${ENDPOINT}"   -H "Authorization: Key ${FAL_KEY:?Set FAL_KEY}"   -H "Content-Type: application/json"   --data-binary "@${PAYLOAD_FILE}")

REQ_ID=$(echo "${SUBMIT}" | jq -r '.request_id // empty')
STATUS_URL=$(echo "${SUBMIT}" | jq -r '.status_url // empty')
RESP_URL=$(echo "${SUBMIT}" | jq -r '.response_url // empty')

if [ -z "${REQ_ID}" ]; then
  echo "Queue submit failed: ${SUBMIT}" >&2
  exit 1
fi
echo "Queued request_id=${REQ_ID} (saved cleanly—safe from 504 timeouts)"

while true; do
  POLL=$(curl -sS -H "Authorization: Key ${FAL_KEY}" "${STATUS_URL}")
  STATE=$(echo "${POLL}" | jq -r '.status // "UNKNOWN"')
  echo "[$(date +%H:%M:%S)] status=${STATE}"
  if [ "${STATE}" = "COMPLETED" ]; then break; fi
  if [ "${STATE}" = "FAILED" ] || [ "${STATE}" = "CANCELED" ]; then
    echo "Job failed: ${POLL}" >&2
    exit 1
  fi
  sleep 8
done

curl -sS -H "Authorization: Key ${FAL_KEY}" "${RESP_URL}" > "${OUT_JSON}"
echo "Saved full response -> ${OUT_JSON}"

# Auto-archive LoRA .safetensors or output video if present
LORA_URL=$(jq -r '.diffusers_lora_file.url // empty' "${OUT_JSON}")
if [ -n "${LORA_URL}" ]; then
  curl -fsSL "${LORA_URL}" -o "${REQ_ID}.safetensors"
  echo "Archived portable LoRA -> ${REQ_ID}.safetensors (copy into ComfyUI/models/loras/)"
fi
VID_URL=$(jq -r '.video.url // empty' "${OUT_JSON}")
if [ -n "${VID_URL}" ]; then
  curl -fsSL "${VID_URL}" -o "${REQ_ID}.mp4"
  echo "Archived output video -> ${REQ_ID}.mp4"
fi
```

## Step-by-Step Resolution

1. **Swap fal.run to queue.fal.run for every job over 20 seconds:** Use https://queue.fal.run/<endpoint> on all FLUX LoRA training, Wan VACE 14B, Kling O1 V2V, and SAM 2 video jobs so client connections never hang.
2. **Log request_id immediately before polling:** Save request_id and response_url to disk or your job database right after submission so even a laptop sleep or CI restart can resume fetching the completed output without paying twice.
3. **Download and archive .safetensors and output MP4s immediately:** Copy diffusers_lora_file into permanent S3/R2 storage and/or your local ComfyUI/models/loras/ directory as soon as status reaches COMPLETED.
4. **Match LoRA architecture strictly in ComfyUI:** Load FLUX LoRAs exclusively through LoraLoaderModelOnly (strength 0.75–0.90) attached to a FLUX diffusion model—never inside models/checkpoints/ or onto an SDXL/SD1.5 pipeline.

## Verification Check (Confirm Local .safetensors Integrity & ComfyUI Folder Placement)

```bash
# Check downloaded LoRA file is a valid binary safetensors weight (>15 MB, not an HTML error page):
ls -lh *.safetensors && file *.safetensors
# Correct ComfyUI destination (NEVER models/checkpoints/):
# cp <req_id>.safetensors ~/ComfyUI/models/loras/ff_brand_v1.safetensors
```

**Expected healthy output:**

```text
Binary safetensors file typically 18–170 MB (never a 2 KB HTML/JSON error stub), visible inside ComfyUI LoraLoaderModelOnly after pressing R to refresh.
```

## Prevention Guardrails

1. **Use webhook callbacks (fal_webhook query param) in production backends:** In serverless web apps (Vercel, Cloudflare Workers), pass ?fal_webhook=https://your-app/api/fal-done on queue.fal.run instead of holding a polling loop inside an edge function.
2. **Never rely on third-party temporary CDN URLs for permanent brand assets:** Mirror trained .safetensors files into your own versioned R2/S3 bucket (e.g. brand-loras/v1/ff_brand_v1.safetensors) and pass that durable URL to fal-ai/flux-lora.
3. **Verify file size before loading into ComfyUI:** An expired signed URL downloaded via curl without -f saves a 300-byte XML error file with a .safetensors extension—always pass curl -fsSL so HTTP errors fail loudly.

## FAQs

### If my synchronous fal.run request timed out with 504, did I lose my $2.00 trained LoRA?

No—log into your fal.ai dashboard Request History immediately. Completed jobs retain their output JSON and diffusers_lora_file URL there so you can still download the .safetensors weight file without paying to train a second time.

### Why does ComfyUI throw "key not found" or ignore my downloaded fal.ai FLUX LoRA?

Make sure the file sits in ComfyUI/models/loras/ (not models/checkpoints/), press R in the ComfyUI browser window to refresh node dropdowns, wire it through LoraLoaderModelOnly connected to a FLUX model (not SDXL), and include your exact trigger_word inside the prompt.

### How often should my script poll status_url on queue.fal.run?

Polling every 5 to 10 seconds is clean and respectful for 60-to-240-second LoRA training and video editing jobs. For production web apps, attach a fal_webhook callback URL so fal.ai pushes the completed payload to your backend with zero polling.
