Skip to content
How Zhihu Built DBAgent: An AI Agent Architecture for Trustworthy Database Operations

How Zhihu Built DBAgent: An AI Agent Architecture for Trustworthy Database Operations

Zhihu's DBAgent employs Deep Agents for dynamic planning, modular DB Skills for codified runbooks, and A2A protocol for task management to orchestrate real-time database operations across MySQL, TiDB, OceanBase, and Redis with human-in-the-loop governance and full audit trails.

Xiaolei Talks DB
Xiaolei Talks DB
Xiaolei Talks DB

Why DBAgent Was Needed

Zhihu's database team had built rich operational capabilities over years — instance topology queries, monitoring, slow log search, alert handling, backup/recovery, scaling, failover, ticketing, and change execution. However, these capabilities were scattered across different platforms, interfaces, and SOPs:

MySQL, TiDB, OceanBase, and Redis each had different operation entry points and data structures.

Metadata, monitoring, logs, alerts, and change systems were independent.

A single "database slow" issue required sequentially querying topology, monitoring, slow logs, and change records.

New engineers needed to memorize numerous platform entry points, parameter conventions, and troubleshooting experience.

Production operations must satisfy identity, permission, approval, and audit requirements.

Traditional ChatBots could answer knowledge questions but had three clear limitations for real operations:

They didn't know if data was still valid — database topology, capacity, alerts, and slow SQL change in real time and cannot rely on model training data or historical documents.

They lacked closed-loop execution capability — real troubleshooting is a loop of "identify problem → supplement parameters → call tools → observe results → adjust plan → query again → form conclusion."

They lacked production governance — without preserving real identity, pausing before risky actions, and recording tool parameters and results, stronger models actually increase potential risk.

Therefore, DBAgent is positioned not as a "more database-savvy chatbot" but as an intelligent orchestration layer for database operations: users state goals in natural language, the agent handles understanding, planning, and scheduling, but data still comes from real systems and high-risk actions remain constrained by existing governance.

Design Goals

1. One Entry Point for Multiple Database Scenarios

Cover MySQL, TiDB, OceanBase, and Redis, unifying read-only queries, monitoring inspections, slow log analysis, alert analysis, and controlled changes. Users don't need to judge which platform to open or remember specific interfaces.

2. Data from Tools, Not Model Memory

The model handles understanding, planning, induction, and explanation. Cluster state, capacity, topology, SQL, alerts, and other facts must come from real-time tool returns. When tools fail, the failure is reported honestly; the model is not allowed to fabricate a "plausible-looking" result using language ability.

3. Codify Database Experience as Iteratable Skills

Encapsulate "when to use which capability, required parameters, how to call interfaces, how to judge results, and how to handle common exceptions" into independent DB Skills. Knowledge updates don't require modifying agent core code, and platform differences don't all pile into one giant system prompt.

4. Support Multi-step Tasks and Specialized Division of Labor

Complex tasks are planned first, then executed; some domain capabilities can be delegated to specialized sub-agents. For example, Redis scenarios are split into metadata retrieval, runtime diagnostics, and change ticketing roles, making tool sets and prompt contexts more focused.

5. Make High-risk Actions Pausable, Confirmable, and Traceable

Production probing, remote binary execution, and write operations cannot be treated as ordinary Q&A. DBAgent uses a human-in-the-loop mechanism to transition tasks to an input-waiting state, where users approve, edit, reject, or supplement information before execution continues. Task state and tool trajectories preserve full context.

Critical note: Agent frameworks, prompts, and Skills are not permission systems. Real identity, least privilege, resource authorization, credential hosting, and audit must still be enforced by the access gateway, tool layer, and downstream platforms together.

Overall Architecture

The architecture comprises four layers: Access & Protocol, Agent Runtime, Tools & Platforms, and cross-cutting capabilities.

3.1 Access & Protocol Layer: Turning a Conversation into a Manageable Task

Users can initiate requests from Enterprise WeChat, operations workbench, or other agents. The access layer handles user identity resolution, session management, admission control, and audit logging, then passes trusted identity via request context to DBAgent.

DBAgent exposes A2A v1 protocol externally, providing Agent Card, JSON-RPC, and streaming output. Unlike ordinary synchronous interfaces, A2A models a request as a task with taskId and contextId, making it naturally suitable for multi-round tool calls and human confirmation.

The A2A adapter in code has two key responsibilities:

Convert underlying LangGraph task events into A2A v1 data structures.

Wrap LangGraph's interrupt/resume mechanism into standard TASK_STATE_INPUT_REQUIRED and ordinary follow-up Messages.

This means callers don't need to understand LangGraph internal state; they just reply "approve", rejection reason, or send structured decisions on the same task to resume it.

3.2 Deep Agent Core: Understanding, Planning, and Feedback Loops

DBAgent's core is built with create_deep_agent and runs on LangGraph Server. The model can use default providers or internal model gateways via OpenAI-compatible interfaces.

Unlike fixed workflows, the Deep Agent dynamically decides the next action based on the current problem:

Judge user intent and database type.

Check if required parameters are complete.

Select and read the corresponding Skill.

Decide whether to call tools directly or delegate to a sub-agent.

Observe tool results and adjust subsequent steps.

Form final answer when goal is reached.

The system prompt defines global capability boundaries and routing rules — e.g., distinguishing Beidou alerts from Welkin monitoring, Kibana raw slow logs from platform slow SQL views, Redis metadata queries from runtime probing. It does not store all interface details but requires the agent to read the corresponding Skill when a scenario is matched.

3.3 DB Skills: Turning Tacit DBA Experience into Executable Knowledge

DB Skills are the key layer connecting "model reasoning" with "platform capabilities." Current code splits Skills by domain: dbops-query: Read-only queries for MySQL, TiDB, OceanBase instances, topology, schema, processlist, backups, tickets dbops-monitor: QPS, watermark, disk, replication lag, connections, DTS/TiCDC status, health inspections dbops-elk-query: MySQL/TiDB slow logs, database component log search and aggregation analysis dbops-ob-query: OceanBase/OCP cluster, tenant, zone, session, TopSQL, backup, alert queries dbops-bds: Beidou alert weekly reports, personal alert inspections, alert pattern analysis dbops-redis: Redis cluster, topology, capacity trends, latency, runtime diagnostics dbops-iaas: IP to Pod, container, node infrastructure reverse lookup dbops-ops: Controlled changes: scaling, failover, cluster create/delete, SQL, DTS, OSC

Deep Agents use progressive disclosure: at startup only Skill names and summaries are loaded; full SKILL.md is read only when actually matched. This controls context length and avoids irrelevant SOPs interfering with current decisions.

Skills support three-tier resolution: environment variable directory, server fixed directory, code repository built-in directory. Production can maintain Skills in the fixed directory and create/update via management interfaces; old versions are auto-backed up before updates, achieving decoupling of knowledge iteration from agent core.

This design has a practical value: database platform interfaces and troubleshooting experience can iterate quickly while the core orchestration framework stays stable.

3.4 Tool Layer: Connecting Real Systems with Deterministic Code

If Skills describe "how things should be done," the tool layer solves "actually getting things done." Current DBAgent tools include:

Generic async HTTP tool for calling Welkin, Beidou, IAAS, and other JSON APIs.

OceanBase OCP dedicated signed client completing AK/SK signing server-side.

MySQL/TiDB slow log dedicated tools handling precise index selection, time filtering, data cleaning, and aggregation.

Redis cluster, topology, capacity, runtime, and change tools.

Restricted server binary execution tool for specific diagnostic programs.

Long-term memory query and write tools.

Tools generally use async implementation and a unified response envelope: { "code": 0, "msg": "success", "data": {} } When code == 0, data is authoritative; on failure, msg gives the real error. The unified envelope reduces the model's chance of misjudging complex return structures and makes "fail without fabrication" an executable rule, not just a prompt instruction.

The slow log tool further embodies "deterministic logic pushdown." Index selection, time fields, cluster filtering, SQL fingerprint aggregation — these rules are implemented in code; the model only provides confirmed parameters and interprets results. Compared to letting the model directly stitch Elasticsearch DSL, this approach is more stable, testable, and auditable.

3.5 Sub-agents: Converging Context and Tool Sets by Domain

The main agent currently defines three Redis-specific sub-agents:

Redis Metadata Agent: queries cluster list, topology, capacity trends.

Redis Runtime Agent: executes fixed runtime commands and latency probing.

