We are still updating this page. Some data may be missing here — we will complete it shortly.
Overview
The system consists of several components working together to prevent exceeding API limits and ensure stable operation.
┌─────────────────────────────────────────────┐
│ RestrictionManager │
│ (Coordinator of all types of restrictions) │
└─────┬──────────────┬──────────────┬─────────┘
│ │ │
▼ ▼ ▼
┌──────────┐ ┌────────────┐ ┌─────────────┐
│ Rate │ │ Operating │ │ Adaptive │
│ Limiter │ │ Limiter │ │ Delayer │
└──────────┘ └────────────┘ └─────────────┘
Interfaces and Types
ILimiter (Base Interface)
interface ILimiter {
getTitle(): string
setConfig(config: any): Promise<void>
setLogger(logger: LoggerInterface): void
getLogger(): LoggerInterface
canProceed(requestId: string, method: string, params?: any): Promise<boolean>
waitIfNeeded(requestId: string, method: string, params?: any): Promise<number>
updateStats(requestId: string, method: string, data: any): Promise<void>
reset(): Promise<void>
getStats(): Record<string, any>
}
RestrictionParams
interface RestrictionParams {
rateLimit?: RateLimitConfig // Rate limiting settings
operatingLimit?: OperatingLimitConfig // Operation time limit settings
adaptiveConfig?: AdaptiveConfig // Adaptive delay settings
maxRetries?: number // Maximum number of request retries (default: 3). Except for `batch` requests
retryDelay?: number // Base delay between retries in ms (default: 1000)
}
System Components
1. RateLimiter (Rate Limiting)
Purpose: Implements the "Leaky Bucket" algorithm for limiting request frequency.
Configuration
interface RateLimitConfig {
burstLimit: number // Bucket capacity (maximum number of simultaneous requests)
drainRate: number // Leak rate (requests per second)
adaptiveEnabled: boolean // Enable adaptive management
}
Operation Principle
- Token-based system: Each request consumes one token
- Automatic replenishment: Tokens are replenished at the rate of
drainRate - Adaptive management:
- With frequent errors, limits are automatically reduced by 20%
- With stable operation, limits are gradually restored
- Minimum values:
drainRate = 0.5,burstLimit = 5
2. OperatingLimiter (Operation Time Limiting)
Purpose: Controls total operation execution time within a sliding window.
Configuration
interface OperatingLimitConfig {
windowMs: number // Time period in milliseconds (default: 600000 = 10 minutes)
limitMs: number // Maximum execution time in milliseconds (default: 480000 = 480 seconds)
heavyPercent: number // Threshold for heavy request notifications (%)
}
Operation Principle
- Sliding window: Tracks execution time over the last 10 minutes
- Method-specific tracking: Statistics are kept separately for each method
- Safety buffer: Calculations use
limitMs - 5000(5 second buffer) - Blocking: When the limit is reached, blocks execution until statistics are reset
Features
- For batch requests, analyzes all nested methods
- Automatic cleanup of outdated data (> windowMs + 10 seconds)
- Logging of heavy requests when exceeding
heavyPercent
3. AdaptiveDelayer (Adaptive Delays)
Purpose: Dynamically calculates delays based on previous request execution experience.
Configuration
interface AdaptiveConfig {
enabled: boolean // Enable adaptive delays
thresholdPercent: number // Activation threshold (% of operating limit)
coefficient: number // Delay multiplier (0.01 = 1% of remaining blocking time)
maxDelay: number // Maximum delay in milliseconds
}
Delay Calculation Algorithm
If operating of current method > (limitMs × thresholdPercent / 100):
If operating_reset_at > current time:
Delay = (operating_reset_at - current time) × coefficient
Otherwise:
Delay = 7000 ms (default value)
Final delay = min(calculated, maxDelay)
Features
- For batch requests, selects the maximum delay among all methods
- Does not block execution, only adds delay
- Uses statistics from OperatingLimiter
4. RestrictionManager (Main Coordinator)
Purpose: Manages all types of restrictions and error handling.
Order of Applying Restrictions
- Operating Limit Check: Checks operation time limit
- Adaptive Delay: Applies adaptive delay if necessary
- Rate Limit: Checks and applies rate limiting (loop for parallel requests)
Error Handling
// Determining error type
#isRateLimitError(error): boolean // 503 or QUERY_LIMIT_EXCEEDED
#isOperatingLimitError(error): boolean // 429 or OPERATION_TIME_LIMIT
#isNeedThrowError(error): boolean // Critical errors (no point in retrying)
Retry Strategy
- For limit errors: Exponential delay considering the attempt number
- For other errors: Basic backoff with jitter (±10%)
- Critical errors: No retries
Default Configurations
Default parameters for regular tariffs (standard)
{
rateLimit: {
burstLimit: 50, // 50 simultaneous requests
drainRate: 2, // 2 requests per second
adaptiveEnabled: true
},
operatingLimit: {
windowMs: 600000, // 10 minutes
limitMs: 480000, // 480 seconds (8 minutes)
heavyPercent: 80 // Notification at 80% usage
},
adaptiveConfig: {
enabled: true,
thresholdPercent: 80, // Activation at 80% of limit
coefficient: 0.01, // 1% of remaining blocking time
maxDelay: 7000 // Maximum 7 seconds delay
},
maxRetries: 3,
retryDelay: 1000
}
Parameters for the Enterprise plan
{
...standard,
rateLimit: {
burstLimit: 250, // 250 simultaneous requests
drainRate: 5, // 5 requests per second
adaptiveEnabled: true
}
}
Parameters for bulk data processing
{
...standard,
rateLimit: {
burstLimit: 30,
drainRate: 1,
adaptiveEnabled: true
},
operatingLimit: {
windowMs: 600_000,
limitMs: 480_000,
heavyPercent: 50 // Higher threshold for notifications
},
adaptiveConfig: {
enabled: true,
thresholdPercent: 50, // More threshold
coefficient: 0.015, // More pause
maxDelay: 10_000 // Max 10 seconds
},
maxRetries: 5 // More attempts
}
Real-time parameters
{
...standard,
adaptiveConfig: {
enabled: false, // Off
thresholdPercent: 100,
coefficient: 0.001,
maxDelay: 480_000
},
maxRetries: 1
}
Monitoring and Statistics
Getting Statistics
import { ApiVersion } from '@bitrix24/b24jssdk'
// const $b24 = ...
const statsV2 = $b24.getHttpClient(ApiVersion.v2).getStats()
const statsV3 = $b24.getHttpClient(ApiVersion.v3).getStats()
// Statistics structure:
{
// General statistics
retries: number, // Number of retry attempts
consecutiveErrors: number, // Consecutive errors
limitHits: number, // Limit hits
// Rate Limiter
tokens: number, // Current number of tokens
burstLimit: number, // Current burst limit
drainRate: number, // Current drain rate
// Adaptive Delayer
adaptiveDelays: number, // Number of applied delays
totalAdaptiveDelay: number, // Total delay time
adaptiveDelayAvg: number, // Average delay
// Operating Limiter
heavyRequestCount: number, // Number of heavy requests
operatingStats: { // Method statistics (in seconds)
[method: string]: number
},
// Errors by method
errorCounts: {
[method: string]: number
}
}
Resetting Statistics
// Complete reset of all limiter statistics
import { ApiVersion } from '@bitrix24/b24jssdk'
// const $b24 = ...
await $b24.getHttpClient(ApiVersion.v2).reset()
await $b24.getHttpClient(ApiVersion.v3).reset()
Usage Recommendations
Configuration for different scenarios:
import { ParamsFactory } from '@bitrix24/b24jssdk'
// const $b24 = ...
// Default parameters
$b24.setRestrictionManagerParams( ParamsFactory.getDefault() )
// Batch processing
$b24.setRestrictionManagerParams( ParamsFactory.getBatchProcessing() )
// Real-time
$b24.setRestrictionManagerParams( ParamsFactory.getRealtime() )
// By tariff plan
$b24.setRestrictionManagerParams( ParamsFactory.fromTariffPlan('enterprise') )
// Dynamic configuration change
$b24.setRestrictionManagerParams({
...ParamsFactory.getDefault(),
rateLimit: {
burstLimit: 30, // Temporary reduction in case of problems
drainRate: 1,
adaptiveEnabled: true
}
})