การจำกัดอัตรา
อยู่ภายในขีดจำกัดอัตราของ Omise API และสร้างการรวมที่ มีประสิทธิภาพ เรียนรู้เกี่ยวกับเฮดเดอร์การจำกัดอัตรา จัดการข้อผิดพลาด 429 อย่างสง่างาม และเพิ่มประสิทธิภาพรูปแบบคำขอของคุณ
ภาพรวม
เพื่อให้แน่ใจว่าบริการเชื่อถือได้สำหรับผู้ค้าทุกราย Omise ใช้การจำกัดอัตราบนคำขอ API การจำกัดอัตราป้องกันไม่ให้การรวมเดียวครอบงำ API และรับประกันการจัดสรรทรัพยากรอย่างเป็นธรรม การทำความเข้าใจและเคารพขีดจำกัดเหล่านี้เป็นสิ่งสำคัญสำหรับการสร้างการรวมการชำระเงินที่แข็งแกร่ง
เริ่มต้นอย่างรวดเร็ว
- ขีดจำกัดเริ่มต้น: 1,000 คำขอต่อนาทีต่อคีย์ API
- ตรวจสอบเฮดเดอร์
X-RateLimit-*ในการตอบกลับ - จัดการ HTTP 429 ด้วยการชะลอแบบทวีคูณ
- ใช้งานคิวคำขอสำหรับการดำเนินการปริมาณสูง
- แคชการตอบกลับเมื่อเหมาะสม
รายละเอียดการจำกัดอัตรา
ขีดจำกัดปัจจุบัน
| ประเภทขีดจำกัด | ค่า | ขอบเขต |
|---|---|---|
| ขีดจำกัดอัตรามาตรฐาน | 1,000 คำขอ/นาที | ต่อคีย์ API |
| การอนุญาตระ เบิด | ~100 คำขอ | อนุญาตการระเบิดสั้นๆ |
| ระยะเวลารีเซ็ต | 60 วินาที | หน้าต่างแบบเลื่อน |
สิ่งที่นับเข้าสู่ขีดจำกัด
✅ นับ:
- คำขอ API ทั้งหมด (GET, POST, PATCH, DELETE)
- คำขอที่สำเร็จ (การตอบกลับ 2xx)
- คำขอที่ล้มเหลว (การตอบกลับ 4xx, 5xx)
- การยืนยันตัวตนที่ล้มเหลว
❌ ไม่นับ:
- คำขอที่ถูกบล็อกก่อนถึง API (URL ที่ไม่ถูกต้อง)
- คำขอสินทรัพย์คงที่
- การเข้าถึงแดชบอร์ด
- การส่ง webhook จาก Omise
เฮดเดอร์การจำกัดอัตรา
การตอบกลับ API ทุกครั้งรวมข้อมูลการจำกัดอัตราในเฮดเดอร์:
เฮดเดอร์การตอบกลับ
HTTP/1.1 200 OK
Content-Type: application/json
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 995
X-RateLimit-Reset: 1612137600
คำอธิบายเฮดเดอร์
| เฮดเดอร์ | คำอธิบาย | ตัวอย่าง |
|---|---|---|
X-RateLimit-Limit | คำขอสูงสุดที่อนุญาตในหน้าต่าง | 1000 |
X-RateLimit-Remaining | คำขอที่เหลือในหน้าต่างปัจจุบัน | 995 |
X-RateLimit-Reset | Unix timestamp เมื่อขีดจำกัดรีเซ็ต | 1612137600 |
การอ่านเฮดเดอร์ในโค้ด
# Ruby - ตรวจสอบเฮดเดอร์การจำกัดอัตรา
require 'omise'
Omise.api_key = ENV['OMISE_SECRET_KEY']
response = Omise::Charge.retrieve('chrg_test_...')
# เข้าถึงเฮดเดอร์
limit = response.http_headers['X-RateLimit-Limit']
remaining = response.http_headers['X-RateLimit-Remaining']
reset = response.http_headers['X-RateLimit-Reset']
puts "ขีดจำกัดอัตรา: #{remaining}/#{limit}"
puts "รีเซ็ตที่: #{Time.at(reset.to_i)}"
# Python - ตรวจสอบเฮดเดอร์การจำกัดอัตรา
import omise
from datetime import datetime
omise.api_secret = os.environ['OMISE_SECRET_KEY']
charge = omise.Charge.retrieve('chrg_test_...')
# เข้าถึงเฮดเดอร์ (เฉพาะไลบรารี)
headers = charge.response_headers
limit = headers.get('X-RateLimit-Limit')
remaining = headers.get('X-RateLimit-Remaining')
reset_timestamp = int(headers.get('X-RateLimit-Reset', 0))
print(f"ขีดจำกัดอัตรา: {remaining}/{limit}")
print(f"รีเซ็ตที่: {datetime.fromtimestamp(reset_timestamp)}")
// Node.js - ตรวจสอบเฮดเดอร์การจำกัดอัตรา
const omise = require('omise')({
secretKey: process.env.OMISE_SECRET_KEY
});
try {
const charge = await omise.charges.retrieve('chrg_test_...');
// เฮดเดอร์ที่มีอยู่ในการตอบกลับ
const headers = charge._response.headers;
const limit = headers['x-ratelimit-limit'];
const remaining = headers['x-ratelimit-remaining'];
const reset = headers['x-ratelimit-reset'];
console.log(`ขีดจำกัดอัตรา: ${remaining}/${limit}`);
console.log(`รีเซ็ตที่: ${new Date(reset * 1000)}`);
} catch (error) {
console.error('คำขอล้มเหลว:', error);
}
HTTP 429 การตอบกลับ
เมื่อคุณเกินขีดจำกัดอัตรา API จะส่งคืน HTTP 429 Too Many Requests:
429 รูปแบบการตอบกลับ
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1612137660
Retry-After: 60
{
"object": "error",
"location": "https://www.omise.co/api-errors#rate-limit-exceeded",
"code": "rate_limit_exceeded",
"message": "too many requests, please try again later"
}
ฟิลด์การตอบกลับ
| ฟิลด์ | คำอธิบาย |
|---|---|
code | "rate_limit_exceeded" |
message | ข้อความข้อผิดพลาดที่อ่านได้ |
Retry-After | วินาทีที่จะรอก่อนลองใหม่ |
การจัดการการจำกัดอัตรา
กลยุทธ์ 1: การชะลอแบบทวีคูณ (แนะนำ)
ลองใหม่ด้วยความล่าช้าที่เพิ่มขึ้น:
# Ruby - การชะลอแบบทวีคูณ
require 'omise'
def create_charge_with_backoff(params, max_attempts: 5)
attempt = 0
begin
attempt += 1
Omise::Charge.create(params)
rescue Omise::Error => e
if e.code == 'rate_limit_exceeded' && attempt < max_attempts
# คำนวณความล่าช้าในการชะลอ: 1 วินาที, 2 วินาที, 4 วินาที, 8 วินาที, 16 วินาที
delay = 2 ** (attempt - 1)
# เพิ่มการสั่นไหว (ความสุ่ม) เพื่อป้องกันการรุมกัน
jitter = rand(0..delay * 0.1)
sleep(delay + jitter)
retry
else
raise
end
end
end
# การใช้งาน
charge = create_charge_with_backoff(
amount: 100000,
currency: 'thb',
card: token
)
# Python - การชะลอแบบทวีคูณด้วย decorator
import time
import random
from functools import wraps
def exponential_backoff(max_attempts=5, base_delay=1):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(max_attempts):
try:
return func(*args, **kwargs)
except omise.errors.BaseError as e:
if e.code != 'rate_limit_exceeded':
raise
if attempt == max_attempts - 1:
raise
# คำนวณความล่าช้าพร้อมการสั่นไหว
delay = base_delay * (2 ** attempt)
jitter = random.uniform(0, delay * 0.1)
total_delay = delay + jitter
print(f"ถูกจำกัดอัตรา กำลังลองใหม่ใน {total_delay:.2f} วินาที...")
time.sleep(total_delay)
raise Exception("เกินจำนวนครั้งการลองใหม่สูงสุด")
return wrapper
return decorator
@exponential_backoff(max_attempts=5)
def create_charge(amount, currency, card):
return omise.Charge.create(
amount=amount,
currency=currency,
card=card
)
# การใช้งาน
charge = create_charge(100000, 'thb', token)
// Node.js - การชะลอแบบทวีคูณ
async function createChargeWithBackoff(chargeData, maxAttempts = 5) {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
try {
return await omise.charges.create(chargeData);
} catch (error) {
if (error.code !== 'rate_limit_exceeded' || attempt === maxAttempts - 1) {
throw error;
}
// คำนวณความล่าช้าพร้อมการสั่นไหว
const baseDelay = Math.pow(2, attempt) * 1000;
const jitter = Math.random() * baseDelay * 0.1;
const delay = baseDelay + jitter;
console.log(`ถูกจำกัดอัตรา กำลังลองใหม่ใน ${(delay / 1000).toFixed(2)} วินาที...`);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}
// การใช้งาน
const charge = await createChargeWithBackoff({
amount: 100000,
currency: 'thb',
card: token
});