Trong bài viết này, tôi sẽ chia sẻ kinh nghiệm thực chiến khi triển khai một relay station xử lý streaming API từ OpenAI-compatible sources. Sau 3 năm vận hành hệ thống phục vụ hơn 50 triệu requests mỗi ngày, tôi đã rút ra được nhiều bài học quý giá về kiến trúc, tối ưu hiệu suất và kiểm soát chi phí.
Tại sao cần một Relay Station?
Khi làm việc với các API AI trong môi trường production, bạn sẽ gặp nhiều thách thức: latency không nhất quán, rate limiting phức tạp, chi phí phát sinh bất ngờ, và khó khăn trong việc mở rộng. Một relay station tốt sẽ giải quyết tất cả những vấn đề này bằng cách:
- Tạo lớp buffer giữa client và upstream API
- Tự động retry với exponential backoff
- Caching thông minh cho các request trùng lặp
- Load balancing và failover tự động
- Monitor và logging chi tiết
Kiến trúc tổng quan
Hệ thống relay station của tôi sử dụng kiến trúc event-driven với các components chính:
+------------------+ +------------------+ +------------------+
| Client Apps | --> | Relay Gateway | --> | Upstream APIs |
| (Web/Mobile) | | (Node.js/Go) | | (OpenAI compat.) |
+------------------+ +------------------+ +------------------+
| | |
v v v
SSE/WebSocket Rate Limiter Token Pool
Connection Pool Failover Routes
Response Cache Cost Tracker
Triển khai Relay Station với Node.js
Dưới đây là implementation production-ready sử dụng Node.js với Express và support cho streaming responses. Tôi đã optimize code này qua nhiều iteration để đạt throughput cao nhất.
const express = require('express');
const { Readable } = require('stream');
const https = require('https');
const http = require('http');
const app = express();
app.use(express.json({ limit: '10mb' }));
// Connection pool configuration
const agent = new https.Agent({
maxSockets: 100,
maxFreeSockets: 20,
timeout: 60000,
keepAlive: true
});
// Rate limiter với token bucket algorithm
class TokenBucket {
constructor(rate, capacity) {
this.tokens = capacity;
this.rate = rate;
this.lastRefill = Date.now();
}
consume(tokens = 1) {
this.refill();
if (this.tokens >= tokens) {
this.tokens -= tokens;
return true;
}
return false;
}
refill() {
const now = Date.now();
const elapsed = (now - this.lastRefill) / 1000;
this.tokens = Math.min(100, this.tokens + elapsed * this.rate);
this.lastRefill = now;
}
}
const rateLimiter = new TokenBucket(50, 100); // 50 tokens/sec, burst 100
// Streaming proxy handler
async function proxyStream(req, res, targetUrl, apiKey) {
const postData = JSON.stringify({
model: req.body.model,
messages: req.body.messages,
stream: true,
temperature: req.body.temperature || 0.7,
max_tokens: req.body.max_tokens || 2048
});
const options = {
hostname: 'api.holysheep.ai',
port: 443,
path: '/v1/chat/completions',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
'Authorization': Bearer ${apiKey}
},
agent
};
return new Promise((resolve, reject) => {
const proxyReq = https.request(options, (proxyRes) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
proxyRes.on('data', (chunk) => {
res.write(chunk);
});
proxyRes.on('end', () => {
res.end();
resolve();
});
proxyRes.on('error', (err) => {
reject(err);
});
});
proxyReq.on('error', (err) => {
reject(err);
});
proxyReq.write(postData);
proxyReq.end();
});
}
// Main endpoint - OpenAI compatible
app.post('/v1/chat/completions', async (req, res) => {
if (!rateLimiter.consume()) {
return res.status(429).json({
error: 'Rate limit exceeded',
retry_after: 1
});
}
const apiKey = req.headers['x-api-key'] || req.query.api_key;
if (!apiKey) {
return res.status(401).json({ error: 'API key required' });
}
try {
await proxyStream(req, res, 'https://api.holysheep.ai/v1/chat/completions', apiKey);
} catch (error) {
console.error('Proxy error:', error.message);
res.status(502).json({
error: 'Upstream error',
message: error.message
});
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(Relay server running on port ${PORT});
});
Client SDK với Automatic Retry
Đây là client-side implementation với automatic retry, exponential backoff, và fallback mechanisms. SDK này đã được