All Blog

Chat APIs & SDKs: The Ultimate Developer Guide (2026)

12 min read
May 28, 2026

chat-api-sdk-ultimate-guide.png

TL;DR

  • A chat API handles message routing, storage, and delivery on the server side. A chat SDK wraps that API into native client libraries so you integrate in hours, not months.
  • Building chat from scratch takes 6–12 months and 3–5 engineers. A managed chat SDK gets you to production in days.
  • The CPaaS market is projected to reach USD 86.26 billion by 2030 at 28.7% CAGR (Grand View Research) — chat is the most demanded component.
  • Free Chat API — Tencent RTC offers a permanent free tier: 1,000 MAU, no concurrency limits, push notifications included across 6 vendor channels.
  • This guide covers architecture, capabilities, provider comparison, integration methods, pricing models, and a step-by-step tutorial to send your first message.

What Is a Chat API/SDK?

Chat API Defined

A chat API (Application Programming Interface) is a set of server-side endpoints that handle real-time message routing, persistent storage, user authentication, presence management, and delivery guarantees between clients. When your application calls a chat API, the service:

  • Authenticates the sender via secure tokens
  • Routes the message to one or more recipients through optimized network paths
  • Persists the message in distributed storage for history retrieval
  • Triggers push notifications if recipients are offline
  • Returns delivery status and read receipts back to the sender

The API abstracts away WebSocket connection management, message queuing, database sharding, geographic replication, and push notification integrations. You send structured requests; the platform handles the distributed systems complexity.

Chat APIs typically expose two transport layers:

  1. WebSocket — persistent bidirectional connection for real-time message streaming to clients
  2. REST/HTTP — request-response endpoints for server-side operations (admin actions, bot messages, bulk operations)

Chat SDK Defined

A chat SDK (Software Development Kit) is a client-side library that wraps the chat API into platform-native code. Instead of managing raw WebSocket connections, handling reconnection logic, and parsing binary protocols, you call high-level methods like sendMessage(), joinGroup(), or markAsRead().

A production chat SDK includes:

  • Connection management — automatic reconnection with exponential backoff, heartbeat signals, session resumption
  • Local caching — offline message queue, conversation list persistence, draft storage
  • Event system — callbacks for incoming messages, typing indicators, presence changes, connection state
  • Media pipeline — image/video compression, progressive upload with progress callbacks, thumbnail generation
  • Push token management — automatic registration for APNs, FCM, and vendor-specific push channels
  • Sync engine — sequence-number-based reconciliation to ensure no messages are missed after offline periods

UIKit: The Third Layer

Beyond APIs and SDKs, many providers offer a UIKit — prebuilt UI components (conversation list, message bubbles, input bar, media viewer, group management screens) that you embed directly into your app. This is the fastest path to a working chat feature but trades customization for speed.

Tencent RTC's UIKit delivers a complete chat interface in under 5 minutes — conversation list with avatars, message view with media, input bar with voice/emoji/file support — all with a single component import.

API vs SDK vs UIKit: Quick Comparison

LayerWhat It IsIntegration TimeCustomization LevelBest For
REST APIServer-to-server HTTP endpointsDays to weeksUnlimitedBackend bots, admin tools, data migration
Client SDKNative platform libraryHours to daysHighCustom UI with full UX control
UIKitPrebuilt UI + SDK5–30 minutesModerate (theming)MVPs, standard chat UX, rapid prototyping

When to Use Which

UIKit when you want chat working within the hour and the default UI is acceptable. Most UIKits support theming (colors, fonts, layout density) without code changes.

SDK when you need a fully custom interface — unique message layouts, custom animations, novel interaction patterns — but still want managed infrastructure handling the hard parts.

REST API when you're building server-side integrations: chatbots, moderation pipelines, analytics dashboards, message import/export, or webhook-triggered workflows.

Most production apps use a combination: UIKit for the primary chat screen, SDK methods for custom features (reactions, threads, custom cards), and REST API for backend automation.

Why Chat APIs Matter: Build vs. Buy

The Deceptive Complexity of Chat

Chat looks simple on the surface — send a message, receive a message. But production-grade messaging is one of the most challenging distributed systems problems. The edge cases multiply:

  • Message ordering across geographically distributed servers with clock skew
  • Exactly-once delivery despite network partitions, app crashes, and device switches
  • Offline sync — reconstructing state when a user was offline for days across multiple conversations
  • Push notifications across 6+ vendor channels (APNs, FCM, Huawei Push, Xiaomi MiPush, OPPO Push, vivo Push)
  • Media delivery — CDN routing, adaptive transcoding, thumbnail generation, expiration policies
  • Moderation at scale — real-time content filtering that understands context, not just keywords
  • Compliance — GDPR right-to-deletion across replicated storage, HIPAA encryption requirements, data residency mandates
  • Traffic spikes — handling 100x normal load during live events without message loss

Build vs. Buy Decision Matrix

FactorBuild In-HouseManaged Chat API/SDK
Time to market6–12 months (minimum viable)1 day – 2 weeks (production-ready)
Engineering cost3–5 dedicated engineers, $500K–$1M/year$0 at startup scale, $399–$2K/month growing
InfrastructureWebSocket servers, message queues, databases, CDN, push gatewaysFully managed, auto-scaling
Push notificationsIntegrate APNs + FCM + Huawei + Xiaomi + OPPO + vivo separatelySingle toggle, all channels built-in
ScalingRe-architecture at each 10x growth milestoneAutomatic horizontal scaling
MaintenanceOngoing: OS updates, security patches, protocol upgrades, SDK updatesProvider handles all operational burden
ComplianceBuild audit trails, encryption layers, deletion pipelines yourselfCertifications included (SOC2, GDPR)
Global coverageDeploy and maintain edge nodes in multiple regionsProvider's existing global infrastructure

When Building Makes Sense

Building in-house is justified only when:

  1. Chat IS your product — you're building the next Slack, Discord, or WhatsApp
  2. Regulatory constraints prevent any third-party data processing
  3. Protocol-level innovation is your competitive advantage (novel encryption, custom transport)

For the other 95% of applications — where chat is a feature supporting the core product (marketplace, dating, gaming, healthcare, education, e-commerce) — a managed solution eliminates months of undifferentiated engineering.

The Hidden Costs of "Free" Open-Source

Some teams consider open-source messaging (Matrix/Synapse, Ejabberd, Rocket.Chat). While these avoid vendor fees, they introduce:

  • Operational overhead: You run, monitor, scale, and patch servers 24/7
  • Feature gaps: Push notifications, read receipts, typing indicators require custom development
  • Client SDK burden: You build and maintain client libraries for each platform
  • No SLA: Downtime at 2 AM is entirely your problem
  • Hidden compute costs: WebSocket servers are expensive — handling 100K concurrent connections requires significant infrastructure

Total cost of ownership for self-hosted solutions typically exceeds managed services by 3–5x when accounting for engineering time, infrastructure, and opportunity cost.

Core Capabilities of a Production Chat API

Messaging Fundamentals

One-to-One (1v1) Chat

Private conversations between two users. Requirements beyond basic send/receive:

  • Persistent conversation history with server-side storage
  • Online/offline presence awareness
  • Typing indicators with debouncing
  • Message lifecycle status (sending → sent → delivered → read)
  • Message recall within configurable time windows
  • Draft persistence across sessions

Group Chat

Multi-party conversations with varying complexity levels:

Group TypeMembersFeaturesUse Case
Work Group2–200All features, invite-onlyTeams, families, friend groups
Public Group200–10,000Admin-moderated, join requestsCommunities, classrooms
Meeting Group2–300Temporary, auto-dissolveVideo call participants
Live Group10,000–100,000+Broadcast-optimized, limited replyLive streaming chat, events
CommunityUnlimited channelsChannel-based, topic threadingDiscord-style communities

Message Types

Modern chat APIs support rich message formats beyond plain text:

TypeDescriptionTypical Payload
TextPlain or rich text with @mentions, links, formattingString + mention list
ImageCompressed + thumbnail + original resolutionFile + dimensions + thumbnail URL
VideoCompressed + streaming-ready + cover frameFile + duration + cover URL
AudioVoice messages with waveform dataFile + duration + waveform array
FileAny binary with metadataFile + filename + size + MIME type
LocationCoordinates + map previewLat/long + address string + map image
CustomDeveloper-defined JSON payloadArbitrary structured data
MergerCombined forwarded messagesArray of message references
Reply/QuoteMessage with quoted parentParent message ID + reply content

Custom messages are the most powerful — they let you build product cards, order updates, payment requests, polls, interactive cards, and any domain-specific message format your app needs.

Advanced Features

Offline Push Notifications

When users aren't connected via WebSocket, messages must reach them through platform push channels. Comprehensive push coverage requires:

  • Apple Push Notification service (APNs) — all iOS devices
  • Firebase Cloud Messaging (FCM) — most Android devices globally
  • Huawei Push Kit — Huawei devices without Google services
  • Xiaomi MiPush — Xiaomi/Redmi/POCO devices
  • OPPO Push — OPPO/Realme/OnePlus devices
  • vivo Push — vivo/iQOO devices

This matters enormously for global apps. Relying only on APNs + FCM means push notifications simply don't arrive on hundreds of millions of Android devices in China, India, and Southeast Asia where vendor-specific push services are required.

TRTC Chat includes all 6 push channels in every plan — including the free tier.

Read Receipts

Message status progression:

  1. Sending — message queued locally, awaiting network
  2. Sent — server acknowledged receipt
  3. Delivered — recipient device received the message
  4. Read — recipient viewed the message in the chat screen

For group messages, read receipts include aggregated counts (e.g., "Read by 8 of 12 members") with the option to view which specific members have read.

Message Search

Full-text search across conversation history — both local (on-device SQLite) and remote (server-side indexed search). Critical for enterprise and support use cases where users need to find past information quickly.

Message Recall and Edit

Users can unsend or modify messages within configurable time windows:

  • Recall propagates deletion to all recipients
  • Edit updates the message in-place with "edited" indicator
  • Both operations sync to offline devices on reconnection
  • Admins can recall any message in groups they manage

Reactions and Threads

  • Emoji reactions on individual messages (with per-user tracking)
  • Threaded replies creating sub-conversations without cluttering the main timeline
  • Thread notification controls separate from main conversation

Content Moderation

  • Real-time profanity and sensitive word filtering
  • Image classification (NSFW detection, violence, spam)
  • Rate limiting (configurable per-user, per-group message frequency caps)
  • User reporting and blocking workflows
  • Admin tools: mute members, pin messages, set group permissions

User Presence and Typing Indicators

  • Real-time online/offline/away/DND status
  • Typing indicators with automatic timeout
  • Last-seen timestamps
  • Custom status messages with emoji
  • Platform/device indicators (mobile/desktop/web)

Conversation Management

  • Pin important conversations to top
  • Mute notifications per conversation
  • Archive conversations without deleting
  • Unread count badges (total and per-conversation)
  • Conversation-level settings (notification preferences, media auto-download)
  • Conversation groups/folders for organization

How Chat APIs Work: Architecture Deep Dive

Understanding the internal architecture helps you debug integration issues, optimize performance, and make informed technical decisions.

System Architecture

A production chat platform consists of five core subsystems working together:

┌─────────────┐                                    ┌─────────────┐
│  Client A   │         WebSocket/TLS              │  Client B   │
│  (SDK)      │◄──────────────────────────────────►│  (SDK)      │
└──────┬──────┘                                    └──────┬──────┘
       │                                                  │
       ▼                                                  ▼
┌──────────────────────────────────────────────────────────────────┐
│                      Connection Gateway Layer                     │
│  (WebSocket termination, auth validation, load balancing)        │
└──────────────────────────────┬───────────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────────┐
│                       Message Router / Broker                     │
│  (Recipient lookup, online detection, fan-out for groups)        │
└──────────┬────────────────────┬────────────────────┬─────────────┘
           │                    │                    │
           ▼                    ▼                    ▼
┌────────────────┐   ┌──────────────────┐   ┌──────────────────┐
│  Message Store │   │   Sync Engine    │   │  Push Notification│
│  (Persist +    │   │  (Offline queue  │   │  Service (APNs,  │
│   History)     │   │   + sequence     │   │  FCM, Huawei,    │
│                │   │   tracking)      │   │  Xiaomi, OPPO,   │
└────────────────┘   └──────────────────┘   │  vivo)           │
                                            └──────────────────┘

Component Breakdown

1. Connection Gateway

The gateway layer manages persistent WebSocket connections from all clients:

  • TLS termination and certificate management
  • Authentication token validation on connection establishment
  • Connection routing to appropriate backend services
  • Horizontal scaling — each gateway instance handles 100K–500K concurrent connections
  • Geographic distribution for lowest-latency connection paths
  • Heartbeat monitoring and dead connection cleanup

2. Message Router / Broker

The router is the brain of the system:

  • Receives messages from authenticated senders
  • Validates message format and applies rate limits
  • Assigns server-side sequence numbers for ordering guarantees
  • Determines recipients: direct lookup for 1v1, member list expansion for groups
  • Checks recipient online status via gateway registry
  • Online recipients: routes directly through their WebSocket connection
  • Offline recipients: queues for sync engine + triggers push notification

3. Message Store

Handles persistent storage with tiered architecture:

  • Hot tier (Redis/memory): Active conversations, recent messages, presence data — sub-millisecond reads
  • Warm tier (NoSQL — Cassandra/DynamoDB): Message history for the past 30–90 days — single-digit millisecond reads
  • Cold tier (Object storage — S3/COS): Media files, archived messages, compliance archives — optimized for cost over speed
  • Search index (Elasticsearch): Full-text search across message content

Message ordering uses server-assigned monotonically increasing sequence numbers per conversation, ensuring consistent ordering even with clock skew across distributed servers.

4. Push Notification Service

