跪拜 Guibai
← Back to the summary

Don't Rewrite Dify: Sink Heavy Logic into LangGraph with a Hybrid Architecture

🤔🤔 Don't Tear Down Dify — Sink the Heavy Logic into LangGraph

A very common failure scene

Dify has been live for three months, and the business experience is great: operations edits prompts themselves, maintains the knowledge base independently, and can quickly build new workflows by dragging and dropping on the canvas.

Then requirements start stacking up:

  1. Approval needs to support rejection, parameter modification, and resubmission;
  2. Task failure auto-retries 3 times, and if the last retry fails, it goes to manual fallback;
  3. A certain node needs to loop-call an internal risk control API until the status meets the condition;
  4. High-risk deletion operations must pause and wait for the approval system to call back.

You keep adding nodes and branches on the Dify canvas. When you reach a dozen or so branches, the problem is no longer "the diagram is a bit ugly," but: changing one branch means re-running the full-chain regression, and operations doesn't dare touch it, nor does development dare delete it.

At this point, the team easily gets an idea: just migrate everything to LangGraph, and use code for more control.

My suggestion is: not yet. A full rewrite is the highest-risk option in a migration, and it can easily lose the operational self-service capabilities that Dify has accumulated.

A safer path is: keep Dify as is, and only gradually sink the heavy logic that the platform capabilities block into LangGraph.

In one sentence: simple, frequently prompt-tuned business stays in Dify; heavy logic, strong governance, and flows that need code freedom sink into LangGraph.

image(1).png

First, see clearly: you don't need to switch platforms, you need to layer

Many people turn a migration discussion into "which is stronger, Dify or LangGraph." This comparison itself is off track.

They are not on the same layer:

So the correct move is not replacement but layered composition.

                    ┌─────────────────────────┐
用户请求 ──────────▶ │        Dify 应用         │
                    │  入口 / 门面 / 运营层     │
                    └───────────┬─────────────┘
                                │
                ┌───────────────┴────────────────┐
                │                                │
                ▼                                ▼
     ┌──────────────────┐            ┌──────────────────────┐
     │ 简单问答 / 简单检索 │            │ 复杂子任务:HTTP 调用  │
     │ Dify 内部直接完成  │            │ LangGraph 服务        │
     └──────────────────┘            │ 状态机 / 审批 / 循环   │
                                     │ 失败重规划             │
                                     └──────────┬───────────┘
                                                │
                          ┌─────────────────────┴─────────────────────┐
                          ▼                                           ▼
                ┌──────────────────┐                      ┌──────────────────┐
                │ 统一检索服务       │                      │ 统一 Tool Runtime │
                │ 多路召回 / 重排    │                      │ 鉴权 / 限流 / 审计 │
                └──────────────────┘                      └──────────────────┘

One sentence: Dify doesn't retire, LangGraph doesn't seize power, and common capabilities are extracted for both sides to share.

What should be migrated, and what should not be touched

In actual scenarios, let's evaluate:

Dify's original capability Migration target When is it worth migrating
Workflow LangGraph StateGraph Many branches, loops, need failure replanning, require unit tests and code review
Knowledge base node Independent retrieval service Need multi-path recall, custom filtering, reranking, integration with internal permission documents
Tool node Unified Tool Runtime Many tools, complex permissions, need unified rate limiting, logging, timeout, auditing
Human approval node interrupt / resume Need persistent approval, rejection then parameter modification to continue, high-risk operations fallback

These scenarios below must stay in Dify:

The reason is simple: Dify's core value is low-code self-service operations. Migrating flows that operations tunes every day into code turns every change into a developer release. ---- This is not an upgrade; it's a regression. ----

The migration motive should be "platform capability is blocked," not "I want to use code to look more advanced."

43a7d933c895d143579bb3d17ed800095baf0702.webp

Four migration points, how to implement

1. Workflow → LangGraph StateGraph

Dify's canvas is a fixed-connection pattern. Once loops, dynamic branches, or failure retries appear, the canvas quickly bloats, and it's hard to write unit tests or do code review.

LangGraph's StateGraph is state-centric, with nodes and conditional edges freely orchestrated, suitable for Agent patterns like ReAct and Plan-and-Execute. Code can go into Git, go through testing, and go through review.

But the key is not "move everything." Prioritize migrating chains with many branches, many loops, and the need for dynamic replanning; keep simple chains in Dify.

The judgment standard is not "it's a bit complex," but "its complexity can no longer be safely maintained on the canvas."

2. Knowledge base → independent retrieval service

Dify's built-in knowledge base suits small scale and simple retrieval. Once you need multi-path recall, custom filtering, reranking, and integration with internal permission documents, the built-in retrieval's customization space is insufficient.

The approach is not to migrate documents, but to extract retrieval into an independent service: this way, both Dify and LangGraph call the same retrieval API service. Retrieval logic is uniformly reused, avoiding two sets of logic splitting.

The essence of knowledge base migration is productizing retrieval capability, not document relocation. ---- Agents must be managed with engineering discipline ----

3. Scattered tool nodes → unified Tool Runtime

In Dify, each tool is configured separately, and permissions, logging, and rate limiting logic are scattered. When there are many tools, it's hard to trace:

After migration, a unified tool gateway is encapsulated: input validation, authentication, timeout, rate limiting, and call auditing all converge into this layer. Dify and LangGraph share the same runtime, avoiding duplicate development and logic inconsistency.

Tool migration is not moving nodes, it's converging permissions.

