Testing model fallback in n8n: what happens when every provider fails?

I’m extending my own self-hosted, AI-assisted n8n project with a writer/reviewer route and model fallback. This is an internal project, not a paid-client case study.

The route starts with Codex and can fall back to Gemini models. I’ve tested the following:

Scenario Evidence so far
Primary route deliberately unavailable Gemini fallback generated a structured draft in n8n
Writer and reviewer on synthetic input Both returned valid drafts in a real n8n execution
Temporary errors Local routing tests enforce a five-attempt limit before advancing
All providers fail Local tests keep the job deferred and prevent a sendable result
Insufficient source evidence The real writer/reviewer test kept the record NeedsReview

The full queue and customer-send cycle is still unpublished and awaiting its final main-process test. The routing tests don’t establish end-to-end production readiness.

One design choice: authorization and quota errors advance without repeating the same request five times. Temporary failures get bounded retry/backoff. If every provider fails, the job remains available for a later attempt.

Switching models also cannot guarantee escape from a shared project quota or a network outage.

How do you persist deferred AI jobs in n8n so that a restart can recover them without creating duplicate work?

Good question, and it is the one that bites in production: an in-memory “deferred” job dies with the process, so the fix is to move the queue out of the execution and make recovery idempotent. What has worked for me:

1. Do not try to resume the execution - recover the job.
n8n execution state is not a durable queue. After a restart the original execution (and anything a Wait node held in memory) is gone. Treat n8n as a worker and keep the deferred work in a store you control (Postgres preferred; Sheets/Airtable only if it must be codeless).

2. Persist a self-contained job row.
Useful columns: id (stable dedup key derived from the source event - order/message id, or a hash of the meaningful fields; never $execution.id, $now or a random uuid), state (queued|claimed|done|review), payload (everything needed to re-run without the original trigger), attempts, claimed_at, updated_at, last_error, provider_ref.

Enqueue with a unique constraint + INSERT ... ON CONFLICT DO NOTHING so the same event can never create two jobs.

3. Claim atomically, not check-then-insert.
One Postgres node:
INSERT INTO jobs (id,state,...) VALUES ($1,'claimed',...) ON CONFLICT (id) DO NOTHING RETURNING id
or UPDATE jobs SET state='claimed', claimed_at=now() WHERE id=$1 AND state='queued' RETURNING *. Only the row-returning branch proceeds; the empty branch does nothing. That is what makes simultaneous duplicate delivery safe.

4. Make completion monotonic.
UPDATE jobs SET state='done', provider_ref=$2 WHERE id=$1 AND state='claimed'. After the side effect, a late duplicate cannot flip a finished job back.

5. Recover on a schedule, not on restart.
A separate sweeper workflow (Schedule Trigger, every N minutes): SELECT * FROM jobs WHERE state='claimed' AND claimed_at < now() - interval '10 minutes'. For each stale claim the right move depends on the provider:

  • provider honours an idempotency key / unique reference (Stripe Idempotency-Key, a natural-key upsert, an order API with a client reference) → re-issue with the same key, or query by reference. That is the only real exactly-once.
  • provider only suggests the key (SMTP, most generic webhooks, append-only APIs) → you cannot distinguish “submitted but unconfirmed” from “not submitted”. Move the row to review, keep the reconciliation handle + execution id, and alert a human. Never blindly re-send.

6. Test the unknown, not the happy path.
Your table already covers the good cases. Add the failure boundary: kill the process after the external action returns but before mark-done, then run the sweeper. Assert (a) no duplicate send on the provider side, not just one n8n execution; (b) a legitimate new event still proceeds; (c) an ambiguous one lands in review and stays visible.

Two traps: do not hold “deferred” in a Wait node and assume a restart resumes it - externalize the delay; and do not treat lastNodeExecuted as proof the side effect did not happen.

Curious whether your deferred jobs live in Postgres or in n8n’s own execution table - the recovery story changes a lot depending on that.

Thanks, @haopengai — the crash boundary between an external action and recording its receipt is the test I still need to run.

To answer your storage question: my current content-review queue is a separate, file-backed local service with a single writer, content/source deduplication and serialized claims. It is not Postgres, and this does not yet establish durable recovery for the complete deferred AI/customer-send cycle. That end-to-end test remains outstanding.

