Jump to content

Building an Autonomous Customer Success Agent with TiDB Serverless and Google Cloud

From JOHNWICK

Customer churn is a billion $ problem. Every SaaS company loses customers, and traditional customer success teams can’t scale to prevent it. What if we could build an AI agent that thinks, learns, and acts like the best customer success managers — but operates 24/7 at infinite scale?

That’s exactly what we built for the TiDB AgentX Hackathon 2025, and the results amazed us.

The Vision: True Autonomy Most “AI agents” today are glorified chatbots or simple automation scripts. We wanted to build something fundamentally different: a truly autonomous system that could:

  • Detect churn risks in real-time
  • Analyze similar successful cases
  • Learn from past interventions
  • Understand customer communications
  • Strategize personalized retention plans
  • Execute multi-step workflows
  • Adapt when things go wrong
  • Remember every outcome for continuous improvement

The key insight: Intelligence emerges from data architecture. The right database enables autonomous behaviour.

Why TiDB Serverless Changed Everything Traditional databases force you to choose: fast transactions OR complex analytics. Customer success needs both simultaneously. TiDB Serverless delivers:

🎯 Vector Search for Business Logic Instead of just storing customer data, we stored 768-dimensional semantic embeddings representing customer behaviour, churn patterns, and successful interventions.

# Generate semantic embeddings for similarity matching
customer_embedding = generate_semantic_embedding(
    f"segment:{customer.segment} usage:{customer.usage_score} "
    f"nps:{customer.nps} churn_risk:{customer.churn_probability}"
)

# Find similar successful retention cases
similar_cases = await tidb.find_similar_retention_cases(
    customer_embedding=customer_embedding,
    customer_segment=customer.segment,
    churn_probability=customer.churn_probability
)

Result: Our agent finds proven retention strategies in <50ms by comparing current customers to similar successful cases.

⚡ HTAP: Real-time + Analytics in One Query Customer success requires split-second decisions based on historical patterns. TiDB’s HTAP processing eliminates the traditional OLTP/OLAP divide:

-- Single query: real-time churn detection + segment analysis
SELECT customer_id, churn_probability,
       AVG(churn_probability) OVER (PARTITION BY segment) as segment_avg,
       COUNT(*) OVER (PARTITION BY risk_level) as risk_count
FROM customers 
WHERE last_updated >= NOW() - INTERVAL 1 HOUR
  AND churn_probability >= 0.75
ORDER BY churn_probability DESC

Result: Instant identification of at-risk customers with full business context.

🧠 JSON-Native Agent Memory AI agents need flexible memory that evolves. TiDB’s native JSON support enabled persistent learning:

# Store flexible agent memory with embeddings
memory_context = {
    "customer_segment": "enterprise",
    "intervention_strategy": "executive_outreach", 
    "success_factors": ["dedicated_support", "executive_call"],
    "effectiveness_score": 0.89,
    "timestamp": datetime.now().isoformat()
}

await tidb.store_agent_memory(
    customer_id=customer.id,
    context=memory_context,
    outcome="successful",
    embedding=strategy_embedding
)

Result: The agent learns from every interaction and improves over time. The Autonomous Workflow Architecture

Our agent follows an 8-step autonomous workflow, with each step leveraging different TiDB capabilities:

1. DETECT → HTAP Real-time Analytics Continuously monitor customer health using TiDB’s HTAP processing:

# Detect high-risk customers with real-time + historical context
high_risk_customers = db.query(Customer).filter(
    Customer.churn_probability >= 0.75,
    Customer.last_login_days_ago > 7
).order_by(Customer.annual_contract_value.desc()).all()

2. ANALYZE → Vector Search Similarity Find customers with similar profiles who were successfully retained:

# Vector similarity search for proven strategies
similarity = 1 - cosine(customer_embedding, pattern_embedding)
if similarity > 0.8:  # High confidence match
    proven_strategies.append(pattern.successful_interventions)

3. LEARN → Agent Memory Retrieval Access persistent memories of successful interventions:

# Retrieve relevant agent memories using vector search
agent_memories = await tidb.retrieve_agent_memory(
    customer_id=customer.id,
    interaction_type="churn_intervention",
    context_embedding=customer_embedding
)

4. UNDERSTAND → Full-Text Communication Analysis Analyze customer sentiment and pain points:

-- Full-text search for customer communication insights
SELECT message_content, sentiment_score, timestamp
FROM customer_communications
WHERE customer_id = ? 
  AND MATCH(message_content) AGAINST('billing frustrated support')
ORDER BY timestamp DESC

5. STRATEGIZE → AI Strategy Generation Use Google Gemini LLM with all TiDB context to generate personalized strategies:

# AI strategy generation using comprehensive TiDB data
intervention_strategy = await gemini.analyze_retention_strategy(
    customer_profile=customer_data,
    similar_cases=vector_results,
    agent_memories=memories,
    communications=sentiment_analysis,
    relationships=graph_connections
)

6. EXECUTE → Multi-step Autonomous Actions Implement the strategy through automated workflows:

# Multi-step execution with self-correction
execution_steps = [
    {"type": "personalized_email", "template": "retention_v2"},
    {"type": "retention_discount", "amount": "20%"}, 
    {"type": "schedule_success_call", "urgency": "high"}
]

7. ADAPT → Self-Correction Logic Automatically adapt when steps fail:

# Autonomous self-correction
if email_result == "bounced":
    await execute_phone_call(customer)
elif call_result == "rejected": 
    await schedule_product_demo(customer)

8. REMEMBER → JSON Learning Storage Store outcomes for continuous improvement:

# Store learning for future improvements
learning_record = {
    "strategy_used": intervention_strategy["strategy"],
    "outcome": "successful",
    "effectiveness": 0.87,
    "customer_characteristics": customer_profile,
    "adaptations_made": self_corrections
}

The Results That Amazed Us After deploying our autonomous agent:

  • 🎯 Live demo customers saved from churn
  • 💰 $$ revenue retained through automated interventions
  • 📉 % churn reduction
  • ⚡ 30-second response time to churn signals
  • 🤖 95% agent autonomy — minimal human oversight required

Code Architecture: React + Cloud Run + TiDB

What We Learned About Autonomous Systems

1. Data Architecture Enables Intelligence The right database doesn’t just store data — it enables intelligent behaviour. TiDB’s combination of vector search, HTAP processing, and JSON flexibility created emergent autonomous capabilities.

2. Self-Correction is Critical Autonomous systems must handle failures gracefully. Our agent’s ability to adapt (email fails → phone call → demo) was essential for 95% autonomy.

3. Memory Makes Agents Smarter Persistent, searchable memory transformed our agent from reactive to predictive. Each intervention made future decisions better.

4. Business Logic + AI = Magic Combining domain-specific business rules with LLM intelligence created something more powerful than either alone.

The Future of Autonomous Business Systems This project proved that autonomous business intelligence is possible today with the right data architecture. TiDB Serverless doesn’t just support autonomous agents — it enables them.

Read the full article here: https://sudsk.medium.com/building-an-autonomous-customer-success-agent-with-tidb-serverless-and-google-cloud-6f8f566cff33