4. Human approval → LangGraph interrupt / resume

This is the highest-value and most worthwhile scenario to pilot first.

Dify's native human node has difficulty supporting cross-instance persistent approval, or rejecting, modifying parameters, and then resuming execution.

LangGraph's interrupt natively supports human-in-the-loop interruption: execution pauses at the approval point, state is persisted; the approval system gets the thread_id, and after a human approves or rejects, the flow resumes with the same thread_id.

Below is illustrative code; focus on the structure of interrupt and resume:

from typing import TypedDict
from langgraph.graph import StateGraph, END
from langgraph.types import interrupt, Command
from langgraph.checkpoint.memory import MemorySaver


class State(TypedDict, total=False):
    ticket_id: str
    status: str
    reason: str


def approval_node(state: State):
    # Pause here, wait for human approval
    decision = interrupt({
        "action": "delete_records",
        "ticket_id": state["ticket_id"],
        "risk": "high",
    })
    if decision["approved"]:
        return {"status": "approved"}
    return {"status": "rejected", "reason": decision["reason"]}


builder = StateGraph(State)
builder.add_node("approval", approval_node)
builder.add_edge("approval", END)

# MemorySaver for demo; in production, switch to a persistent checkpointer like Redis
# NOTE!!! In production you must use a persistent checkpointer, otherwise the approval state is lost if the instance restarts.
checkpointer = MemorySaver()
app = builder.compile(checkpointer=checkpointer)

# 1. Start the flow; it will pause at the approval node
app.invoke(
    {"ticket_id": "ticket-123"},
    config={"configurable": {"thread_id": "ticket-123"}},
)

# 2. After human approval, resume execution with the same thread_id
app.invoke(
    Command(resume={"approved": True}),
    config={"configurable": {"thread_id": "ticket-123"}},
)

Dify doesn't need to care about state machine details; it only needs to initiate an HTTP call at the complex subtask node, get the thread_id, and trigger resume via a callback after approval completes. Timeout, degradation, and failure fallback branches can still be configured on the Dify side.

The value of approval migration is not "adding a few nodes," but making high-risk operations pausable, resumable, and auditable.

Migration order: don't start with the hardest

Many teams migrate the most complex flow first, get stuck after two weeks, and lose morale. A more stable order is:

Step 1: Sink common capabilities first
Unify Tool Runtime + independent retrieval service
High reusability, low risk, shared by Dify / LangGraph
      
Step 2: Get human approval working first
interrupt / resume + thread_id recovery
Pick a high-risk but clearly bounded approval scenario as a pilot
        
Step 3: Gradually sink complex Workflows
Only migrate chains with many branches, loops, and replanning needs
For each migration, retain a path to switch back to Dify

Each migrated part must be able to gray-release, verify, and roll back (just in case). It must achieve "every migration step is controllable".

The cost of a hybrid architecture, must be accepted upfront

Dify calling LangGraph over HTTP is not without cost:

The only boundary red line: don't force simple subtasks out, don't layer for the sake of layering. Use unified traceId + thread_id to ensure full-chain traceability.

The difficulty of a hybrid architecture is not "getting it connected," but being able to trace problems clearly and roll back cleanly when they occur.

image (1).png

These three cases: don't do a hybrid architecture

If your business meets any of the following, directly prioritize self-development or pure LangGraph, and don't do a Dify + LangGraph hybrid:

  1. The flow is almost entirely strong logic, loops, and approvals, with almost no need for operations to self-tune prompts;
  2. Extremely high latency and stability requirements, unable to accept additional HTTP cross-service call overhead;
  3. The team is very small, with no energy to maintain two systems and two sets of operation and monitoring.

Saying this is basically stating the obvious; such designs are essentially what everyone does. Treat these as a note of caution...

Finally

Dify is the fast delivery layer for business; LangGraph is the code orchestration layer for core logic.

Migration is not replacement, it's layering. Simple flows stay in Dify and are maintained by operations; complex, strongly governed, continuously iterated logic sinks into LangGraph, trading code for orchestration freedom.

No need to tear everything down. Gradual sinking has lower risk and more stable returns.

If you're ready to act, the next step is only one thing: choose a high-risk but clearly bounded approval scenario, and get interrupt / resume + thread_id working first. Remember: deciding whether to expand the migration scope after it works is more reliable than drawing a big picture from the start.

Welcome to discuss in the comments! Hope this article helps you and offers some reference.

Comments

Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.

用户573468752399 1 likes

After we sank the heavy logic into LangGraph, our bill actually went up a notch. Three reasons: first, the same flow calls the model once on each side, so the same prompt gets paid for twice; second, both sides have their own retries, and failures stack into three or four calls; third, keys are scattered across several platforms, so at month's end we can't match which flow spent how much. Later we unified into a single gateway layer: both sides go through the same key, tag by flow, retries happen only once at the gateway, and usage is exported by business line, only then did the accounts balance. Several domestic model providers offer one key that calls all models, enterprise channel pricing, and itemized exports that can be broken down by flow; anyone doing hybrid architecture can have a chat. Details via private message.

Sailing

Cost indeed tends to rise, especially when both sides call once each and retries stack up. Unified gateway and flow tagging, that direction is fine. But the sinking mentioned in the article is mainly not to save money; it's that Dify is insufficient in complex scenarios and needs engineering to fill the gap. The gateway solves usage control; whether a flow should be sunk should still be chosen by scenario, not an either/or.