Redis Ticket Agent: submits change requests.

Sub-agents aren't for adding hierarchy but for reducing the number of tools and instruction conflicts a single agent faces. Each role works within a smaller capability boundary; the main agent handles overall goals, delegation, and result integration.

3.6 Human-in-the-loop: Turning Risky Actions into Explicit States

DBAgent configures mandatory interrupts for certain high-risk tools: connecting to production Redis to execute runtime commands, launching diagnostic binaries on servers, and Deep Agents' built-in execution and file-write actions.

When interrupted, the task stops and returns:

The tool name about to execute.

Complete parameters.

Human-readable risk explanation.

Allowed decisions: approve, edit, reject, or reply.

The user's follow-up message is converted into a structured resume decision, and the task continues from the original thread. Tool trajectories are also output as A2A extension data with task state for caller display or audit.

The significance: approval is no longer a natural language "please confirm" but a formal node in the agent's state machine.

3.7 Memory, Observability, and Sandbox

Long-term memory. At each user turn start, the system retrieves relevant long-term memory once based on current question semantics and injects it into model context; at turn end, it writes back per strategy. Retrieved results are explicitly marked "for reference only"; real-time topology and metrics must still be re-queried via tools.

Observability. Langfuse callbacks record model, tool, and session traces; context middleware reads token usage from model returns and records per-thread context consumption, helping detect long sessions and context bloat.

Thread-level sandbox. When LangSmith Sandbox is configured, the system creates or reuses isolated environments per thread; without config, it uses the default state backend. Sandbox capability further isolates the generic execution environment from the host service.

Request Processing Flow

A typical request goes through seven steps:

Step 1: Receive Request and Bind Identity, Task, Session

The access gateway passes the natural language question, trusted user identity, and session info to DBAgent. The A2A layer creates or continues a task, binding taskId, contextId, and LangGraph thread so subsequent tool calls, human confirmations, and task resumptions all occur in the same context.

Step 2: Load Context and Long-term Memory

The memory middleware retrieves once per user turn only, avoiding repeated Memory service access during the agent's tool loop. Results supplement historical agreements and environment facts but do not replace real-time queries.

Step 3: Identify Intent and Check Parameters

The agent first judges which database type and job category the question belongs to, then checks key parameters, e.g.:

MySQL/TiDB/OceanBase queries usually need cluster name and database type.

Redis scenarios usually need App name and cluster identifier.

Slow logs need explicit cluster and time window.

Change operations need explicit target object and action.

If key parameters are missing, the agent asks the user for clarification rather than guessing a cluster or time range.

Step 4: Route to Skill and Form Execution Plan

Based on routing rules, the agent selects the target Skill, reads the full SOP, then decides which tools and execution order are needed. Complex tasks can write a todo list first or delegate to a specialized sub-agent.

Example: "Check slow SQL for a TiDB cluster in the last hour" routes to the log Skill, fills instance_name, start/end time, then calls the TiDB slow log dedicated tool. "Which clusters under this Redis App" is better delegated to the Redis Metadata sub-agent.

Step 5: Choose Execution Path by Risk Level

Read-only queries call tools directly. Production probing or changes enter human confirmation state, waiting for user approval, parameter edits, rejection, or supplementary info.

After user approval, the task resumes from the original thread, not restarting. This is critical for multi-step operations because previously confirmed objects, parameters, and tool results are preserved.

Step 6: Execute Tools and Validate Returns

Tools access real platforms or data sources, returning the unified envelope. The agent judges success, no-data, or failure based on code, msg, and data. The same query retries a limited number of times; if still failing, the reason is stated directly — connection errors, permission errors, or empty results are not interpreted as business conclusions.

Step 7: Generate DBA-oriented Conclusion

The model aggregates and interprets tool returns into an answer suitable for DBAs, including:

Current status and key metrics.

Anomalous objects and impact scope.

Correlations across multiple data sources.

Possible causes with evidence.

Risk warnings and suggested next steps.

Results stream back via A2A; tool trajectories enter observability; facts suitable for retention are written to long-term memory.

Typical Case: Why Slow SQL Analysis Needs an Agent

User asks: "Help me see why a certain TiDB cluster slowed down in the last hour."

A traditional QA system might give generic troubleshooting advice. DBAgent breaks it into an executable task:

Confirm TiDB cluster name and time window.

Read log Skill, use correct slow log index and time field.

Call slow log dedicated tool, filter precisely by cluster.

Aggregate by database, Pod, SQL type, slowest SQL, and high-frequency fingerprints.

If needed, continue querying monitoring, topology, or recent changes.

Merge evidence from different tools into a diagnostic conclusion.

The key is not that "the model knows TiDB" but that it works along a constrained evidence chain: parameters from user or platform, steps from Skill, data from tools, conclusion from traceable returns.

Key Design Trade-offs

6.1 Skills and Code Each Do What They're Good At

Frequently changing SOPs, routing experience, and interface usage notes go in Skills; identity verification, request signing, time handling, data aggregation, and risk interception go in deterministic code. The former pursues maintainability and fast iteration; the latter pursues stability, testability, and auditability.

6.2 Generic and Specialized Tools Coexist

Generic HTTP tools can quickly cover many internal platforms, but complex or high-risk scenarios should gradually converge into specialized tools. Specialized tools can fix target systems, parameter structures, timeouts, return models, and security policies, reducing the model's degrees of freedom.

6.3 Memory Is Not a Real-time Database

Long-term memory suits user preferences, environment conventions, and historical facts — not real-time capacity, topology, and alerts. DBAgent explicitly states this boundary in the memory injection text to prevent "historically so" from being mistaken as "still so now."

6.4 Approval Must Enter the State Machine

If approval exists only in prompts, the model might miss it, and upstream systems can't accurately identify what the task is waiting for. Modeling approval as INPUT_REQUIRED enables true pausability, resumability, and integrability.

6.5 Agent Should Not Become a New Super-permission Entrance

DBAgent can unify user experience but must not bypass existing database governance. The ideal chain: upstream retains real user identity, tool layer enforces action-level policies, downstream platforms re-verify resources and permissions, credentials are server-hosted, and all systems use a unified request ID to link audit trails.

Next Steps: From "Usable" to "Trustworthy"

Current code already has multi-database Skills, specialized tools, sub-agents, A2A, HITL, Memory, and observability. For larger-scale production use, evolution can continue along five directions:

Tighten identity and authorization boundaries: Ensure all production entries fail-closed on missing/invalid identity; permission decisions use real user, asset, and action, not just role tags; read and write operations use different permission domains.

Gradually replace generic HTTP capabilities with fixed-purpose tools: Add target domain, HTTP method, interface path, and parameter whitelists to generic tools; build fixed-purpose clients for high-frequency capabilities so the model only selects business actions and parameters.

Unify mandatory approval for high-risk actions: Put changes, production probing, and remote execution under a policy engine; tool metadata decides whether HITL is forced, avoiding reliance solely on Skill or system prompt conventions.

Build evaluation and replay systems: Establish test sets around routing accuracy, parameter completeness, tool success rate, evidence-backed conclusion rate, misoperation interception rate, and human takeover rate; replay with real but desensitized historical tasks to continuously verify Skill and model upgrades.

Expand autonomy in phases: Start with read-only queries, diagnostic suggestions, and Shadow Mode; then enter restricted production read-only; write operations long-term retain approval, ticketing, and rollback mechanisms. Autonomy level upgrades should be proven by data, not model capability marketing.

Conclusion

The value of a database agent is not hiding all operations platforms behind a chat box, but reorganizing scattered tools, knowledge, and processes into an executable, governable task chain.

In this architecture:

Deep Agents handle understanding questions, planning steps, and adjusting strategy based on results.

DB Skills codify scenario-specific SOPs and platform usage knowledge.

Specialized tools fetch real data and execute deterministic actions.

A2A handles taskification, streaming interaction, and cross-system collaboration.

HITL, identity, permissions, audit, and observability jointly constrain production risk.

This is the core problem Zhihu DBAgent aims to solve: not replacing DBAs with models, but letting the tools, experience, and governance capabilities DBAs have already built be organized and invoked in a more natural, efficient way.

When every agent conclusion has data backing, every action has clear boundaries, and every execution can be paused and traced, it truly has the chance to grow from a demo system into a trustworthy database collaboration partner in production environments.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

database operationsAgent ArchitectureLangGraphhuman-in-the-loopA2A ProtocolDeep AgentsDB SkillsDBAgent
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.