Handles offline message delivery:

  • Maintains device token registry mapping users → devices → push channels
  • Formats push payloads per platform specifications (APNs JSON, FCM data/notification messages)
  • Manages token lifecycle: registration, refresh, invalidation
  • Handles delivery failures with retry logic
  • Respects user preferences: DND schedules, mute settings, notification categories
  • Batches multiple messages into single push payloads for active group conversations

5. Sync Engine

Ensures consistency when clients reconnect:

  • Tracks per-client last-acknowledged sequence number
  • On reconnection: calculates diff between client state and server state
  • Streams missed messages in correct order
  • Resolves conflicts (e.g., message recalled while client was offline)
  • Handles conversation list changes (new groups joined, conversations archived by others)

Message Lifecycle: Complete Flow

When User A sends "Hello" to User B:

  1. Client Asdk.sendMessage("Hello", to: userB) — SDK assigns client-side message ID, shows optimistic UI
  2. SDK serializes message, sends over encrypted WebSocket
  3. Gateway receives, validates auth token, forwards to Router
  4. Router assigns server sequence number, writes to Message Store (acknowledged)
  5. Router checks gateway registry: Is User B connected?
    • Online path: Routes message through User B's WebSocket → Client B SDK receives, fires event → UI updates
    • Offline path: Queues in Sync Engine → triggers Push Notification Service
  6. Push Service looks up User B's device tokens, sends push via appropriate channel (APNs if iOS)
  7. User B opens app → SDK reconnects → Sync Engine sends all messages since last sequence
  8. Client B renders message, marks as read → Router propagates read receipt → Client A receives read status update

Total latency for the online path: typically 50–200ms depending on geographic distance.

Market Landscape: Provider Comparison

The chat API/SDK market has matured significantly. Here's a detailed comparison of the major providers across dimensions that matter for production decisions.

Comprehensive Provider Comparison

DimensionTRTC ChatStreamSendbirdAgora ChatCometChatPubNub
Free Tier1,000 MAU permanentLimited trial100 MAU500 MAU100 MAULimited trial
Starting Price$399/10K MAUContact sales$399/5K MAU (Starter)$349/50K MAU$49/1K MAUContact sales
Overage Cost$0.05/MAU~$0.07/userVaries by plan$0.05/MAUCustom~$0.15/MAU
Concurrency LimitsNone (free tier included)Plan-basedPlan-basedPlan-basedPlan-basedPlan-based
PlatformsWeb, iOS, Android, Flutter, RN, Unity, Unreal, Electron, macOS, WindowsWeb, iOS, Android, Flutter, RNWeb, iOS, Android, Flutter, RN, UnityWeb, iOS, Android, Flutter, RN, UnityWeb, iOS, Android, Flutter, RN, IonicWeb, iOS, Android, Flutter, RN
Platform Count1056665
UIKitYes (5 min)YesYesYesYesNo
Push ChannelsAPNs + FCM + Huawei + Xiaomi + OPPO + vivoAPNs + FCMAPNs + FCMAPNs + FCM + HuaweiAPNs + FCMAPNs + FCM
SDK Size (Android)~1,670 KB~3,200 KB~4,500 KB~2,800 KB~3,100 KB~1,900 KB
SDK Size (iOS)~1,805 KB~3,500 KB~5,200 KB~3,000 KB~3,400 KB~2,100 KB
Max Group Size100,000+5,000100,0003,000 default100,000Unlimited channels
Message HistoryUnlimited (stored)30 days (Starter)Plan-dependentPlan-dependentPlan-dependent30 days default
MCP IntegrationYes (@tencent-rtc/mcp@latest)NoNoNoNoNo
E2E EncryptionAvailableAvailableAvailableAvailableAvailableAvailable
Audio/Video IntegrationNative (same platform)Third-partyThird-partyNative (Agora RTC)Third-partyThird-party

Key Differentiators by Provider

TRTC Chat (by Tencent RTC) stands out for:

  • Most generous permanent free tier — 1,000 MAU with zero concurrency limits and full push support
  • Broadest platform coverage — 10 platforms including Unity, Unreal, Electron, macOS, Windows
  • Smallest SDK footprint — ~1.7 MB Android, ~1.8 MB iOS
  • Most comprehensive push — 6 channels covering Chinese Android vendors
  • MCP integration — AI-assisted development with @tencent-rtc/mcp@latest
  • Native audio/video — chat + calling from the same vendor, same SDK initialization

Stream (GetStream) is popular for its polished React/SwiftUI components and extensive documentation. However, pricing is opaque (contact sales required), and their model charges overage at $0.07/user with concurrent connection limits at $0.79/concurrent user over quota.

Sendbird has strong enterprise features (translation, moderation, analytics dashboard) but carries the largest SDK size (~4.5 MB Android, ~5.2 MB iOS) and costs escalate quickly — $399/month for just 5K MAU at the Starter tier.

Agora Chat benefits from native integration with Agora's real-time audio/video infrastructure. Good choice if you're already using Agora for calling and want a single vendor. Starting at $349/50K MAU makes it competitive for higher-scale apps.

CometChat offers straightforward developer experience with the lowest entry price ($49/1K MAU) but features are more limited at lower tiers.

PubNub is fundamentally a pub/sub messaging infrastructure rather than a purpose-built chat solution. Powerful and flexible but requires significantly more development effort to build chat features that other SDKs provide out of the box.

How to Integrate: Three Approaches

Integration complexity varies dramatically based on your chosen approach. Here's what each path looks like with TRTC Chat.

Approach 1: UIKit — 5 Minutes to Working Chat

The UIKit gives you a complete, themed chat interface with minimal code. TRTC's Chat UIKit provides:

  • Conversation list with avatars, last message preview, unread badges, and timestamps
  • Message view with bubbles, delivery status, timestamps, and media previews
  • Input bar with text, emoji, voice recording, image picker, video, and file attachment
  • Group management: create, invite, mute, pin, leave
  • User profile cards with presence indicators

React (Web) — Complete Setup:

npm install @tencentcloud/chat-uikit-react
import React from 'react';
import { ChatApp } from '@tencentcloud/chat-uikit-react';
import '@tencentcloud/chat-uikit-react/dist/cjs/index.css';

function App() {
  return (
    <ChatApp
      SDKAppID={1400000000} // Your SDKAppID from TRTC Console
      userid='user_001'
      userSig={generatedUserSig} // Generated server-side
    />
  );
}

export default App;

That's the entire integration. You now have a full-featured chat application with conversation management, real-time messaging, media sharing, and group creation.

Flutter — Complete Setup:

# pubspec.yaml
dependencies:
  tencent_cloud_chat_uikit: ^2.0.0
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';

class ChatScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return TIMUIKitChat(
      sdkAppID: 1400000000,
      userID: 'user_001',
      userSig: generatedUserSig,
    );
  }
}

When UIKit is the right choice:

  • You want to validate chat as a feature quickly (MVP/prototype)
  • Standard chat UX is acceptable for your use case
  • Design resources are limited or allocated elsewhere
  • You plan to customize appearance (theming) but not interaction patterns

Approach 2: SDK — 30 Minutes to Custom Chat

