本指南解释了 TheRPC 的速率限制系统,并提供管理 API 使用的最佳实践。
速率限制应用于多个层面:
具体限制取决于您的订阅计划。查看您的控制面板了解当前限制。
当您超出速率限制时,您将收到:
{
"jsonrpc": "2.0",
"error": {
"code": -32029,
"message": "Rate limit exceeded"
},
"id": 1
}
HTTP 响应将包含以下头信息:
X-RateLimit-Limit: 10
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1628696400
async function callWithRetry(method, params, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await makeRequest(method, params);
return response;
} catch (error) {
if (error.code === -32029) {
// 超出速率限制
const backoffTime = Math.pow(2, i) * 1000;
await new Promise((resolve) => setTimeout(resolve, backoffTime));
continue;
}
throw error;
}
}
throw new Error('Max retries exceeded');
}
将多个调用合并为单个请求:
[
{
"jsonrpc": "2.0",
"method": "eth_getBalance",
"params": ["0x742d35Cc6634C0532925a3b844Bc454e4438f44e", "latest"],
"id": 1
},
{
"jsonrpc": "2.0",
"method": "eth_blockNumber",
"params": [],
"id": 2
}
]
对于实时数据,使用 eth_subscribe 而不是轮询。
通过以下方式监控您的使用情况:
function trackApiUsage(response) {
const limits = {
limit: response.headers['X-RateLimit-Limit'],
remaining: response.headers['X-RateLimit-Remaining'],
reset: response.headers['X-RateLimit-Reset'],
};
// 记录或监控使用情况
console.log(`API 调用剩余: ${limits.remaining}/${limits.limit}`);
}
const cache = new Map();
async function getCachedBlockNumber(cacheTime = 5000) {
const cached = cache.get('blockNumber');
if (cached && Date.now() - cached.timestamp < cacheTime) {
return cached.value;
}
const newValue = await web3.eth.getBlockNumber();
cache.set('blockNumber', {
value: newValue,
timestamp: Date.now(),
});
return newValue;
}
不同的订阅计划有不同的限制:
查看定价页面以获取详细的计划比较。
如果您经常达到速率限制,请考虑: