Building Serverless API with Tencent Cloud SCF
Building Serverless API with Tencent Cloud SCF
Serverless architecture lets developers run code without managing servers—paying only for actual invocations with fast cold starts and infinite elasticity. Tencent Cloud SCF (Serverless Cloud Function) is one of the most mature Serverless platforms in China. This guide walks you through building and deploying a complete RESTful API with SCF.
Serverless Architecture Overview
Core Philosophy
Serverless doesn't mean "no servers"—it means the cloud platform handles all server management:
| Traditional Architecture | Serverless Architecture | |------------------------|----------------------| | Purchase/rent servers | No server management | | Always running, always billing | Pay per invocation and execution time | | Manual scaling | Auto elastic scaling | | Manage OS and runtime | Focus only on business code | | Fixed costs | Variable costs (near-zero idle cost) |
SCF vs. Other Platforms
| Feature | Tencent Cloud SCF | Alibaba Cloud FC | AWS Lambda | |---------|-------------------|-----------|------| | Runtimes | Node.js/Python/Go/Java/PHP | Node.js/Python/Go/Java/PHP | Node.js/Python/Go/Java/.NET | | Max execution time | 900 seconds | 600 seconds | 900 seconds | | Memory | 128 MB–3 GB | 128 MB–3 GB | 128 MB–10 GB | | Cold start time | 100–300 ms | 100–500 ms | 50–200 ms | | Free tier | 1M invocations/month | 1M invocations/month | 1M invocations/month | | Provisioned concurrency | Yes | Yes | Yes |
Project Design
We'll build a Todo management API with the following endpoints:
| Method | Path | Function | |--------|------|----------| | GET | /api/todos | List all todos | | GET | /api/todos/:id | Get a single todo | | POST | /api/todos | Create a todo | | PUT | /api/todos/:id | Update a todo | | DELETE | /api/todos/:id | Delete a todo |
Architecture
Client → API Gateway → SCF Function → Cloud MongoDB
↓
Cloud Monitoring/Logging
Function Development
Creating the Function
- Log in to the Tencent Cloud SCF Console
- Click New → Create from scratch
- Configure:
| Setting | Value | Notes | |---------|-------|-------| | Function name | todo-api | Project name | | Runtime | Node.js 18 | LTS version | | Handler | index.main | Entry function | | Memory | 256 MB | Medium configuration | | Timeout | 30 seconds | API response requirements |
Code Implementation
'use strict';
const MongoClient = require('mongodb').MongoClient;
const MONGO_URI = process.env.MONGO_URI;
let cachedDb = null;
async function connectToDatabase() {
if (cachedDb) return cachedDb;
const client = await MongoClient.connect(MONGO_URI);
const db = client.db('todo_app');
cachedDb = db;
return db;
}
exports.main = async (event) => {
const db = await connectToDatabase();
const collection = db.collection('todos');
const method = event.httpMethod || event.requestContext?.httpMethod;
const path = event.path || event.requestContext?.path;
const body = event.body ? JSON.parse(event.body) : {};
let response;
if (method === 'GET' && path === '/api/todos') {
const todos = await collection.find({}).toArray();
response = { code: 0, data: todos };
}
else if (method === 'GET' && path.match(/^\/api\/todos\/[a-f0-9]+$/)) {
const id = path.split('/').pop();
const todo = await collection.findOne({ _id: new require('mongodb').ObjectId(id) });
response = todo ? { code: 0, data: todo } : { code: 404, message: 'Not found' };
}
else if (method === 'POST' && path === '/api/todos') {
const result = await collection.insertOne({
title: body.title,
completed: false,
createdAt: new Date()
});
response = { code: 0, data: { id: result.insertedId } };
}
else if (method === 'PUT' && path.match(/^\/api\/todos\/[a-f0-9]+$/)) {
const id = path.split('/').pop();
await collection.updateOne(
{ _id: new require('mongodb').ObjectId(id) },
{ $set: { title: body.title, completed: body.completed, updatedAt: new Date() } }
);
response = { code: 0, message: 'Updated' };
}
else if (method === 'DELETE' && path.match(/^\/api\/todos\/[a-f0-9]+$/)) {
const id = path.split('/').pop();
await collection.deleteOne({ _id: new require('mongodb').ObjectId(id) });
response = { code: 0, message: 'Deleted' };
}
else {
response = { code: 404, message: 'Route not found' };
}
return {
statusCode: response.code === 404 ? 404 : 200,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(response)
};
};
Dependency Management
Create package.json:
{
"name": "todo-api",
"version": "1.0.0",
"dependencies": {
"mongodb": "^6.3.0"
}
}
Install dependencies locally and package together before uploading:
npm install
zip -r todo-api.zip . -x "node_modules/.cache/*"
API Gateway Configuration
API Gateway bridges SCF functions to HTTP endpoints:
Create API Service
- Go to the API Gateway Console
- Create service → Select same region as SCF
- Create API:
| Setting | Value | Notes | |---------|-------|-------| | API name | TodoAPI | Identifier | | Frontend type | HTTP | HTTP protocol | | Path | /api/todos | Resource path | | Method | GET/POST/PUT/DELETE | Multiple methods | | Backend type | SCF | Link to SCF function | | Function name | todo-api | Target function |
Enable CORS
For separated frontend/backend deployments, enable CORS:
- Access-Control-Allow-Origin:
https://your-frontend.com - Access-Control-Allow-Methods:
GET, POST, PUT, DELETE, OPTIONS - Access-Control-Allow-Headers:
Content-Type, Authorization
Authentication Configuration
API Gateway supports multiple authentication methods:
| Method | Use Case | Complexity | |--------|----------|-----------| | Key pair | Service-to-service | Low | | OAuth 2.0 | Third-party authorization | Medium | | Custom auth | JWT Token verification | Medium | | No auth | Public APIs | None |
Recommended: Use a custom auth function for JWT Token verification:
// Auth function
exports.main = async (event) => {
const token = event.headers?.authorization?.replace('Bearer ', '');
try {
const decoded = require('jsonwebtoken').verify(token, process.env.JWT_SECRET);
return {
isAuthorized: true,
context: { userId: decoded.userId }
};
} catch (e) {
return { isAuthorized: false };
}
};
Database Integration
Cloud MongoDB
Tencent Cloud offers fully managed MongoDB:
| Spec | Storage | Monthly Cost | Use Case | |------|---------|-------------|----------| | 1C2G | 20 GB SSD | ¥320 | Dev/test | | 2C4G | 50 GB SSD | ¥650 | Small production | | 4C8G | 100 GB SSD | ¥1,200 | Medium production |
Connection Optimization
Database connections are slow during cold starts. Recommendations:
- Connection reuse: Store the DB connection in a global variable
- Private network: MongoDB instance and SCF in the same VPC
- Connection pool: Configure reasonable pool size (10–20 connections)
Alternative: TCB (Tencent CloudBase)
Skip MongoDB management with Tencent CloudBase:
const cloudbase = require('@cloudbase/node-sdk');
const app = cloudbase.init();
const db = app.database();
// No connection string needed, auto-authenticated
const result = await db.collection('todos').get();
TCB offers a free tier, ideal for MVPs and lightweight apps.
Deployment and CI/CD
Serverless Framework Deployment
# Install Serverless Framework
npm install -g serverless
# Create serverless.yml
cat > serverless.yml << 'EOF'
component: scf
name: todo-api
inputs:
src:
src: ./
exclude:
- node_modules/**
functionName: todo-api
runtime: Nodejs18
handler: index.main
memorySize: 256
timeout: 30
environmentVariables:
MONGO_URI: mongodb://...
events:
- apigw:
name: todo-api-gw
parameters:
protocols:
- http
- https
serviceName: todo-api-service
endpoints:
- path: /api/todos
method: ANY
EOF
# Deploy
serverless deploy
GitHub Actions Auto-Deployment
name: Deploy SCF
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
- run: npm install
- run: npm install -g serverless
- run: serverless deploy
env:
TENCENT_SECRET_ID: ${{ secrets.TENCENT_SECRET_ID }}
TENCENT_SECRET_KEY: ${{ secrets.TENCENT_SECRET_KEY }}
Performance and Cost Analysis
Performance Metrics
| Metric | Expected | Optimized | |--------|----------|-----------| | Cold start latency | 200–500 ms | <200 ms (provisioned concurrency) | | Warm start latency | 10–50 ms | <10 ms | | Concurrent handling | Auto-elastic | Unlimited | | Single execution time | 20–100 ms | Optimize DB queries |
Cost Calculation
Example: 1M monthly invocations, 100ms avg execution, 256 MB memory:
| Billing Item | Usage | Monthly Cost | |-------------|-------|-------------| | Invocations | 1M | ¥1.33 (above free tier) | | Execution time | 1M × 100ms × 0.25 GB | ¥2.33 | | Free tier offset | Deduction | -¥1.33 | | API Gateway | 1M | ¥7.00 | | Total | | ¥9.33/month |
Compared to GCP Cloud Functions, SCF offers lower latency for China-based traffic and a free tier that covers more low-traffic scenarios.
Provisioned Concurrency
Cold starts are Serverless's biggest pain point. SCF provisioned concurrency keeps function instances warm:
# Configure provisioned concurrency
tccli scf PutProvisionedConcurrentConfig \
--FunctionName todo-api \
--VersionValue '{"VersionProvisionedConcurrentNums": [{"Version": "1", "Capacity": 5}]}'
| Config | Cost Impact | Effect | |--------|------------|--------| | Provisioned=0 | Lowest cost | Cold starts occur | | Provisioned=5 | +~¥50/month | Eliminates cold start for first 5 concurrent | | Provisioned=10 | +~¥100/month | Suitable for steady traffic |
Best Practices
- Single responsibility: One function per API endpoint, or use route dispatch
- Cold start optimization: Reduce package size, use provisioned concurrency, keep functions lean
- Error handling: Unified error format, retry mechanisms, dead letter queues
- Logging standards: Use structured logging, correlate requestId
- Security: Store secrets in environment variables, enable function auth, restrict invocation sources
- Monitoring alerts: Configure >5% error rate alerts, >500ms P99 latency alerts
Conclusion
Tencent Cloud SCF frees API development from server management—focus only on business code from development to deployment. Combined with API Gateway and Cloud MongoDB, a complete Serverless API can cost as little as a few dollars per month, making it the best choice for small projects and MVPs.
Duoyun Cloud is a Tencent Cloud partner offering SCF and API Gateway architecture consulting with exclusive discounts. Purchase Tencent Cloud resources through Duoyun for better pricing and professional Chinese-language technical support, helping you build Serverless apps at the lowest cost. Visit duoyun.io for details.
Need Professional Cloud Consulting?
Our cloud architect team will customize the best solution for you — free
Free Consultation