The SDK gives you full control over the UI while Tencent RTC manages all infrastructure. You build your own interface and call SDK methods for chat operations.

Step 1: Install the SDK

# Web (npm)
npm install @tencentcloud/chat

# iOS (CocoaPods)
pod 'TXIMSDK_Plus_iOS'

# Android (Gradle)
implementation 'com.tencent.imsdk:imsdk-plus:7.9.5668'

# Flutter
flutter pub add tencent_cloud_chat_sdk

# React Native
npm install react-native-tim-js

Step 2: Initialize and Login

import TencentCloudChat from '@tencentcloud/chat';

// Create SDK instance (singleton)
const chat = TencentCloudChat.create({
  SDKAppID: 1400000000, // From TRTC Console
});

// Set log level (use 4 in production to reduce noise)
chat.setLogLevel(1); // 0=verbose, 1=debug, 2=info, 3=warn, 4=error

// Login with server-generated userSig
async function login(userID, userSig) {
  try {
    const { data } = await chat.login({ userID, userSig });
    console.log('Login success, repeat login:', data.repeatLogin);
  } catch (error) {
    console.error('Login failed:', error.code, error.message);
  }
}

await login('developer_01', serverGeneratedUserSig);

Step 3: Register Event Listeners

// SDK ready — safe to call data-fetching APIs
chat.on(TencentCloudChat.EVENT.SDK_READY, () => {
  console.log('SDK ready — fetch conversations and messages now');
  loadConversations();
});

// New messages received
chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, (event) => {
  const newMessages = event.data;
  newMessages.forEach((msg) => {
    switch (msg.type) {
      case TencentCloudChat.TYPES.MSG_TEXT:
        renderTextMessage(msg.from, msg.payload.text, msg.time);
        break;
      case TencentCloudChat.TYPES.MSG_IMAGE:
        renderImageMessage(msg.from, msg.payload.imageInfoArray[1].url, msg.time);
        break;
      case TencentCloudChat.TYPES.MSG_CUSTOM:
        const customData = JSON.parse(msg.payload.data);
        renderCustomMessage(msg.from, customData, msg.time);
        break;
    }
  });
});

// Conversation list updated (unread counts, last messages)
chat.on(TencentCloudChat.EVENT.CONVERSATION_LIST_UPDATED, (event) => {
  updateConversationListUI(event.data);
});

// Read receipts for sent messages
chat.on(TencentCloudChat.EVENT.MESSAGE_READ_BY_PEER, (event) => {
  event.data.forEach((msg) => {
    updateMessageStatus(msg.ID, 'read');
  });
});

// Network state changes
chat.on(TencentCloudChat.EVENT.NET_STATE_CHANGE, (event) => {
  const { state } = event.data;
  if (state === TencentCloudChat.TYPES.NET_STATE_CONNECTED) {
    showConnectionStatus('connected');
  } else if (state === TencentCloudChat.TYPES.NET_STATE_CONNECTING) {
    showConnectionStatus('reconnecting');
  } else {
    showConnectionStatus('disconnected');
  }
});

Step 4: Send Messages

// Send text message
async function sendText(toUserID, text) {
  const message = chat.createTextMessage({
    to: toUserID,
    conversationType: TencentCloudChat.TYPES.CONV_C2C, // 1v1
    payload: { text },
  });
  
  // Optimistic UI: show immediately with "sending" status
  renderOutgoingMessage(message);
  
  try {
    const { data } = await chat.sendMessage(message);
    updateMessageStatus(data.message.ID, 'sent');
  } catch (error) {
    updateMessageStatus(message.ID, 'failed');
    console.error('Send failed:', error.code, error.message);
  }
}

// Send image message
async function sendImage(toUserID, file) {
  const message = chat.createImageMessage({
    to: toUserID,
    conversationType: TencentCloudChat.TYPES.CONV_C2C,
    payload: { file }, // File object from input[type=file]
    onProgress: (percent) => {
      updateUploadProgress(message.ID, percent);
    },
  });
  
  await chat.sendMessage(message);
}

// Send custom message (e.g., product card, order update)
async function sendProductCard(toUserID, product) {
  const message = chat.createCustomMessage({
    to: toUserID,
    conversationType: TencentCloudChat.TYPES.CONV_C2C,
    payload: {
      data: JSON.stringify({
        type: 'product_card',
        productId: product.id,
        title: product.title,
        price: product.price,
        imageUrl: product.imageUrl,
        actionUrl: product.url,
      }),
      description: `Product: ${product.title}`,
      extension: '',
    },
  });
  
  await chat.sendMessage(message);
}

// Send message to a group
async function sendGroupText(groupID, text) {
  const message = chat.createTextMessage({
    to: groupID,
    conversationType: TencentCloudChat.TYPES.CONV_GROUP,
    payload: { text },
  });
  
  await chat.sendMessage(message);
}

Step 5: Group Management

// Create a work group (invite-only)
async function createTeamGroup(name, memberIDs) {
  const { data } = await chat.createGroup({
    type: TencentCloudChat.TYPES.GRP_WORK,
    name: name,
    introduction: 'Created via TRTC Chat SDK',
    memberList: memberIDs.map(id => ({ userID: id })),
  });
  
  console.log('Group created:', data.group.groupID);
  return data.group.groupID;
}

// Join a public group
async function joinGroup(groupID) {
  await chat.joinGroup({ groupID });
}

// Get group member list
async function getMembers(groupID) {
  const { data } = await chat.getGroupMemberList({
    groupID,
    count: 50,
    offset: 0,
  });
  return data.memberList;
}

// Set group admin
async function setAdmin(groupID, userID) {
  await chat.setGroupMemberRole({
    groupID,
    userID,
    role: TencentCloudChat.TYPES.GRP_MBR_ROLE_ADMIN,
  });
}

Step 6: Message History and Conversation List

// Get conversation list (paginated)
async function loadConversations(cursor = '') {
  const { data } = await chat.getConversationList({
    count: 20,
    cursor: cursor,
  });
  
  data.conversationList.forEach((conv) => {
    renderConversation({
      id: conv.conversationID,
      name: conv.userProfile?.nick || conv.groupProfile?.name,
      avatar: conv.userProfile?.avatar || conv.groupProfile?.avatar,
      lastMessage: conv.lastMessage?.messageForShow,
      unreadCount: conv.unreadCount,
      timestamp: conv.lastMessage?.lastTime,
    });
  });
  
  if (!data.isCompleted) {
    // More conversations available — load on scroll
    return data.nextCursor;
  }
}

// Get message history for a conversation (paginated, reverse chronological)
async function loadMessages(conversationID, lastMessageID = '') {
  const { data } = await chat.getMessageList({
    conversationID: conversationID, // e.g., "C2Cuser_002" or "GROUPgroup_001"
    count: 30,
    nextReqMessageID: lastMessageID,
  });
  
  // Messages are in chronological order
  data.messageList.forEach((msg) => {
    renderMessage(msg);
  });
  
  return data.nextReqMessageID; // For loading more
}

Approach 3: REST API — Server-Side Integration

