---
updatedAt: 2025-09-17T00:21:42.000Z
agentTools:
  projectIndex: https://booking-api-docs.guesty.com/llms.txt
---

# API traffic management

```node Node
// This example demonstrates a traffic management strategy that includes pacing, exponential backoff, and retry headers

const axios = require('axios');

// === CONFIGURATION ===
const REQUESTS_PER_SECOND = 5;
const INTERVAL_MS = 1000 / REQUESTS_PER_SECOND; // Send one request every 200ms
const MAX_RETRIES = 5;
const BASE_BACKOFF_MS = 500; // Initial backoff time in milliseconds

// === STATE ===
let queue = [];              // Queue to hold pending API requests
let isProcessing = false;    // Indicates whether the queue is currently being processed

/**
 * Add a request function to the queue for paced execution.
 */
function scheduleRequest(requestFn) {
  queue.push(requestFn);
  if (!isProcessing) processQueue();
}

/**
 * Processes queued requests at fixed intervals to avoid bursting the API.
 */
async function processQueue() {
  isProcessing = true;
  while (queue.length > 0) {
    const req = queue.shift();
    await req(); // Execute the request
    await new Promise(res => setTimeout(res, INTERVAL_MS)); // Wait to stay within rate limit
  }
  isProcessing = false;
}

/**
 * Constructs a function that performs a search request, with retry logic and exponential backoff.
 */
function makeSearchRequest(token, checkIn, checkOut) {
  return async () => {
    for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
      try {
        // Make an authenticated GET request to Guesty's search endpoint
        const response = await axios.get('https://booking-api.guesty.com/api/listings', {
          headers: {
            'Authorization': `Bearer ${token}`,
            'accept': 'application/json; charset=utf-8'
          },
          params: { checkIn, checkOut, adults: 2 }
        });

        // If response includes a Retry-After header, pause before continuing
        const retryAfter = response.headers['retry-after'];
        if (retryAfter) {
          console.warn(`Retry-After header received. Pausing for ${retryAfter} seconds.`);
          await new Promise(res => setTimeout(res, parseInt(retryAfter) * 1000));
        }

        console.log(`Results for ${checkIn} to ${checkOut}:`, response.data);
        break; // Success: Exit retry loop

      } catch (error) {
        if (error.response && error.response.status === 429) {
          // Too many requests: compute backoff duration
          const retryAfter = error.response.headers['retry-after'];
          const backoff = retryAfter ? parseInt(retryAfter) * 1000 : BASE_BACKOFF_MS * Math.pow(2, attempt);
          console.warn(`429 Rate Limit. Retrying in ${backoff}ms (attempt ${attempt + 1})...`);
          await new Promise(res => setTimeout(res, backoff)); // Wait before retrying
        } else {
          // Other errors: log and abort retry attempts
          console.error('Request failed:', error.message);
          break;
        }
      }
    }
  };
}

// === EXECUTION ===
// Token should be obtained and cached using a secure method before this point
const ACCESS_TOKEN = 'YOUR_ACCESS_TOKEN';

// Schedule several search requests to demonstrate rate pacing and retry resilience
scheduleRequest(makeSearchRequest(ACCESS_TOKEN, '2025-07-01', '2025-07-03'));
scheduleRequest(makeSearchRequest(ACCESS_TOKEN, '2025-07-04', '2025-07-06'));
scheduleRequest(makeSearchRequest(ACCESS_TOKEN, '2025-07-07', '2025-07-09'));
scheduleRequest(makeSearchRequest(ACCESS_TOKEN, '2025-07-10', '2025-07-12'));
scheduleRequest(makeSearchRequest(ACCESS_TOKEN, '2025-07-13', '2025-07-15'));

// This pacing with retries ensures compliance with rate limits and resilience to bursts

```

```python Python
"""
This script demonstrates a simple traffic management strategy for Guesty's Booking Engine API.
It limits request frequency, applies exponential backoff on 429 errors, and respects Retry-After headers.
"""

import time
import requests

REQUESTS_PER_SECOND = 5
INTERVAL = 1 / REQUESTS_PER_SECOND  # 200ms
MAX_RETRIES = 5
BASE_BACKOFF = 0.5  # seconds

def make_search_request(token, check_in, check_out):
    url = "https://booking-api.guesty.com/api/listings"
    headers = {
        "Authorization": f"Bearer {token}",
        "accept": "application/json; charset=utf-8"
    }
    params = {
        "checkIn": check_in,
        "checkOut": check_out,
        "adults": 2
    }

    for attempt in range(MAX_RETRIES + 1):
        try:
            response = requests.get(url, headers=headers, params=params)
            if response.status_code == 200:
                retry_after = response.headers.get("Retry-After")
                if retry_after:
                    print(f"Retry-After received: waiting {retry_after}s")
                    time.sleep(int(retry_after))
                print(f"Results for {check_in} to {check_out}:", response.json())
                break
            elif response.status_code == 429:
                retry_after = response.headers.get("Retry-After")
                wait = int(retry_after) if retry_after else BASE_BACKOFF * (2 ** attempt)
                print(f"Rate limited. Retrying in {wait:.2f}s (attempt {attempt + 1})...")
                time.sleep(wait)
            else:
                print("Request failed with status:", response.status_code)
                break
        except requests.RequestException as e:
            print("Request error:", str(e))
            break

def run_requests():
    token = "YOUR_ACCESS_TOKEN"
    date_ranges = [
        ("2025-07-01", "2025-07-03"),
        ("2025-07-04", "2025-07-06"),
        ("2025-07-07", "2025-07-09"),
        ("2025-07-10", "2025-07-12"),
        ("2025-07-13", "2025-07-15")
    ]
    for check_in, check_out in date_ranges:
        make_search_request(token, check_in, check_out)
        time.sleep(INTERVAL)

run_requests()

```

```php PHP
<?php
/**
 * This PHP script implements basic traffic control with pacing and retries for Guesty's Booking Engine API.
 * It handles rate limiting by applying exponential backoff and respecting Retry-After headers.
 */

define('ACCESS_TOKEN', 'YOUR_ACCESS_TOKEN');
define('MAX_RETRIES', 5);
define('BASE_BACKOFF', 0.5);  // seconds
define('INTERVAL', 0.2);      // 200ms between requests

function make_search_request($checkIn, $checkOut) {
    $url = 'https://booking-api.guesty.com/api/listings?checkIn=' . $checkIn . '&checkOut=' . $checkOut . '&adults=2';

    for ($attempt = 0; $attempt <= MAX_RETRIES; $attempt++) {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Authorization: Bearer ' . ACCESS_TOKEN,
                'accept: application/json; charset=utf-8'
            ]
        ]);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $retryAfter = curl_getinfo($ch, CURLINFO_RETRY_AFTER) ?: null;
        curl_close($ch);

        if ($httpCode === 200) {
            echo "Results for $checkIn to $checkOut:\n$response\n";
            if ($retryAfter) {
                echo "Retry-After received. Sleeping for {$retryAfter}s...\n";
                sleep((int)$retryAfter);
            }
            break;
        } elseif ($httpCode === 429) {
            $backoff = $retryAfter ? (int)$retryAfter : BASE_BACKOFF * pow(2, $attempt);
            echo "Rate limited. Retrying in {$backoff}s (attempt " . ($attempt + 1) . ")...\n";
            usleep($backoff * 1000000);
        } else {
            echo "Request failed with HTTP status $httpCode\n";
            break;
        }
    }
}

function run_requests() {
    $dates = [
        ['2025-07-01', '2025-07-03'],
        ['2025-07-04', '2025-07-06'],
        ['2025-07-07', '2025-07-09'],
        ['2025-07-10', '2025-07-12'],
        ['2025-07-13', '2025-07-15']
    ];

    foreach ($dates as [$checkIn, $checkOut]) {
        make_search_request($checkIn, $checkOut);
        usleep(INTERVAL * 1000000);
    }
}

run_requests();
?>

```

```json Response Example
{"success":true}
```

# Define your configuration

<!-- node@3-13 -->
<!-- python@6-12 -->
<!-- php@7-10 -->

Define the per-second rate limit, request interval, maximum number of retries and exponential backoff period.

# Implement internal logic

<!-- node@18-34 -->
<!-- python@10 -->

See next step

# Implement retry and exponential backoff logic

<!-- node@36-77 -->
<!-- python@26-46 -->
<!-- php@15-46 -->

Constructs a function that performs a search request, with retry logic and exponential backoff.

# Test the efficacy of your strategy

<!-- node@79-90 -->
<!-- python@48-61 -->
<!-- php@48-64 -->

Test you implementation to demonstrate rate pacing and retry resilience.