Replicate API Timeout? Fix Prediction Failures & Webhook Errors
Replicate predictions are asynchronous — the synchronous wait= parameter caps at 60 seconds, but image and video models typically take 2–10 minutes. Here is how to switch to async polling, handle webhooks, and debug canceled vs failed status errors.
Understanding Replicate's async model
Every Replicate prediction goes through the same lifecycle: starting → processing → succeeded / failed / canceled. The API is async-first — POST /predictions returns immediately with an ID and status starting, not the output. The wait= parameter is a convenience shortcut that blocks up to N seconds (max 60) — if the model isn't done, the response returns with status canceled and you must poll or use a webhook.
1. Switch from wait= to async polling
If you use replicate.run() inside a serverless function or short-lived process, it will time out. Replace it with explicit create-then-poll:
# BAD: replicate.run() blocks and times out on long models
output = replicate.run("stability-ai/sdxl:...", input={"prompt": "cat"})
# GOOD: create prediction, then poll
import replicate, time
prediction = replicate.predictions.create(
version="stability-ai/sdxl:39ed52f2319f9...",
input={"prompt": "a photorealistic cat on a rooftop, golden hour"}
)
print(f"Prediction ID: {prediction.id} — status: {prediction.status}")
# Poll every 2 seconds until done
while prediction.status not in ("succeeded", "failed", "canceled"):
time.sleep(2)
prediction.reload()
print(f"Status: {prediction.status}")
if prediction.status == "succeeded":
print(prediction.output)
elif prediction.status == "failed":
print(f"Error: {prediction.error}")
else:
print("Prediction was canceled (timeout or manual cancel)") - Billing is per second of compute — a canceled prediction still charges for compute time used before cancellation.
- Poll at 2–5 second intervals — Replicate rate-limits aggressive polling; 2 seconds is the practical minimum.
2. Use webhooks for predictions over 60 seconds
For image and video models that take 2–10 minutes, polling is wasteful. Pass a webhook URL and Replicate will POST the completed prediction object to your endpoint:
import replicate
prediction = replicate.predictions.create(
version="anotherjesse/zeroscope-v2-xl:9f747673...",
input={
"prompt": "a drone shot of a mountain at sunrise",
"num_frames": 24,
"fps": 8,
},
webhook="https://yourapp.com/webhooks/replicate",
webhook_events_filter=["completed"] # only fire on final status
)
print(f"Prediction {prediction.id} queued — webhook will fire when done") // Next.js webhook handler — pages/api/webhooks/replicate.ts
import type { NextApiRequest, NextApiResponse } from "next";
import crypto from "crypto";
export default function handler(req: NextApiRequest, res: NextApiResponse) {
// Verify the webhook signature
const secret = process.env.REPLICATE_WEBHOOK_SECRET!;
const sig = req.headers["webhook-secret"] as string;
const body = JSON.stringify(req.body);
const expected = crypto.createHmac("sha256", secret).update(body).digest("hex");
if (sig !== expected) return res.status(401).end("Invalid signature");
const prediction = req.body;
if (prediction.status === "succeeded") {
console.log("Output URLs:", prediction.output);
// Save to DB, notify user, etc.
} else if (prediction.status === "failed") {
console.error("Prediction failed:", prediction.error);
}
res.status(200).end("ok");
} - Webhook URL must be publicly accessible —
localhostwon't work; use ngrok or a deployed endpoint during development. webhook_events_filter=["completed"]— without this, you receive events for every status change (starting, processing, completed).- Replicate retries failed deliveries — your endpoint must return 2xx within 5 seconds or Replicate will retry.
3. Debug input validation errors (status: "failed")
When prediction.status == "failed", always check prediction.error. Common causes:
| Error message | Fix |
|---|---|
Failed to load image from URL | URL must be publicly accessible and return the correct Content-Type header (image/png, image/jpeg) |
Input validation failed | Check parameter ranges in the model's schema — e.g. guidance_scale must be > 0, num_inference_steps < 500 |
CUDA out of memory | Reduce image resolution or batch size; some community models have hard limits |
Model version not found | Model version was deleted by its owner; find the current version hash on the model's Replicate page |
# Always log the full error field
prediction = replicate.predictions.get(prediction_id)
if prediction.status == "failed":
print(f"Failed: {prediction.error}")
# e.g. "Failed to load image from URL: 403 Forbidden"
# e.g. "guidance_scale must be between 1 and 20" 4. Cold boot on community models
Community models (everything not under the official replicate/ namespace) are only kept warm if they have recent traffic. A cold start adds 30–120 seconds before inference begins. Your prediction shows status starting for longer than expected.
- Use official models —
stability-ai/sdxl,meta/llama-2-70bare kept warm 24/7. - Create a deployment —
replicate.deployments.predictions.create()targets your private deployment with min instances set to 1, eliminating cold boot. Costs a flat per-minute idle fee. - Warm-up ping — run a cheap prediction (1 step, tiny resolution) at startup to boot the model before real requests arrive.
# Target a private deployment for warm instances
prediction = replicate.deployments.predictions.create(
deployment_owner="your-username",
deployment_name="sdxl-prod",
input={"prompt": "a cat", "num_inference_steps": 20},
webhook="https://yourapp.com/webhooks/replicate",
) Get an email the next time Replicate goes down
Outage alerts for Replicate, straight to your inbox. No account needed, unsubscribe in every email.
Watching more than one service? A free account covers 5 services + a daily digest — and Pro is currently free.
FAQ
Why does my Replicate prediction time out?
Replicate's synchronous wait= parameter has a hard 60-second limit. Image and video generation models typically take 2–10 minutes. If the model isn't done within the wait window, you get a canceled status. Switch to async polling or webhooks for long-running models.
What is the difference between "canceled" and "failed" status?
canceled means the prediction was stopped — either by the wait= timeout expiring, or by calling DELETE /predictions/{id}/cancel. failed means the model ran but threw an error — check prediction.error for the message.
Why is my Replicate community model slow on first run?
Community models use cold-boot infrastructure. When no one has run the model recently, Replicate downloads weights and starts a container before inference begins — adding 30–120 seconds. Use official models or create a private deployment with minimum 1 instance to avoid cold boot.
What is the difference between replicate.run() and replicate.deployments.predictions.create()?
replicate.run() blocks until done — it polls internally and is fine for short models but times out in serverless environments. replicate.deployments.predictions.create() targets a private deployment with warm instances and no cold boot. For async control on public models, use replicate.predictions.create() and poll or handle webhooks yourself.