The REST API handles backend operations: system notifications, chatbot messages, user management, data export, and admin actions.

Send a System Notification:

curl -X POST \
  "https://console.tim.qq.com/v4/openim/sendmsg?sdkappid=${SDKAPPID}&identifier=admin&usersig=${ADMIN_USERSIG}&contenttype=json" \
  -H "Content-Type: application/json" \
  -d '{
    "SyncOtherMachine": 2,
    "From_Account": "system_notification",
    "To_Account": "user_001",
    "MsgLifeTime": 604800,
    "MsgBody": [{
      "MsgType": "TIMTextElem",
      "MsgContent": {
        "Text": "Your order #ORD-2026-8834 has shipped! Estimated delivery: May 30."
      }
    }]
  }'

Import User Accounts (Batch):

curl -X POST \
  "https://console.tim.qq.com/v4/im_open_login_svc/multiaccount_import?sdkappid=${SDKAPPID}&identifier=admin&usersig=${ADMIN_USERSIG}&contenttype=json" \
  -H "Content-Type: application/json" \
  -d '{
    "Accounts": ["user_001", "user_002", "user_003", "user_004", "user_005"]
  }'

Common REST API Use Cases:

  • System notifications (order updates, payment confirmations, appointment reminders)
  • Chatbot message injection (AI responses, automated workflows)
  • Bulk user import during migration from another provider
  • Message history export for compliance/analytics
  • Admin operations (mute user, dissolve group, set attributes)
  • Webhook callbacks for real-time analytics pipelines

Integration Approach Summary

AspectUIKitClient SDKREST API
Time to production5–30 minutes2 hours – 2 weeksHours – days
UI ownershipProvider (themed)Fully customN/A (backend only)
PlatformsWeb, iOS, Android, FlutterAll 10 platformsAny HTTP client
Real-time deliveryBuilt-inWebSocket eventsWebhook callbacks
Offline supportBuilt-inSDK cache layerN/A
Ideal use caseStandard chat UXCustom chat UXBackend automation

Best Practices for Production Chat

Message Reliability

Problem: Messages can be lost to network failures, app crashes, or server issues.

Solution — Client-Side Retry with Deduplication:

async function sendWithRetry(message, maxAttempts = 3) {
  // 1. Show immediately in UI (optimistic)
  addToUI(message, { status: 'sending' });
  
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      const result = await chat.sendMessage(message);
      updateStatus(message.ID, 'sent');
      return result;
    } catch (error) {
      if (attempt === maxAttempts) {
        updateStatus(message.ID, 'failed');
        // Show retry button in UI
        enableRetryButton(message.ID);
        throw error;
      }
      // Exponential backoff: 1s, 2s, 4s
      await new Promise(r => setTimeout(r, 1000 * Math.pow(2, attempt - 1)));
    }
  }
}

The SDK already handles deduplication via client-assigned message IDs — retrying the same message won't create duplicates on the server.

Solution — Sequence-Based Sync:

Track the last received server sequence number locally. On every reconnection, the SDK automatically requests all messages after that sequence — guaranteeing no gaps in conversation history.

Push Notification Strategy

Do:

  • Register push tokens on every app launch (tokens rotate unpredictably)
  • Include sender name + message preview in push payload
  • Use notification categories (iOS) / channels (Android) for user control
  • Respect device DND settings server-side
  • Clean up invalid tokens from push delivery failure callbacks
  • Support all relevant vendor channels for your target market

Don't:

  • Send push when the user has the app in foreground (the SDK handles this)
  • Include sensitive content in lock-screen-visible push payloads
  • Send individual pushes for every message in active group conversations (batch into "3 new messages in Project Chat")
  • Ignore push registration failures (retry with backoff)

Badge Management:

// Track total unread count for app badge
chat.on(TencentCloudChat.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, (event) => {
  const totalUnread = event.data;
  // iOS: set badge number
  // Android: update notification badge
  updateAppBadge(totalUnread);
});

Security Best Practices

1. Server-Side UserSig Generation (Mandatory)

UserSig is the authentication token that proves a user's identity. Generate it exclusively on your backend:

// Server-side (Node.js) — CORRECT
const TLSSigAPIv2 = require('tls-sig-api-v2');

const SDKAppID = 1400000000;
const secretKey = process.env.TRTC_SECRET_KEY; // From environment, never hardcoded

function generateUserSig(userID, expireSeconds = 604800) {
  const api = new TLSSigAPIv2.Api(SDKAppID, secretKey);
  return api.genUserSig(userID, expireSeconds); // 7-day default expiry
}

// Expose via authenticated endpoint
app.post('/api/chat/token', authMiddleware, (req, res) => {
  const userSig = generateUserSig(req.user.id);
  res.json({ userSig, expiresIn: 604800 });
});

Never include secretKey in client code, JavaScript bundles, or version control.

2. Rate Limiting

Configure per-user message rate limits to prevent abuse:

  • 1v1 conversations: 10 messages/second
  • Group messages: 5 messages/second per user
  • System messages: configurable based on use case

3. Content Moderation

Enable server-side content filtering:

  • Custom word blacklists
  • Regex pattern matching (phone numbers, URLs)
  • Image moderation via AI classification
  • Callback URLs for custom moderation logic

4. Access Control

Implement granular group permissions:

  • Who can invite/remove members
  • Who can send messages (all members vs. admins only)
  • Who can pin/recall messages
  • Who can modify group profile
  • Role hierarchy: Owner > Admin > Member

Scalability Patterns

Conversation List Pagination:

// Load 20 conversations at a time, more on scroll
let cursor = '';
async function loadMore() {
  const { data } = await chat.getConversationList({ count: 20, cursor });
  cursor = data.nextCursor;
  renderConversations(data.conversationList);
  return !data.isCompleted; // true if more available
}

Large Group Optimization:

  • Disable individual read receipts for groups with 100+ members
  • Use message priorities to drop non-essential messages under load
  • Implement member list lazy loading (load first 50, then on scroll)
  • Consider splitting very active large groups into topic-based channels

How to Choose the Right Chat API

Selection Framework (Weighted Scoring)

Score each provider on five dimensions:

1. Feature Completeness (Weight: 30%)

  • All message types you need (text, media, custom, reactions, threads)
  • Group chat capabilities and size limits
  • Advanced features: search, moderation, translation, threads
  • Audio/video calling integration (if needed alongside chat)

2. Pricing and Scale Economics (Weight: 25%)

  • Free tier generosity (important for validation phase)
  • Cost trajectory as you grow from 1K to 100K MAU
  • Hidden costs: media storage, push notifications, moderation, history retention
  • Concurrency limits and overage penalties

3. Platform Coverage (Weight: 20%)

  • SDKs for all your target platforms
  • Maintenance frequency and update cadence
  • UIKit availability for rapid development
  • Game engine support (Unity/Unreal) if applicable

4. SDK Quality (Weight: 15%)

  • Binary size impact on app download size
  • Memory usage and battery consumption in background
  • Documentation quality, code samples, migration guides
  • Release frequency and bug response time

