Mastering RunnableWithFallbacks in LangChain.js
Aug 25,2026

Introduction

So far in this LangChain.js series, we've learned how to build increasingly complex AI workflows.

We've covered:

  • RunnableSequence

  • RunnableParallel

  • RunnableLambda

  • RunnablePassthrough

  • RunnableAssign

  • RunnableBranch

These components help us build powerful AI workflows.

But there is one important problem we haven't handled properly yet:

What happens when an AI workflow fails?

Imagine your application is using OpenAI:

User
 ↓
OpenAI
 ↓
Response

Everything works perfectly.

But suddenly:

  • OpenAI is temporarily unavailable.

  • The API returns an error.

  • The request times out.

  • You hit a rate limit.

  • The model becomes unavailable.

What should your application do?

One option is simply to show an error:

Something went wrong.
Please try again.

But this isn't always the best user experience.

Instead, we could automatically try another model:

User
 ↓
OpenAI
 ↓
❌ Failed
 ↓
Gemini
 ↓
Response

This is called a fallback.

LangChain provides RunnableWithFallbacks to make this pattern easier.

In this article, we'll learn:

  • What RunnableWithFallbacks is

  • Why fallbacks are important

  • How fallbacks work

  • Basic fallback example

  • OpenAI → Gemini fallback

  • Gemini → OpenAI fallback

  • Multiple fallback models

  • Fallbacks with RunnableSequence

  • Fallbacks with RunnableParallel

  • Fallbacks with RunnableBranch

  • Error handling

  • Understanding onError

  • Fallback input

  • Real-world use cases

  • Best practices

  • Common mistakes

Let's get started.


What is RunnableWithFallbacks?

RunnableWithFallbacks allows a Runnable to automatically try one or more alternative Runnables when the primary Runnable fails.

Conceptually:

Primary Runnable
      ↓
   Success?
   /     \
 Yes      No
 ↓         ↓
Output   Fallback
           ↓
        Output

For example:

OpenAI
  ↓
Failed?
  ↓
Gemini
  ↓
Response

The official LangChain.js API provides fallback functionality through withFallbacks(), which returns a Runnable that tries the configured fallback Runnables when the original Runnable fails.


Why Do We Need Fallbacks?

AI applications depend on external services.

That means failures are unavoidable.

For example:

Your Application
      ↓
OpenAI API
      ↓
Internet
      ↓
OpenAI Infrastructure

Any part of this chain can experience problems.

Possible failures include:

  • Network errors

  • Timeout errors

  • API errors

  • Rate limits

  • Service outages

  • Temporary model failures

  • Invalid requests

A production application should have a strategy for handling these failures.

Fallbacks are one strategy.


A Simple Example

Let's say we have:

const primaryChain = ...;
const fallbackChain = ...;

We can create a fallback workflow:

const chainWithFallback =
  primaryChain.withFallbacks({
    fallbacks: [
      fallbackChain,
    ],
  });

Now invoke:

const result =
  await chainWithFallback.invoke(input);

The behavior becomes:

primaryChain
     ↓
Success?
 ┌───┴───┐
Yes      No
 ↓        ↓
Output  fallbackChain

Project Setup

Let's create a project.

mkdir runnable-fallbacks
cd runnable-fallbacks
npm init -y

Install the required packages:

npm install @langchain/core @langchain/openai @langchain/google-genai dotenv

Project Structure

runnable-fallbacks/
│
├── index.js
├── .env
└── package.json

Configure API Keys

Create a .env file:

OPENAI_API_KEY=your_openai_api_key
GOOGLE_API_KEY=your_google_api_key

Add .env to .gitignore:

node_modules/
.env

Never commit API keys to Git.


Import the Models

import "dotenv/config";

import {
  ChatOpenAI,
} from "@langchain/openai";

import {
  ChatGoogleGenerativeAI,
} from "@langchain/google-genai";

Initialize OpenAI

const openAIModel =
  new ChatOpenAI({
    model: "gpt-4.1-mini",
  });

Initialize Gemini

const geminiModel =
  new ChatGoogleGenerativeAI({
    model: "gemini-2.5-flash",
  });