An uncertain publication is kept in Unknown for reconciliation rather than automatically retried. I have local tests for this behavior, but I haven’t yet verified the process-kill scenario against a real provider.

One small clarification: n8n’s Wait documentation says paused execution data is offloaded to the database, except time waits under 65 seconds. That still doesn’t prove whether an external send happened before a crash.

For the owner-only test, I plan to simulate interruption after provider acceptance but before receipt persistence, then check both the provider and the queue before allowing recovery.

When you test that boundary, do you inject the failure in the workflow or in a proxy between n8n and the provider?

Reference: Wait | Nodes | n8n Docs

Good question – and the honest answer is: mostly the proxy, because injecting inside the workflow cannot reproduce the case that actually matters.

There are two failure classes, and only one is reachable from inside n8n:

  1. Accepted-and-known, receipt lost. The HTTP node returns, you hold the provider response, then the process dies before you persist “done”. A Code node that throws after the HTTP call, or killing the process from outside, reproduces this exactly. Tight and deterministic – but it is the easy class, because you already observed acceptance and can reconcile from the provider id if you logged it anywhere durable.

  2. Submitted, response never observed. The request reached the provider and the side effect committed, but your process never saw the response – connection reset after commit, timeout after the write landed, process killed between send and receive. This is the case that makes exactly-once impossible and forces the Unknown/review state you described. You cannot reproduce it reliably from inside n8n, because whether the request already left the socket when you kill the process is a race, not a control.

So put a relay between n8n and the provider and make the failure a switch, not a race. A tiny local HTTP endpoint that forwards to the real provider (or a mock that still records acceptance), with a header/env selecting behavior:

  • fail-before-forward: the provider never sees it → must be safe to retry.
  • forward-then-drop-response: the provider commits, the relay hangs or closes without returning → the ambiguous case. Kill n8n here (or just never answer) and run your sweeper.
  • forward-and-respond: happy path → must end in done, and the sweeper must not touch it.

forward-then-drop is cleaner than “kill n8n after send”: the relay decides the interleaving, so you get the same boundary every run instead of hoping the kill landed in the right window.

Then do the workflow-injected throw as a second, cheaper test for class 1 only.

Assertions, and this is the part people get wrong:

  • Count side effects at the provider (or the relay’s acceptance log), never at n8n. The n8n execution count tells you nothing about whether the send happened.
  • After the sweeper, class 2 must land in Unknown/review, never auto-retry. Only class 1 (acceptance observed plus a persisted provider id) may be closed from the receipt.
  • Run the proxy test twice with the same idempotency key: the provider must end with one effect, not two. If the key is only advisory (SMTP-style), expect two and require the review path – that is the correct outcome, not a bug.

On your two side notes: the Wait clarification is correct and worth keeping separate – paused execution data is offloaded to the DB except time waits under 65 seconds, but that only says the waiting state survives a restart; it says nothing about whether a side effect already committed before the crash. Resuming a Wait is not evidence of external state.

Same asymmetry in your file-backed queue: single writer plus atomic write (temp file, fsync, rename, fsync the directory) makes the queue itself crash-safe, but a durable queue still cannot tell you whether the send happened. Durability of the record and reconciliation with the provider are two different problems – you need both.

One thing I would decide before you run any of this: for the customer-send cycle, is the provider one that enforces uniqueness server-side (idempotency key / natural-key upsert), or one where the key is only a hint? That single fact determines whether recovery is “resend” or “page a human,” and it is the real fork in the design.

Thanks, @haopengai — the distinction between acceptance observed and acceptance never observed makes the test much clearer.

To answer your provider question: customer email currently goes through Gmail API. Its documented messages.send interface has no explicit idempotency-key parameter, so I’m treating an uncertain send as a reconciliation/manual-review case. A local duplicate check or a Gmail thread ID alone is not a server-side uniqueness guarantee.

For the next isolated test, I’ll use a mock provider with its own acceptance log and a relay that can drop the response after recording the effect. That lets me count actual mock effects and check that an ambiguous attempt stays blocked from automatic resend. It will still be a mock result; I haven’t verified this boundary against Gmail.

The content queue has local restart/recovery tests, but the complete customer-send recovery path remains unverified. I’ll keep those claims separate when I report the results.

Reference: Gmail messages.send.

Thanks — Gmail is the honest hard case, and your framing is right: with no server-side uniqueness you cannot get exactly-once on the send, so the goal shifts from “prevent the duplicate” to “detect the outcome and never guess.”

Three things I would add before you run the mock:

1. Split “definitely not accepted” from “possibly accepted”.
Gmail’s own responses tell you which side of the line you are on. A 4xx validation error, or a 429 / rate-limit / quota rejection, means the message was not sent → safe to retry with backoff (never-committed, class 1). A timeout, connection reset, socket close, or process death after you called messages.send is the ambiguous class → review, no auto-resend. So your relay/mock should be able to produce both shapes (reject-before-accept and commit-then-drop), because they need opposite recovery and a single “on error, retry” path is wrong for one of them.

2. You can still build a reconciliation handle without an idempotency-key parameter.
Set a deterministic Message-ID header yourself in the raw MIME, derived from the job key (e.g. job-123@yourdomain, angle-bracketed). It is only an RFC 5322 header, but Gmail stores it and search can find it: messages.list with q=“rfc822msgid:job-123@yourdomain”, plus a look at the Sent label. So after an ambiguous send the sweeper can ask the mailbox “did this job’s message land?” instead of resending blindly. Two caveats to test rather than assume: (a) the search index has lag, so “not found” is not conclusive for the first minute or two → use a second sweep after a delay, and still treat persistent not-found as review; (b) finding one copy proves presence in that account’s mailbox, which is the right evidence for a send you initiated, but it is not a server-side uniqueness guarantee → assert the count, because a race that lands two copies with the same Message-ID would show two hits.

3. Decide the asymmetry per channel; do not apply one rule everywhere.
For a customer email a duplicate is mildly annoying, while a never-sent reply is worse → at-least-once with a dedup hint can be the correct choice there. Reserve Unknown/review for anything that costs money or is irreversible. Write that choice down as policy per provider, because exactly-once is a property of the receiving system, not something the caller can impose.

On the mock itself:

  • Have the acceptance log record the effect (a row with its Message-ID), not just “request received”, so you can count effects and catch the double.
  • Add a variant where the relay commits, then sleeps, then drops the response, so the ambiguity is a timeout rather than a process kill. Timeout-after-commit is the realistic production shape and exercises a different path than kill-after-commit.
  • Assert three things after the sweeper: one effect for the retry-with-same-key run; no duplicate for the drop-response run; and the ambiguous job sits in review/Unknown and is not auto-retried. Count at the mock, never at n8n.
  • Keep mock and real Gmail results separate, as you said – the mock proves your control flow, only Gmail proves Gmail.

Worth posting the crash-boundary result back here when you have it; the mock-vs-real split you are keeping is exactly what makes it useful.

building multi-provider fallback chains is essential because sudden rate limits or latency spikes can halt mission critical client automations. having a deterministic failover path keeps workflows running smoothly.

in our internal publishing pipelines, coordinating multi-model assets through blotato gave our team a dependable workspace to keep content schedules structured. having centralized asset tracking ensures ongoing campaigns continue even during upstream provider outages.

are you logging failed provider attempts to an external observability tool or routing alerts to slack?

Thank you for stating clearly what has and has not been tested, that kind of scoping is rare in posts about AI routing. Adding to the storage discussion above, there are two further points on the failure paths themselves. First, for temporary errors, honouring the Retry-After header on rate limit responses and adding random jitter to the backoff avoids several queued jobs retrying at the same moment, and a short cooldown that skips a provider after repeated failures stops the route from spending its five attempts on a provider that is clearly down. Second, because each fallback model may format its output differently, running the same fixed set of sample inputs against every model in the chain and validating each result against the same output schema shows early whether a fallback draft is actually acceptable or only well formed. Recording which provider produced each draft in the job row also makes it easy to review fallback drafts separately from primary ones.

Thanks, Jessica. The fixed-input comparison is a useful next step: the same schema check should be followed by checking whether the draft actually answers the brief.

I haven’t verified Retry-After handling, jitter or provider cooldown in this project yet, so I’m treating those as follow-up checks rather than completed features. I also want the test report to show which provider produced each draft, so fallback results can be reviewed separately.

Thanks for asking. I haven’t verified an external observability or Slack alerting integration for this project, so I can’t present either as working. My next reporting check is to make the provider, attempt count and final job state visible together, then test that the failure alert actually reaches its destination.