5. Support and Ecosystem (Weight: 10%)

  • Technical support response time and channels
  • Community resources (forums, Stack Overflow, Discord)
  • Migration tools from other providers
  • Compliance certifications (SOC2, HIPAA, GDPR, ISO 27001)

Decision Flowchart

Ask these questions sequentially — each narrows your options:

What platforms do you target? If you need Unity, Unreal, Electron, or desktop native → TRTC (broadest coverage at 10 platforms) and Agora (6 platforms) are your short list.

What's your target geographic market? If serving users in China, India, Southeast Asia → you need Huawei/Xiaomi/OPPO/vivo push. TRTC is the strongest choice here.

What's your current/projected scale? Under 1,000 MAU → use TRTC's free tier (most generous). Under 10K → compare standard plans. Over 100K → negotiate enterprise agreements.

How sensitive is app size? For lightweight utility apps, dating apps, fitness apps → SDK size matters. TRTC at ~1.7 MB is the smallest. Sendbird at ~4.5 MB adds noticeably to download size.

Do you need AI/MCP integration? If building AI-powered features or using AI coding assistants → TRTC's MCP support enables AI-assisted development workflow.

Red Flags When Evaluating

  • No published pricing → usually means expensive and unpredictable
  • Free tier with time limits → not truly free, creates pressure to decide before you're ready
  • Concurrent connection caps on paid plans → penalizes growth and user engagement
  • SDK not updated in 6+ months → likely maintenance-mode or deprioritized
  • No WebSocket support → polling only = poor real-time UX
  • Media locked in provider infrastructure with no export → vendor lock-in risk

Pricing Models Explained

Chat API pricing varies significantly between providers. Understanding the models helps you predict costs and avoid surprises.

Model 1: MAU-Based (Monthly Active Users)

How it works: Pay based on unique users who connect to chat at least once per billing month.

Pros: Predictable costs tied to actual engagement. Simple to budget. Scales linearly.

Cons: "Active" definition varies between providers. A user who sends 1 message costs the same as one who sends 1,000.

TRTC Chat pricing:

  • Free: 1,000 MAU (permanent, no credit card required, no time limit)
  • Standard: $399/month includes 10,000 MAU
  • Overage: $0.05 per additional MAU
  • No concurrency limits at any tier
  • Push notifications included (all 6 channels)
  • Media storage included

Model 2: Message Volume

How it works: Pay per message processed through the system.

Pros: Low-activity apps pay very little. Directly tied to infrastructure load.

Cons: Unpredictable costs during viral moments or marketing campaigns. Penalizes engagement — the better your chat feature works, the more it costs. A 10,000-member group with 100 messages/day = 1M messages/day = potentially thousands in daily costs.

Model 3: Concurrent Connections

How it works: Pay based on peak simultaneous WebSocket connections.

Pros: Tied to actual infrastructure load. Predictable for steady-state apps.

Cons: Spiky apps (live events, flash sales) face massive overage charges. Global apps with users across time zones have structurally higher peaks. Hard to forecast for budgeting.

Cost Scenario Analysis

ScenarioTRTC ChatSendbirdStreamAgora Chat
500 MAU (pre-launch)$0~$49/moContact sales$0
5,000 MAU (early growth)$0–$399/mo~$399/mo (Starter)Contact sales$0 (within 50K)
15,000 MAU (scaling)$399 + $250 overage = $649/mo~$599/mo (Pro)Custom quote$349/mo (within 50K)
50,000 MAU (growth stage)Enterprise (contact)Enterprise (contact)Enterprise$349 + overage
100,000+ MAU (scale)EnterpriseEnterpriseEnterpriseEnterprise

Hidden Cost Checklist

Before committing to any provider, ask about:

AI Chat Agents

The most significant shift in messaging is the integration of AI agents directly into conversation flows. This goes far beyond simple keyword-matching chatbots:

  • Contextual AI assistants: Agents that understand full conversation history, user preferences, and business context to provide relevant suggestions, translations, or actions
  • AI-powered moderation: Context-aware content analysis that understands nuance (sarcasm, code snippets, medical terminology) rather than just keyword matching
  • Smart replies and auto-complete: Context-aware response suggestions that learn from user communication patterns
  • Conversational commerce: AI agents handling purchases, bookings, support tickets, and complex workflows within chat threads — no app switching required

TRTC Chat supports AI integration through webhook callbacks (server receives all messages for AI processing) and the MCP framework for bidirectional AI interaction.

MCP (Model Context Protocol) Integration

MCP is emerging as the standard protocol for AI model interaction with external tools and data sources. TRTC's @tencent-rtc/mcp@latest package enables:

  • AI coding assistants that understand TRTC's complete API surface
  • Automated code generation with correct method signatures, parameter types, and error handling
  • AI-assisted debugging with knowledge of error codes, rate limits, and common integration pitfalls
  • Development workflow acceleration — describe what you want in natural language, get working integration code

Setup for AI-assisted development (Cursor / VS Code / Claude Code):

{
  "mcpServers": {
    "tencent-rtc": {
      "command": "npx",
      "args": ["-y", "@tencent-rtc/mcp@latest"],
      "env": {
        "SDKAPPID": "YOUR_SDKAPPID",
        "SECRETKEY": "YOUR_SECRET_KEY"
      }
    }
  }
}

Example prompts for AI-assisted integration:

  • "Add real-time group chat to my React app with message history and typing indicators"
  • "Create a customer support chat widget with file upload and message search"
  • "Build a notification system that sends order updates via TRTC Chat REST API"

The MCP server provides the AI assistant with complete API documentation context, ensuring generated code uses real method signatures — no hallucinated APIs.

End-to-End Encryption (E2EE)

Driven by privacy regulations (GDPR, CCPA) and user demand:

  • Signal Protocol adoption: More providers implementing proven encryption protocols
  • Key transparency: Public audit logs proving encryption keys haven't been tampered with
  • Group E2EE: Extending beyond 1v1 to encrypted group conversations (technically challenging due to key distribution across many devices)
  • Compliance-compatible E2EE: Enabling strong encryption while meeting legal interception requirements through key escrow or designated verifier schemes

Multi-Modal and Interactive Messages

Chat evolving beyond text + media:

  • Interactive cards: Messages containing forms, buttons, carousels, date pickers — mini-applications within messages
  • Live objects: Messages that update in real-time (delivery tracking, stock prices, collaborative editing cursors)
  • Voice-first: Async voice messages with AI transcription, translation, and searchability
  • Spatial/AR messages: Location-anchored messages for AR experiences and metaverse interactions

Edge Computing and Ultra-Low Latency

  • Edge message processing: Routing and delivery at CDN edge nodes for sub-50ms latency
  • Offline-first architecture: Full functionality without network connectivity, seamless conflict resolution on reconnection
  • WebTransport protocol: Next-generation transport replacing WebSocket for lower latency, better multiplexing, and native QUIC support

Getting Started: TRTC Chat Step-by-Step Tutorial

Here's a complete tutorial to go from zero to sending your first real-time message with TRTC Chat.

Prerequisites

  • A Tencent RTC account (sign up free — no credit card required)
  • Your SDKAppID and SecretKey from the TRTC Console
  • Node.js 16+ installed (for this Web tutorial)

Step 1: Create Your Application

  1. Sign up at trtc.io — your free tier includes 1,000 MAU permanently
  2. Navigate to the Console and create a new Chat application
  3. Copy your SDKAppID (a numeric identifier like 1400000000)
  4. Copy your SecretKey (used server-side to generate authentication tokens)

Step 2: Set Up the Project

mkdir trtc-chat-quickstart && cd trtc-chat-quickstart
npm init -y
npm install @tencentcloud/chat
npm install tls-sig-api-v2  # UserSig generation (dev/testing only)

Step 3: Generate UserSig (Development Only)

Security: In production, generate UserSig on your authenticated backend. Never ship SecretKey in client code.

// utils/generateUserSig.js
const TLSSigAPIv2 = require('tls-sig-api-v2');

const SDKAppID = 1400000000; // Replace with your SDKAppID
const secretKey = 'your-secret-key-here'; // Replace — NEVER commit this

function generateUserSig(userID, expireSeconds = 604800) {
  const api = new TLSSigAPIv2.Api(SDKAppID, secretKey);
  return api.genUserSig(userID, expireSeconds);
}

module.exports = { generateUserSig, SDKAppID };

Step 4: Initialize, Login, and Listen

// app.js
import TencentCloudChat from '@tencentcloud/chat';
import { generateUserSig, SDKAppID } from './utils/generateUserSig.js';

// 1. Create instance
const chat = TencentCloudChat.create({ SDKAppID });
chat.setLogLevel(2); // Info level

// 2. Register event listeners BEFORE login
chat.on(TencentCloudChat.EVENT.SDK_READY, () => {
  console.log('✓ SDK ready — you can now send and receive messages');
});

chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, (event) => {
  event.data.forEach((msg) => {
    if (msg.type === TencentCloudChat.TYPES.MSG_TEXT) {
      console.log(`[${msg.nick || msg.from}]: ${msg.payload.text}`);
    }
  });
});

chat.on(TencentCloudChat.EVENT.NET_STATE_CHANGE, (event) => {
  console.log('Network state:', event.data.state);
});

// 3. Login
const userID = 'quickstart_user_01';
const userSig = generateUserSig(userID);

const loginResult = await chat.login({ userID, userSig });
console.log('Login result:', loginResult.data);

Step 5: Send Your First Message

// Send a 1v1 text message
async function sendFirstMessage() {
  const message = chat.createTextMessage({
    to: 'quickstart_user_02', // Recipient userID
    conversationType: TencentCloudChat.TYPES.CONV_C2C,
    payload: {
      text: 'Hello from TRTC Chat! This is my first message.',
    },
  });

  try {
    const { data } = await chat.sendMessage(message);
    console.log('✓ Message sent! ID:', data.message.ID);
    console.log('  Server time:', new Date(data.message.time * 1000));
  } catch (error) {
    console.error('✗ Send failed:', error.code, error.message);
  }
}

await sendFirstMessage();

Step 6: Create a Group and Send Group Messages

// Create a group with initial members
async function createAndChat() {
  // Create work group (invite-only, persistent)
  const { data: groupData } = await chat.createGroup({
    type: TencentCloudChat.TYPES.GRP_WORK,
    name: 'Quickstart Team',
    introduction: 'Testing TRTC Chat group messaging',
    memberList: [
      { userID: 'quickstart_user_02' },
      { userID: 'quickstart_user_03' },
    ],
  });

  const groupID = groupData.group.groupID;
  console.log('✓ Group created:', groupID);

  // Send a message to the group
  const groupMessage = chat.createTextMessage({
    to: groupID,
    conversationType: TencentCloudChat.TYPES.CONV_GROUP,
    payload: { text: 'Welcome everyone! Group chat is working.' },
  });

  await chat.sendMessage(groupMessage);
  console.log('✓ Group message sent!');
}

await createAndChat();

Step 7: Fetch Conversation List and History

// Get all conversations
async function listConversations() {
  const { data } = await chat.getConversationList({ count: 20 });
  
  console.log(`\n📋 ${data.conversationList.length} conversations:`);
  data.conversationList.forEach((conv) => {
    const name = conv.userProfile?.nick || conv.groupProfile?.name || conv.conversationID;
    const lastMsg = conv.lastMessage?.messageForShow || '(no messages)';
    const unread = conv.unreadCount;
    console.log(`  ${unread > 0 ? `[${unread}]` : '   '} ${name}: ${lastMsg}`);
  });
}

// Get message history for a specific conversation
async function getHistory(conversationID) {
  const { data } = await chat.getMessageList({
    conversationID,
    count: 15,
  });
  
  console.log(`\n💬 Last ${data.messageList.length} messages:`);
  data.messageList.forEach((msg) => {
    const time = new Date(msg.time * 1000).toLocaleTimeString();
    const content = msg.payload.text || `[${msg.type}]`;
    console.log(`  [${time}] ${msg.from}: ${content}`);
  });
}

await listConversations();
await getHistory('C2Cquickstart_user_02');

Step 8: Mark Messages as Read

// Mark a conversation as read (clears unread badge)
async function markRead(conversationID) {
  await chat.setMessageRead({ conversationID });
  console.log('✓ Conversation marked as read:', conversationID);
}

Step 9: Clean Up

// Logout gracefully
async function cleanup() {
  await chat.logout();
  console.log('✓ Logged out');
  chat.destroy();
  console.log('✓ SDK instance destroyed');
}