Now we have:

OpenAI
   +
Gemini

and we can use one as the fallback for the other.


Creating an OpenAI → Gemini Fallback

Let's make OpenAI the primary model.

const modelWithFallback =
  openAIModel.withFallbacks({
    fallbacks: [
      geminiModel,
    ],
  });

Now invoke:

const response =
  await modelWithFallback.invoke(
    "Explain Node.js streams."
  );

console.log(response.content);

If OpenAI succeeds:

OpenAI
  ↓
Success
  ↓
OpenAI Response

If OpenAI fails:

OpenAI
  ↓
Failure
  ↓
Gemini
  ↓
Gemini Response

Understanding the Flow

The workflow is:

                  ┌──→ Success → OpenAI Response
                  │
User Request → OpenAI
                  │
                  └──→ Failure
                         ↓
                       Gemini
                         ↓
                       Response

The application doesn't have to manually call Gemini.

The fallback mechanism handles the transition.


Adding StringOutputParser

Usually, we don't want to work directly with AIMessage.

Let's add a parser.

import {
  StringOutputParser,
} from "@langchain/core/output_parsers";

const parser =
  new StringOutputParser();

Now:

const modelWithFallback =
  openAIModel
    .withFallbacks({
      fallbacks: [
        geminiModel,
      ],
    })
    .pipe(parser);

Invoke:

const result =
  await modelWithFallback.invoke(
    "What is Node.js?"
  );

console.log(result);

Now result is a string instead of an AIMessage.


Fallback with PromptTemplate

Let's build a complete chain.

First, create a prompt:

import {
  PromptTemplate,
} from "@langchain/core/prompts";

const prompt =
  PromptTemplate.fromTemplate(`
Explain {topic} in simple words.

Include one practical example.
`);

Create the primary and fallback chains:

const openAIChain =
  prompt.pipe(openAIModel);

const geminiChain =
  prompt.pipe(geminiModel);

Now configure the fallback:

const chain =
  openAIChain.withFallbacks({
    fallbacks: [
      geminiChain,
    ],
  });

Add the parser:

const finalChain =
  chain.pipe(parser);

Invoke:

const result =
  await finalChain.invoke({
    topic: "Node.js streams",
  });

console.log(result);

Complete OpenAI → Gemini Example

import "dotenv/config";

import {
  ChatOpenAI,
} from "@langchain/openai";

import {
  ChatGoogleGenerativeAI,
} from "@langchain/google-genai";

import {
  PromptTemplate,
} from "@langchain/core/prompts";

import {
  StringOutputParser,
} from "@langchain/core/output_parsers";

const openAIModel =
  new ChatOpenAI({
    model: "gpt-4.1-mini",
  });

const geminiModel =
  new ChatGoogleGenerativeAI({
    model: "gemini-2.5-flash",
  });

const prompt =
  PromptTemplate.fromTemplate(`
Explain {topic} in simple words.

Include one practical example.
`);

const parser =
  new StringOutputParser();

const openAIChain =
  prompt.pipe(openAIModel);

const geminiChain =
  prompt.pipe(geminiModel);

const chain =
  openAIChain.withFallbacks({
    fallbacks: [
      geminiChain,
    ],
  });

const finalChain =
  chain.pipe(parser);

const result =
  await finalChain.invoke({
    topic: "Node.js streams",
  });

console.log(result);

This gives us a production-style fallback structure:

Prompt
  ↓
OpenAI
  ↓
Failure?
  │
  ├── No → Parser → Output
  │
  └── Yes
        ↓
      Gemini
        ↓
      Parser
        ↓
      Output

Gemini → OpenAI Fallback

Fallbacks don't have to go in one direction.

We can make Gemini the primary model:

const geminiChain =
  prompt.pipe(geminiModel);

const openAIChain =
  prompt.pipe(openAIModel);

const chain =
  geminiChain.withFallbacks({
    fallbacks: [
      openAIChain,
    ],
  });

Now:

Gemini
  ↓
Failed?
  ↓
OpenAI

The choice depends on your application requirements.


Multiple Fallbacks

We can configure more than one fallback.

