Current Location: Home> Latest Articles> PHP Implementation of Rate Limiting and Traffic Control for Baidu Wenxin Yiyan API

PHP Implementation of Rate Limiting and Traffic Control for Baidu Wenxin Yiyan API

gitbox 2025-06-15

What Is the Wenxin Yiyan API?

The Wenxin Yiyan API, provided by Baidu, offers beautiful Chinese sentences via a free interface. Although the official limit is 1000 requests per day, many applications rely on this API, which can easily lead to request overages or frequency issues.

Why Do You Need Rate Limiting and Traffic Control?

Without proper restrictions, frequent or sudden spikes in requests can overload the server, degrade performance, or even impact other users. Implementing controls on both the number and frequency of requests helps maintain the API’s availability and reliability.

How to Implement Rate Limiting and Traffic Control in PHP

Using Redis for Rate Limiting

In PHP, Redis can be used to track and limit user requests by IP and date. Here is an example implementation:


// Connect to Redis server
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

// Get user IP and current date
$ip = $_SERVER['REMOTE_ADDR'];
$date = date("Y-m-d");

// Create Redis key
$key = $ip . '-' . $date;
$count = $redis->get($key);

if (!$count) {
    // First request: initialize count and set expiry
    $redis->set($key, 1);
    $redis->expire($key, 86400);
} else {
    if ($count >= 1000) {
        echo 'Request limit exceeded';
        exit;
    }
    // Increment request count
    $redis->incr($key);
    $redis->expire($key, 86400);
}

// Call Wenxin Yiyan API
$url = 'https://v1.alapi.cn/api/shici?format=text';
$response = file_get_contents($url);
echo $response;

Using NGINX for Traffic Control

Beyond PHP-level control, you can use NGINX to limit incoming request rates, providing a first line of defense against spikes in traffic. Here's an example setup:


http {
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
}

server {
    ...
    location / {
        limit_req zone=one burst=5 nodelay;
        proxy_pass ...;
    }
}

Explanation of settings:

  • rate=1r/s: Allows one request per second per IP
  • burst=5: Permits a burst of up to 5 queued requests
  • nodelay: Requests are either processed immediately or denied, without delay

Conclusion

Combining PHP and Redis for request tracking with NGINX for rate-based throttling offers an effective solution to protect public APIs from overload. In this article, we used Baidu’s Wenxin Yiyan API as a case study to demonstrate practical techniques. These same strategies can be applied to any high-frequency public API, depending on your application's specific needs.