Version 1.0.1 is now available! Looking for a migration guide?
v1.0.1
/
  • Get Started
  • Working
  • GitHub
  • Overview
  • Introduction
  • Actions
  • Call
  • Call
  • CallList
  • CallList
  • FetchList
  • FetchList
  • Batch
  • Batch
  • BatchByChunk
  • BatchByChunk
  • Tools
  • HealthCheck
  • Ping
  • Logger
  • Logger
  • Telegram
  • Limiters
  • Limiters
  • B24Frame
  • Introduction
  • Initialization
  • Auth
  • Dialog
  • Options
  • Parent
  • Placement
  • Slider
  • b24ui
  • b24icons
v1.0.1
  • Get started
  • Working

Restrictions System

The restrictions system provides a comprehensive mechanism for managing request frequency, operation execution time, and adaptive delays.
Limiters
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

  1. Token-based system: Each request consumes one token
  2. Automatic replenishment: Tokens are replenished at the rate of drainRate
  3. 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

  1. Sliding window: Tracks execution time over the last 10 minutes
  2. Method-specific tracking: Statistics are kept separately for each method
  3. Safety buffer: Calculations use limitMs - 5000 (5 second buffer)
  4. 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

  1. Operating Limit Check: Checks operation time limit
  2. Adaptive Delay: Applies adaptive delay if necessary
  3. 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

  1. For limit errors: Exponential delay considering the attempt number
  2. For other errors: Basic backoff with jitter (±10%)
  3. 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
  }
})

Telegram

Sending logs to Telegram

Introduction

Designed for managing Bitrix24 applications. It inherits functionality from AbstractB24 and provides methods for working with authentication, messages, sliders, and more.

On this page

  • Overview
    • Interfaces and Types
  • System Components
    • 1. RateLimiter (Rate Limiting)
    • 2. OperatingLimiter (Operation Time Limiting)
    • 3. AdaptiveDelayer (Adaptive Delays)
    • 4. RestrictionManager (Main Coordinator)
  • Default Configurations
    • Default parameters for regular tariffs (standard)
    • Parameters for the Enterprise plan
    • Parameters for bulk data processing
    • Real-time parameters
  • Monitoring and Statistics
    • Getting Statistics
    • Resetting Statistics
  • Usage Recommendations
Releases
Published under MIT License.

Copyright © 2024-present Bitrix24