Skill站外收录 @skilllib/skill-2117939930272412573
juicebox-rate-limits
实现 Juicebox API 的智能流量调控,包括依据响应头动态解析配额余量与重置时间、按订阅等级执行请求节流、遭遇限流时自动触发带退避策略的重试机制,并持续追踪日级用量以避免超额,确保调用稳定高效。
测试与安全 AI 技能
Skills.MD
# Juicebox Rate Limits
## Overview
Understand and implement proper rate limiting handling for Juicebox API.
## Rate Limit Tiers
| Plan | Requests/Min | Requests/Day | Searches/Month |
|------|--------------|--------------|----------------|
| Free | 10 | 100 | 500 |
| Pro | 60 | 5,000 | 25,000 |
| Enterprise | 300 | 50,000 | Unlimited |
## Instructions
### Step 1: Understand Rate Limit Headers
```typescript
// Juicebox returns these headers with every response
interface RateLimitHeaders {
'x-ratelimit-limit': string; // Max requests per window
'x-ratelimit-remaining': string; // Remaining requests
'x-ratelimit-reset': string; // Unix timestamp when limit resets
'retry-after'?: string; // Seconds to wait (only on 429)
}
function parseRateLimitHeaders(headers: Headers) {
return {
limit: parseInt(headers.get('x-ratelimit-limit') || '0'),
remaining: parseInt(headers.get('x-ratelimit-remaining') || '0'),
reset: new Date(parseInt(headers.get('x-ratelimit-reset') || '0') * 1000),
retryAfter: parseInt(headers.get('retry-after') || '0')
};
}
```
### Step 2: Implement Rate Limiter
```typescript
// lib/rate-limiter.ts
export class RateLimiter {
private queue: Array<() => Promise<void>> = [];
private processing = false;
private lastRequestTime = 0;
private minInterval: number;
constructor(requestsPerMinute: number) {
this.minInterval = 60000 / requestsPerMinute;
}
async execute<T>(fn: () => Promise<T>): Promise<T> {
return new Promise((resolve, reject) => {
this.queue.push(async () => {
try {
const result = await fn();
resolve(result);
} catch (error) {
reject(error);
}
});
this.processQueue();
});
}
private async processQueue() {
if (this.processing || this.queue.length === 0) return;
this.processing = true;
while (this.queue.length > 0) {
const now = Date.now();
const elapsed = now - this.lastRequestTime;
if (elapsed < this.minInterval) {
await sleep(this.minInterval - elapsed);
}
const task = this.queue.shift();
if (task) {
this.lastRequestTime = Date.now();
await task();
}
}
this.processing = false;
}
}
```
### Step 3: Add Exponential Backoff
```typescript
// lib/backoff.ts
export async function withExponentialBackoff<T>(
fn: () => Promise<T>,
options: {
maxRetries?: number;
baseDelay?: number;
maxDelay?: number;
} = {}
): Promise<T> {
const { maxRetries = 5, baseDelay = 1000, maxDelay = 60000 } = options;
let lastError: Error;
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
return await fn();
} catch (error: any) {
lastError = error;
if (error.code === 'RATE_LIMITED') {
const retryAfter = error.retryAfter || 0;
const backoffDelay = Math.min(
baseDelay * Math.pow(2, attempt),
maxDelay
);
const delay = Math.max(retryAfter * 1000, backoffDelay);
console.log(`Rate limited. Retrying in ${delay}ms (attempt ${attempt + 1}/${maxRetries})`);
await sleep(delay);
continue;
}
throw error;
}
}
throw lastError!;
}
```
### Step 4: Implement Quota Tracking
```typescript
// lib/quota-tracker.ts
export class QuotaTracker {
private dailyRequests = 0;
private dailyResetTime: Date;
constructor(private dailyLimit: number) {
this.dailyResetTime = this.getNextMidnight();
}
async checkQuota(): Promise<boolean> {
this.maybeResetDaily();
return this.dailyRequests < this.dailyLimit;
}
recordRequest() {
this.dailyRequests++;
}
getRemainingQuota(): number {
this.maybeResetDaily();
return this.dailyLimit - this.dailyRequests;
}
private maybeResetDaily() {
if (new Date() > this.dailyResetTime) {
this.dailyRequests = 0;
this.dailyResetTime = this.getNextMidnight();
}
}
}
```
## Output
- Rate limiter with queue
- Exponential backoff handler
- Quota tracking system
- Header parsing utilities
## Error Handling
| Scenario | Strategy |
|----------|----------|
| 429 with Retry-After | Wait exact duration |
| 429 without Retry-After | Exponential backoff |
| Approaching limit | Proactive throttling |
| Daily quota exhausted | Queue for next day |
## Resources
- [Rate Limits Documentation](https://juicebox.ai/docs/rate-limits)
- [Quota Dashboard](https://app.juicebox.ai/usage)
## Next Steps
After rate limit handling, see `juicebox-security-basics` for security best practices.
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「juicebox-rate-limits」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次