For example:

Primary
   ↓
Fallback 1
   ↓
Fallback 2
   ↓
Fallback 3

Example:

const chain =
  primaryChain.withFallbacks({
    fallbacks: [
      fallbackChain1,
      fallbackChain2,
      fallbackChain3,
    ],
  });

The configured fallback Runnables are tried in order if the preceding Runnable fails.

For example:

OpenAI
  ↓
❌
Gemini
  ↓
❌
Another Model
  ↓
❌
Local Model

This gives your application multiple opportunities to complete the request.


Important: Fallbacks Are Sequential

Suppose you have:

const chain =
  primary.withFallbacks({
    fallbacks: [
      fallback1,
      fallback2,
    ],
  });

This doesn't mean all three models execute simultaneously.

Instead:

Primary
  ↓
If failed
  ↓
Fallback 1
  ↓
If failed
  ↓
Fallback 2

This is different from RunnableParallel.

Remember:

RunnableParallel
     ↓
Run multiple branches

while:

RunnableWithFallbacks
     ↓
Try alternatives after failure

RunnableWithFallbacks vs RunnableParallel

This distinction is extremely important.

RunnableParallel

Use it when you want multiple operations to run independently.

Input
 ├──→ OpenAI
 ├──→ Gemini
 └──→ Another Model

You want all results.


RunnableWithFallbacks

Use it when you want one primary operation and alternatives only when the primary fails.

Input
 ↓
OpenAI
 ↓
Failed?
 ↓
Gemini

You normally want only one successful path.


RunnableWithFallbacks vs RunnableBranch

These are also different.

RunnableBranch

Makes a decision based on a condition.

Input
 ↓
Condition
 ↓
Choose Chain

Example:

provider === "gemini"
      ↓
Gemini

RunnableWithFallbacks

Makes a decision based on failure.

Input
 ↓
Primary Chain
 ↓
Failed?
 ↓
Fallback

So:

RunnableBranch chooses based on a condition.

RunnableWithFallbacks chooses based on failure.


Handling Errors with onError

By default, when a Runnable fails and the fallback mechanism catches the failure, the fallback can receive the input that was sent to the failed Runnable.

LangChain also allows you to configure how the error is handled.

For example:

const chain =
  primaryChain.withFallbacks({
    fallbacks: [
      fallbackChain,
    ],

    onError: (error) => {
      console.error(
        "Primary chain failed:",
        error
      );
    },
  });

This allows you to inspect or transform error information before fallback execution.

The exact behavior of onError depends on how you configure the fallback chain and what information you choose to pass forward. Refer to the current LangChain.js API when implementing advanced error propagation.


Passing Error Information to the Fallback

Sometimes the fallback model needs to know that the primary model failed.

For example:

Primary Model
     ↓
Failure
     ↓
Fallback Model
     ↓
"Try again with this context"

LangChain supports configuring onError so that error information can be added to the fallback input.

Conceptually:

const chain =
  primaryChain.withFallbacks({
    fallbacks: [
      fallbackChain,
    ],

    onError: (error) => ({
      error: error.message,
    }),
  });

This can be useful when you want the fallback to behave differently depending on the failure.

However, you should avoid passing sensitive error details to an external model unless you actually need them.


Fallbacks with RunnableSequence

Fallbacks can be applied to an entire sequence.

Suppose we have:

Prompt
 ↓
Model
 ↓
Parser

We can create:

const primaryChain =
  prompt
    .pipe(openAIModel)
    .pipe(parser);

const fallbackChain =
  prompt
    .pipe(geminiModel)
    .pipe(parser);

Then:

const reliableChain =
  primaryChain.withFallbacks({
    fallbacks: [
      fallbackChain,
    ],
  });

Now the entire chain has fallback behavior.


Fallback at Model Level vs Chain Level

This is an important design decision.

You can attach a fallback directly to the model:

const model =
  openAIModel.withFallbacks({
    fallbacks: [
      geminiModel,
    ],
  });

Then:

Prompt
 ↓
Fallback Model
 ↓
Parser

Or attach the fallback to the entire chain:

const chain =
  openAIChain.withFallbacks({
    fallbacks: [
      geminiChain,
    ],
  });

Then:

Prompt
 ↓
OpenAI Chain
 ↓
Failure
 ↓
Gemini Chain

The second approach can be useful when the fallback workflow needs to include different preprocessing, prompts, or output handling.


Example: Different Prompts for Fallback

Suppose OpenAI uses:

const openAIPrompt =
  PromptTemplate.fromTemplate(`
Give a detailed technical answer:

{question}
`);

Gemini uses:

const geminiPrompt =
  PromptTemplate.fromTemplate(`
Give a concise technical answer:

{question}
`);

Create:

const openAIChain =
  openAIPrompt
    .pipe(openAIModel)
    .pipe(parser);

const geminiChain =
  geminiPrompt
    .pipe(geminiModel)
    .pipe(parser);

Then:

const reliableChain =
  openAIChain.withFallbacks({
    fallbacks: [
      geminiChain,
    ],
  });

Now the fallback isn't just a different model.

It's a completely different workflow.


Fallbacks with RunnableBranch

We can combine routing and fallback behavior.

For example:

Input
 ↓
Branch
 │
 ├── OpenAI Route
 │       ↓
 │     OpenAI
 │       ↓
 │     Gemini Fallback
 │
 └── Gemini Route
         ↓
       Gemini
         ↓
       OpenAI Fallback

This can be useful when the user explicitly chooses a provider.

Example:

const openAIRoute =
  openAIChain.withFallbacks({
    fallbacks: [
      geminiChain,
    ],
  });

const geminiRoute =
  geminiChain.withFallbacks({
    fallbacks: [
      openAIChain,
    ],
  });

Then:

const router =
  new RunnableBranch({
    branches: [
      [
        (input) =>
          input.provider === "openai",
        openAIRoute,
      ],

      [
        (input) =>
          input.provider === "gemini",
        geminiRoute,
      ],
    ],

    default: openAIRoute,
  });

This gives us:

             ┌──→ OpenAI → Gemini
             │
Input → Router
             │
             └──→ Gemini → OpenAI

Fallbacks with RunnableParallel

This can also be useful.

Suppose you have:

Summary
Keywords
Sentiment

Each branch could have its own fallback.

const summary =
  summaryOpenAI.withFallbacks({
    fallbacks: [
      summaryGemini,
    ],
  });

const keywords =
  keywordOpenAI.withFallbacks({
    fallbacks: [
      keywordGemini,
    ],
  });

const sentiment =
  sentimentOpenAI.withFallbacks({
    fallbacks: [
      sentimentGemini,
    ],
  });

Then:

const parallel =
  RunnableParallel.from({
    summary,
    keywords,
    sentiment,
  });

The architecture becomes:

                    ┌──→ OpenAI → Gemini
                    │
Input ──────────────┼──→ OpenAI → Gemini
                    │
                    └──→ OpenAI → Gemini

Each branch has its own fallback strategy.


Real-World Example: AI Customer Support

Imagine a customer support chatbot.

The primary model is OpenAI.

Customer
   ↓
OpenAI
   ↓
Failed?
   ↓
Gemini
   ↓
Response

This protects the application against temporary provider failures.


Real-World Example: AI Content Generation

Suppose your application generates blog posts.

Blog Topic
   ↓
OpenAI
   ↓
Failed?
   ↓
Gemini
   ↓
Failed?
   ↓
Another Model
   ↓
Blog Content

The user doesn't necessarily need to know which provider ultimately generated the content.

The application simply returns the result.


Real-World Example: AI Coding Assistant

A coding assistant might use:

Primary:
OpenAI

Fallback:
Gemini

If OpenAI fails:

User
 ↓
OpenAI ❌
 ↓
Gemini
 ↓
Code Explanation

This can help improve availability.


Real-World Example: Model Provider Abstraction

Suppose you want your application code to be independent of the model provider.

Instead of:

const response =
  await openAIModel.invoke(input);

you use:

const response =
  await reliableModel.invoke(input);

Where:

const reliableModel =
  openAIModel.withFallbacks({
    fallbacks: [
      geminiModel,
    ],
  });

Now the rest of your application doesn't need to know about the fallback implementation.

This is a good example of abstraction.


Important: Fallbacks Don't Fix Bad Prompts

A fallback is primarily for execution failures.

It doesn't mean:

"If I don't like the answer, use another model."

For example:

OpenAI gives a poor answer

does not automatically mean the fallback should run.

A fallback normally responds to an execution error or failure condition, not subjective answer quality.

If you want to evaluate answer quality and choose another response, that's a different architecture.

For example:

OpenAI
 ↓
Evaluator
 ↓
Good?
 ├── Yes → Output
 └── No  → Another Model

That is an evaluation or routing workflow, not simply a fallback.


Fallbacks and Retries Are Different

This is another important distinction.

Retry

Try the same operation again.

OpenAI
 ↓
Failed
 ↓
Retry OpenAI
 ↓
Failed
 ↓
Retry OpenAI

Fallback

Try a different operation.

OpenAI
 ↓
Failed
 ↓
Gemini

These mechanisms can also be combined.

For example:

OpenAI
 ↓
Retry
 ↓
Still Failed
 ↓
Gemini

This can provide stronger resilience.


Fallbacks and Rate Limits

One common reason for fallback is provider rate limiting.

For example:

OpenAI
 ↓
429 Rate Limit
 ↓
Gemini

However, don't automatically assume every error should trigger a provider switch.

Some errors indicate that the request itself is invalid.

For example:

  • Invalid API request

  • Invalid schema

  • Bad prompt formatting

  • Missing required data

Switching providers won't necessarily fix those problems.

This is why production fallback policies should consider the type of failure.


Best Practices

1. Choose a sensible fallback

Don't choose a fallback randomly.

Consider:

  • Model capabilities

  • Latency

  • Cost

  • Context window

  • Structured output support

  • Tool support

  • Availability

  • Rate limits


2. Keep the fallback workflow compatible

If the primary chain returns:

{
  summary: "...",
  keywords: [...]
}

the fallback should ideally return the same shape.

Otherwise, downstream code may break.


3. Don't create endless fallback chains

Avoid:

A
 ↓
B
 ↓
C
 ↓
D
 ↓
E
 ↓
F

Too many fallbacks can increase latency and make debugging difficult.

Use a small, intentional fallback strategy.


4. Monitor fallback usage

If your fallback is being used frequently, something may be wrong with the primary provider.

Track metrics such as:

Primary success rate
Fallback rate
Fallback success rate
Average latency
Provider errors

5. Consider cost

If your primary model is inexpensive but the fallback is expensive, frequent fallback usage can increase your costs.


6. Don't expose internal errors unnecessarily

Users generally don't need to see:

OpenAI returned HTTP 429.

Instead:

We're temporarily using an alternate AI service.

Or simply return the generated response if the fallback succeeds.


Common Beginner Mistakes

Mistake 1: Confusing fallback with parallel execution

Fallback:

A
 ↓
Failure
 ↓
B

Parallel:

A
B
C

These are completely different execution patterns.


Mistake 2: Assuming fallback runs when the answer is bad

A fallback is primarily triggered by failure, not by subjective response quality.

If you want quality-based routing, use an evaluator or classifier.


Mistake 3: Using incompatible output formats

Suppose your primary returns:

{
  answer: "..."
}

but your fallback returns:

"answer..."

Downstream code expecting the object can fail.

Keep output formats consistent.


Mistake 4: Too many fallbacks

More fallbacks don't automatically mean more reliability.

They can increase:

  • Latency

  • Cost

  • Complexity

  • Debugging difficulty


Mistake 5: Ignoring the original error

If your primary model fails, you should still monitor and log the failure.

Fallbacks should improve resilience, not hide operational problems.


Complete Production-Style Example

Let's build a reusable AI chain.

import "dotenv/config";

import {
  ChatOpenAI,
} from "@langchain/openai";

import {
  ChatGoogleGenerativeAI,
} from "@langchain/google-genai";

import {
  PromptTemplate,
} from "@langchain/core/prompts";

import {
  StringOutputParser,
} from "@langchain/core/output_parsers";

