DEX · Asterdex

Rate Limits and Performance: A Guide to the AsterDEX API

Understanding and respecting rate limits is critical for uninterrupted API operations. How to avoid bans and optimize your interaction with the AsterDEX API.

What Are Rate Limits: API Gateway, WAF and Bot Management

Rate limiting is a critical mechanism at the API Gateway or WAF (Web Application Firewall) level that controls the number of incoming network requests to the server over a given period of time (for example, 1,200 req/min).

In the context of DeFi and crypto exchanges such as AsterDEX, rate limiting serves three key purposes:

  • Bot Management: Separating legitimate algorithmic trading (market making, arbitrage) from malicious scraping and brute-force attacks (credential stuffing).
  • DDoS protection: Preventing application-layer resource exhaustion (Layer 7 DDoS) by blocking suspicious traffic spikes before they reach the matching engine.
  • Resource allocation in distributed systems: Ensuring high availability of microservices by preventing individual database nodes from becoming overloaded.

How Throttling Works Under the Hood (Algorithms)

To interact with the API effectively, it is important to understand the server-side architecture. AsterDEX and most modern high-load systems use in-memory stores (such as Redis) to synchronize request counters across a distributed environment. The most popular algorithms are:

  • Token Bucket: (Attribute: allows traffic bursts). AsterDEX uses this algorithm to smooth out API responses. The server grants "tokens" at a constant rate. If you send a batch of orders at once (burst), the algorithm will let them through as long as tokens remain in the bucket, ensuring minimal latency.
  • Leaky Bucket: (Attribute: ensures a strictly steady flow). Requests are placed in a queue (FIFO) and processed by the server at a fixed rate, preventing database overload (Trading Engine).
  • Sliding Window Counter: (Attribute: memory efficiency). Tracks the number of requests in a dynamically shifting time window, preventing peak overload at minute boundaries (unlike the Fixed Window approach).

AsterDEX Request Processing Architecture

Rate limiting happens long before your order reaches the matching engine. The life cycle of your request looks like this:

1. Client (your Python bot) ➔ Sends an HMAC-SHA256-signed request.

2. WAF / Edge Network (Cloudflare/Imperva) ➔ Checks the IP for DDoS, malicious bot signatures (Bot Management) and L7 anomalies. On violations — a network-level ban (HTTP 403).

3. API Gateway (Nginx/Envoy) ➔ Validates your API key against the global cache in Redis. Applies the Token Bucket algorithm. If tokens are exhausted — returns HTTP 429.

4. AsterDEX Trading Engine ➔ Processes business logic (order placement) only if the API Gateway let the request through.

AsterDEX API Rate Limits

AsterDEX applies an overall limit of 1,200 weight units per minute per IP address or API key. It is important to understand the concept of cost-based rate limiting: it is not the number of physical HTTP requests that is limited, but their computational "cost" for the server.

Different endpoints consume different amounts of tokens (weight) from your bucket:

Request type (Endpoint) Weight (Cost) Impact on the limit (out of 1,200/min)
GET /fapi/v1/ping (Status check) 1 Up to 1,200 requests/min
POST /fapi/v1/order (Placing an order) 2 Up to 600 requests/min
GET /fapi/v1/depth (Deep order book, limit=1000) 10 — 50 Only 24 — 120 requests/min in total
GET /fapi/v1/klines (Historical candles) Up to 100 Risk of an instant ban when spammed

Keep track of the weight of the methods you call in the documentation so you don't exhaust your token bucket faster than you expect.

Tip: Never poll historical data (K-lines) in an infinite REST API loop. To build charts in real time, fetch a historical snapshot once (REST), then keep it updated via WebSocket streams.

If you exceed the limit you will receive HTTP status 429 Too Many Requests. In some cases a temporary ban on API access lasting several minutes may be imposed.

Important distinction: Rate Limit vs WAF Block

Never confuse a soft API throttle with a hard firewall ban:

  • HTTP 429 (Too Many Requests): Expected API Gateway behavior. Your token bucket is empty. Solution: exponential delay and parsing the Retry-After header.
  • HTTP 403 / HTTP 418 / HTTP 503 (IP Ban): You ignored the 429 errors and kept spamming the server (DDoS-like behavior). The WAF classified your script as a malicious bot (credential stuffing / brute force). Access is cut off at the TCP/IP level for anywhere from 5 minutes to 24 hours.

How to Avoid Getting Blocked: Best Practices

1. Use WebSocket for streaming data

If you need real-time market data (prices, trades, order book), use the WebSocket API. It is a "push" model where the server sends you updates proactively, eliminating the need to constantly poll REST endpoints and thereby significantly reducing the number of requests. For more on the difference between the two, see our article REST vs WebSocket.

2. Implement Exponential Backoff

If you receive a 429 Too Many Requests error, do not retry the request immediately. Instead, wait some time before trying again. With each subsequent failed attempt, increase the waiting time. This gives the API room to "breathe" and avoids further blocking.

3. Distributed client-side throttling

If your trading algorithms run in a distributed system (for example, bots launched across multiple AWS servers), local in-memory queues within a single script are not enough. Your microservices must synchronize with each other. Use centralized in-memory stores (such as Redis) to store global request counters. This guarantees that the combined traffic of your entire cluster stays within the limit that the API Gateway on the AsterDEX side enforces.

4. Analyze standard and custom HTTP headers