Complete Working Web Demo

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>TRTC Chat Demo</title>
  <style>
    body { font-family: system-ui; max-width: 600px; margin: 2rem auto; }
    #messages { height: 400px; overflow-y: auto; border: 1px solid #ddd; padding: 1rem; }
    .msg { margin: 0.5rem 0; }
    .msg-me { text-align: right; color: #0066cc; }
    .msg-them { text-align: left; color: #333; }
    #input-area { display: flex; gap: 0.5rem; margin-top: 1rem; }
    #input-area input { flex: 1; padding: 0.5rem; }
    #input-area button { padding: 0.5rem 1rem; }
  </style>
</head>
<body>
  <h2>TRTC Chat Quick Demo</h2>
  <div id='messages'></div>
  <div id='input-area'>
    <input id='msg-input' placeholder="Type a message..." />
    <button onclick="send()">Send</button>
  </div>

  <script type="module">
    import TencentCloudChat from 'https://cdn.jsdelivr.net/npm/@tencentcloud/chat/index.mjs';

    const SDKAppID = 1400000000; // Replace
    const userID = 'demo_user_01';
    const userSig = 'YOUR_USER_SIG'; // Generate server-side
    const recipientID = 'demo_user_02';

    const chat = TencentCloudChat.create({ SDKAppID });
    await chat.login({ userID, userSig });

    chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, (e) => {
      e.data.forEach(msg => {
        if (msg.type === TencentCloudChat.TYPES.MSG_TEXT) {
          addMessage(msg.from, msg.payload.text, 'them');
        }
      });
    });

    function addMessage(from, text, type) {
      const div = document.createElement('div');
      div.className = `msg msg-${type}`;
      div.textContent = `${from}: ${text}`;
      document.getElementById('messages').appendChild(div);
      div.scrollIntoView();
    }

    window.send = async () => {
      const input = document.getElementById('msg-input');
      const text = input.value.trim();
      if (!text) return;

      const message = chat.createTextMessage({
        to: recipientID,
        conversationType: TencentCloudChat.TYPES.CONV_C2C,
        payload: { text },
      });

      await chat.sendMessage(message);
      addMessage('Me', text, 'me');
      input.value = '';
    };

    document.getElementById('msg-input').addEventListener('keydown', (e) => {
      if (e.key === 'Enter') window.send();
    });
  </script>
</body>
</html>

Accelerate Integration with MCP

Instead of reading documentation page by page, use Tencent Cloud's MCP server to let your AI coding assistant generate integration code directly:

Setup (Cursor / VS Code / Claude Code):

{
  "mcpServers": {
    "tencent-rtc": {
      "command": "npx",
      "args": ["-y", "@tencent-rtc/mcp@latest"],
      "env": {
        "SDKAPPID": "YOUR_SDKAPPID",
        "SECRETKEY": "YOUR_SECRET_KEY"
      }
    }
  }
}

Example prompts you can use:

  • "Add real-time chat with message history to my React Native app"
  • "Create a group chat feature with admin controls and moderation"
  • "Build a customer support chat widget with file uploads and typing indicators"
  • "Migrate my existing Firebase chat to TRTC Chat SDK"

The MCP server has access to all TRTC SDK documentation and generates working code with correct API signatures — no hallucinated methods or outdated parameters.

For complete API reference and platform-specific guides, see the TRTC Chat SDK documentation.

Frequently Asked Questions

Q1: What exactly is a chat API and how is it different from a chat SDK?

A chat API is a set of server-side endpoints (REST or WebSocket) that handle message routing, storage, and delivery between users. A chat SDK is a client-side library that wraps the API into platform-native code with additional features: connection management, local caching, event handling, media compression, and push token registration. The API is the engine; the SDK is the car that makes the engine usable from your mobile or web app.

Q2: Can I use a chat API completely free?

Yes. TRTC Chat offers a permanent free tier with 1,000 MAU, no concurrency limits, and push notifications across all 6 vendor channels — Free Chat API. This isn't a trial; it never expires and requires no credit card. Other providers offer smaller free tiers (100–500 MAU) or time-limited trials that expire after 30 days.

Q3: How long does it take to add chat to an existing app?

With UIKit: 5 minutes to a fully working chat interface (conversation list + messaging). With SDK (custom UI): 30 minutes to 2 hours for basic messaging, 1–2 weeks for a polished production experience with all edge cases handled. Building from scratch: 6–12 months for a team of 3–5 engineers.

Q4: How do chat APIs handle users who are offline?

When a recipient is offline, messages are: (1) stored on the server, (2) queued in the sync engine with a sequence number, and (3) a push notification is triggered via APNs/FCM/vendor channels. When the user opens the app, the SDK automatically syncs all missed messages from the server using sequence-number-based reconciliation — guaranteeing no gaps.

Q5: WebSocket vs REST API — when to use which for chat?

WebSocket provides persistent bidirectional connections — essential for real-time message delivery to clients (instant message receipt, typing indicators, presence updates). REST API is request-response — ideal for server-side operations (sending system notifications, bot messages, admin actions, bulk imports, analytics queries). Most implementations use both: WebSocket for the client experience, REST API for backend automation.

Q6: How do chat APIs scale to millions of concurrent users?

Through: (1) horizontal scaling of connection gateway servers (each handling 100K–500K connections), (2) message partitioning by conversation ID for write parallelism, (3) geographic distribution of edge nodes for low latency, (4) tiered storage (hot/warm/cold) for cost-efficient history, and (5) automatic backpressure during traffic spikes. Managed providers handle all of this — you don't provision or manage any infrastructure.

Q7: How difficult is migrating between chat providers?

Migration complexity depends on integration depth. Key steps: (1) export message history via REST API (most providers support this), (2) map user IDs between systems, (3) recreate groups/channels with membership, (4) swap the client SDK, (5) run parallel systems during transition. If you built custom UI (SDK approach), the UI layer stays intact — only the SDK calls change. Plan 2–4 weeks for a production migration with testing.

Q8: How do I secure chat messages in my application?

Layer your security: (1) TLS 1.3 for all transit encryption (mandatory, handled by SDK), (2) server-side UserSig authentication with short token expiry, (3) content moderation filters for spam and abuse, (4) per-user rate limiting, (5) role-based access control for group operations, and (6) optionally end-to-end encryption for sensitive conversations. Critical rule: generate UserSig exclusively on your server — never expose your SecretKey in client code.

Q9: What is MCP and why should I care as a chat developer?

MCP (Model Context Protocol) is a standard enabling AI models to interact with external tools and APIs with full context. TRTC's @tencent-rtc/mcp@latest package lets AI coding assistants (Claude, Cursor, GitHub Copilot) understand the entire Chat API surface — generating accurate integration code, suggesting optimal patterns, and debugging issues without hallucinating nonexistent methods. It dramatically accelerates development for teams using AI-assisted coding workflows.

Q10: MAU-based vs message-based pricing — which is better?

MAU-based is more predictable and better for engagement-focused apps. You pay per active user regardless of message volume, meaning you're not penalized when users chat frequently (which is the behavior you want to encourage). Message-based is cheaper for low-activity apps but creates unpredictable bills during traffic spikes (viral moments, live events, marketing campaigns). For most consumer and enterprise apps, MAU-based pricing is safer to budget and better aligned with your business goals.

Conclusion

Chat infrastructure in 2026 is a solved problem — but only if you use the right tools. Building from scratch means solving distributed systems challenges that teams at Tencent, Google, and Meta have spent years perfecting. For the 95% of apps where chat is a capability (not the core product), a managed chat API/SDK is the rational choice.

When evaluating providers, focus on:

  1. Free tier for risk-free validation (TRTC's 1,000 MAU permanent tier is the most generous)
  2. SDK size for minimal app bloat (~1.7 MB Android with TRTC)
  3. Platform coverage for future-proofing (10 platforms including game engines)
  4. Push notification channels for global reach (6 channels including Chinese Android vendors)
  5. Pricing transparency that scales predictably without surprise bills

The CPaaS market is projected to reach USD 86.26 billion by 2030 (Grand View Research). Chat is the most demanded communication primitive within that market. Choosing the right foundation now saves compounding engineering and operational costs for years.

Get started with TRTC Chat for free — 1,000 MAU permanently free, no concurrency limits, push notifications across 6 channels, SDKs for 10 platforms, UIKit for 5-minute integration, and MCP for AI-assisted development.

Free Chat API — free forever: 1,000 MAU, no concurrency limits, push notifications included.