const openAIModel =
  new ChatOpenAI({
    model: "gpt-4.1-mini",
  });

const geminiModel =
  new ChatGoogleGenerativeAI({
    model: "gemini-2.5-flash",
  });

const prompt =
  PromptTemplate.fromTemplate(`
You are a helpful technical assistant.

Explain the following topic:

{topic}

Use simple English and provide
one practical example.
`);

const parser =
  new StringOutputParser();

const primaryChain =
  prompt
    .pipe(openAIModel)
    .pipe(parser);

const fallbackChain =
  prompt
    .pipe(geminiModel)
    .pipe(parser);

const reliableChain =
  primaryChain.withFallbacks({
    fallbacks: [
      fallbackChain,
    ],
  });

try {
  const result =
    await reliableChain.invoke({
      topic: "Node.js Streams",
    });

  console.log(result);
} catch (error) {
  console.error(
    "All AI providers failed:",
    error
  );
}

The architecture is:

                ┌──→ OpenAI
                │
Request ─────────┤
                │
                └──→ Gemini

But execution happens as:

OpenAI
  ↓
Success → Output

or

OpenAI
  ↓
Failure
  ↓
Gemini
  ↓
Output

Designing a Reliable AI Architecture

We can now combine several concepts we've learned.

For example:

User Request
     ↓
RunnableLambda
     ↓
Normalize Input
     ↓
RunnableBranch
     ↓
Choose AI Workflow
     ↓
RunnableWithFallbacks
     ↓
Primary Model
     ↓
Fallback Model
     ↓
RunnableAssign
     ↓
Enriched Result

This is starting to look much closer to a production AI system.

Each Runnable has one responsibility.


Runnable Concepts We Have Learned

Let's summarize the Runnable components so far.

RunnableSequence

Sequential execution:

A → B → C

RunnableParallel

Concurrent independent execution:

    ┌→ A
Input → B
    └→ C

RunnableLambda

Custom JavaScript logic:

Input → Function → Output

RunnablePassthrough

Preserve input:

Input → Same Input

RunnableAssign

Enrich an object:

Original + New Fields

RunnableBranch

Conditional routing:

Condition → Selected Branch

RunnableWithFallbacks

Failure-based fallback:

Primary → Failure → Fallback

These are some of the most important building blocks for composing LangChain workflows.


What's Next?

We've now learned how to make a workflow resilient using fallbacks.

But there is another important problem.

Imagine you have 100 questions:

const questions = [
  "What is React?",
  "What is Node.js?",
  "What is Next.js?",
  // ...
];

You could execute:

await chain.invoke(question1);
await chain.invoke(question2);
await chain.invoke(question3);

one by one.

But this can be slow.

LangChain provides a batch() method for processing multiple inputs through the same Runnable.

For example:

const results =
  await chain.batch([
    "What is React?",
    "What is Node.js?",
    "What is Next.js?",
  ]);

This opens the door to another important topic:

Batch Processing in LangChain.js: Process Multiple Inputs Efficiently with batch() (OpenAI + Gemini)

We'll cover that next.


Final Thoughts

RunnableWithFallbacks is an important tool for building reliable AI applications.

The basic idea is simple:

Primary
   ↓
Success?
 ┌─┴─┐
Yes  No
 ↓    ↓
Output Fallback

For example:

OpenAI
  ↓
Failed
  ↓
Gemini

This can protect your application against temporary provider failures and improve overall availability.

But fallbacks should be designed carefully.

The most important things to remember are:

Fallback is not the same as parallel execution.

Fallback is not the same as quality-based routing.

Fallback is not the same as retrying the same model.

Instead:

Retry
  ↓
Try the same operation again

while:

Fallback
  ↓
Try an alternative operation

And:

Branch
  ↓
Choose based on a condition

Once you combine these concepts, you can build much more resilient AI workflows:

Input
 ↓
Normalize
 ↓
Route
 ↓
Primary Model
 ↓
Fallback Model
 ↓
Parser
 ↓
Final Output

This is an important step toward building production-ready LangChain applications.

Happy Coding! 🚀