Servers report the state of your limits through response headers. Be sure to parse them in your code:

  • Retry-After: (IETF RFC 7231 standard) Specifies the exact number of seconds the client must wait before the next request after receiving HTTP 429 or 503.
  • X-RateLimit-Limit: The maximum capacity of your bucket (total request limit).
  • X-RateLimit-Remaining: The number of requests/tokens remaining in the current window.
  • X-RateLimit-Reset: Unix timestamp of the full counter reset.

Use these headers to dynamically control the pace at which your bot sends requests.

5. Eliminating clock drift (NTP Time Sync)

A frequent hidden cause of HTTP 429 errors is clock drift on your server. When the API returns an X-RateLimit-Reset: 1712930000 header, your server may conclude that this moment has already arrived even though its internal clock runs 2 seconds fast. As a result, the script resumes requests too early and gets blocked. Solution: Regularly synchronize your server time with an NTP (Network Time Protocol) daemon and cross-check it against the AsterDEX API time (/fapi/v1/time endpoint).

6. Preventing the Thundering Herd problem

If your distributed scripts pause upon hitting the limit and all wait for the reset time simultaneously, a micro-DDoS attack arises: the very millisecond the counter resets, all of your bots send requests at once. The API Gateway treats this anomalous spike as malicious activity and drops the connections (TCP drop). Solution: Always add random jitter to your Exponential Backoff wait time (for example, time.sleep(wait_time + random_milliseconds)) to spread requests out over time.

7. Key isolation and protecting authorization endpoints (Security & Bot Management)

Professional bot management requires separating access rights. Use one API key for public data (order book) and another one for private endpoints (trading/auth). It is important to understand that strict rate limiting on authentication endpoints mitigates hacker attacks such as brute force and credential stuffing.

If your script starts spamming authorization requests due to a bug in its code, the WAF will classify it as a malicious bot (Malicious Bot) and ban the key/IP. Key isolation guarantees that your market-making scripts (good bots) continue running without interruption.

Implementing Exponential Backoff and Header Parsing in Python

Professional trading bots do not use "blind" delays. They react dynamically to standardized IETF headers (Retry-After) and implement Exponential Backoff with jitter to prevent the Thundering Herd problem.

import time
import random
import requests
from requests.exceptions import HTTPError

BASE_URL = "https://fapi.asterdex.com"

def request_with_backoff(method, endpoint, params=None, max_retries=5):
    """
    Performs an HTTP request with smart rate-limit handling (Exponential Backoff
    algorithm) and reading of the Retry-After standard header.
    """
    url = BASE_URL + endpoint

    for attempt in range(max_retries):
        try:
            response = requests.request(method, url, params=params)

            # Reading status headers (information gain: API Gateway context)
            remaining = response.headers.get('X-RateLimit-Remaining')
            if remaining is not None and int(remaining) < 10:
                print(f"[Warning] Осталось мало токенов в корзине (Token Bucket): {remaining}")

            response.raise_for_status()
            return response.json()

        except HTTPError as e:
            if response.status_code == 429:
                # 1. Priority: read the standard IETF Retry-After header
                retry_after = response.headers.get('Retry-After')

                if retry_after:
                    wait_time = int(retry_after)
                    print(f"[HTTP 429] Сервер требует паузу. Retry-After: {wait_time} сек.")
                else:
                    # 2. Fallback: exponential backoff with jitter
                    # Formula: (2 ^ attempt) + random(0, 1000ms)
                    wait_time = (2 ** attempt) + (random.randint(0, 1000) / 1000.0)
                    print(f"[HTTP 429] Бэкофф (Попытка {attempt + 1}). Ожидание: {wait_time:.2f} сек.")

                time.sleep(wait_time)
                continue # Trying again

            elif response.status_code in[403, 503]:
                print("[КРИТИЧЕСКАЯ ОШИБКА] Возможно, сработала блокировка WAF (Bot Management) или сервер недоступен.")
                break # Giving up on retries
            else:
                print(f"Необработанная HTTP ошибка: {e}")
                break

    raise Exception("Превышено максимальное количество попыток (Max Retries) из-за Rate Limits.")

# Usage example:
if __name__ == "__main__":
    print("Отправка запроса с динамическим контролем лимитов...")
    try:
        data = request_with_backoff('GET', '/fapi/v1/exchangeInfo')
        print("Данные успешно получены!")
    except Exception as e:
        print(e)

FAQ: Common Questions About API Limits

What is the AsterDEX API rate limit?

The overall limit is 1,200 weight units (requests) per minute per API key or IP address. This restriction (enforced by the API Gateway) guarantees server stability and protection against DDoS.

What should I do when I get an HTTP 429 Too Many Requests error?

Stop sending requests immediately. Read the Retry-After or X-RateLimit-Reset HTTP header and resume operation using an Exponential Backoff algorithm with jitter.

Can I bypass the limits by rotating IP addresses?

No. AsterDEX uses a hybrid limit (by IP and API key). Circumventing IP limits through proxy networks will be classified by the Bot Management subsystem as malicious traffic (Malicious Bot), resulting in a permanent key ban at the WAF level.

Conclusion

Effective rate-limit management is a hallmark of professionalism and the key to stable, uninterrupted work with the API. By adopting the practices described above, you will avoid bans and make your code more reliable and performant.

To continue learning about the AsterDEX API, check out our other materials:

---