Limites de débit

Chaque clé a un quota de requêtes par minute, réparti en trois politiques. Chaque réponse dit ce qu'il reste ; quand il ne reste rien, attendez le temps que Myle vous indique.

Politiques

PolitiqueQuota par cléCompte
read600 requêtes par minuteLes lectures : GET
write120 requêtes par minuteLes écritures : POST, PATCH, DELETE
export20 requêtes par minuteLes lectures lourdes : un PDF, un CSV, toute requête dont l'en-tête Accept exclut le JSON, et les opérations que la référence marque comme des exports

Les en-têtes

Chaque réponse à une clé, erreurs comprises, porte deux en-têtes (brouillon IETF RateLimit header fields for HTTP) :

CLI

#!/usr/bin/env bash
# rate-limits-headers: the myle CLI (key from `myle login` or MYLE_API_KEY).
# Every response says which quota it was counted in, and what is left of it: -i prints the headers.
myle products list --organization organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d -i | grep -i '^ratelimit'
# ratelimit-policy: "read";q=600;w=60
# ratelimit: "read";r=597;t=41

HTTP

RateLimit-Policy: "read";q=600;w=60
RateLimit: "read";r=597;t=41

TypeScript

import { Myle } from '@myleapp/myle';

const myle = new Myle();
const page = await myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').products.list().firstPage();

// Every response says which quota it was counted in, and what is left of it.
console.log(page.lastResponse.headers.get('RateLimit-Policy')); // "read";q=600;w=60
console.log(page.lastResponse.headers.get('RateLimit')); // "read";r=597;t=41

Python

from myle import Myle

myle = Myle()
page = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products.list().first_page()

# Every response says which quota it was counted in, and what is left of it.
print(page.last_response.headers.get("RateLimit-Policy"))  # "read";q=600;w=60
print(page.last_response.headers.get("RateLimit"))  # "read";r=597;t=41

Go

package main

import (
    "context"
    "fmt"
    "log"

    myle "github.com/myleapp/myle-go"
)

func main() {
    client := myle.NewClient()
    org := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d")
    page, err := org.Products.List(context.Background(), nil).FirstPage()
    if err != nil {
        log.Fatal(err)
    }

    // Every response says which quota it was counted in, and what is left of it.
    fmt.Println(page.LastResponse().Header.Get("RateLimit-Policy")) // "read";q=600;w=60
    fmt.Println(page.LastResponse().Header.Get("RateLimit"))        // "read";r=597;t=41
}

Java

import fr.myleapp.myle.MyleClient;
import fr.myleapp.myle.Page;
import fr.myleapp.myle.Product;

public class Example {
    public static void main(String[] args) {
        MyleClient client = MyleClient.builder().build();
        Page<Product> page = client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products().list().firstPage();

        // Every response says which quota it was counted in, and what is left of it.
        System.out.println(page.lastResponse().headers().firstValue("RateLimit-Policy").orElse(null)); // "read";q=600;w=60
        System.out.println(page.lastResponse().headers().firstValue("RateLimit").orElse(null)); // "read";r=597;t=41
    }
}

Scala

import fr.myleapp.myle.MyleClient

object RateLimitsHeaders {
  def main(args: Array[String]): Unit = {
    val myle = MyleClient()
    val page = myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products.list().firstPage()

    // Every response says which quota it was counted in, and what is left of it.
    println(page.lastResponse.headers.get("RateLimit-Policy").getOrElse("")) // "read";q=600;w=60
    println(page.lastResponse.headers.get("RateLimit").getOrElse("")) // "read";r=597;t=41
  }
}

PHP

<?php

require __DIR__ . '/vendor/autoload.php';

use Myle\Client;

$myle = new Client();
$page = $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->products->list()->firstPage();

// Every response says which quota it was counted in, and what is left of it.
echo $page->lastResponse->header('RateLimit-Policy'), "\n"; // "read";q=600;w=60
echo $page->lastResponse->header('RateLimit'), "\n"; // "read";r=597;t=41

C#

using Myle;

using var client = new MyleClient();
var page = await client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Products.ListAsync().FirstPageAsync();

// Every response says which quota it was counted in, and what is left of it.
Console.WriteLine(page.LastResponse.Headers["RateLimit-Policy"]); // "read";q=600;w=60
Console.WriteLine(page.LastResponse.Headers["RateLimit"]); // "read";r=597;t=41
ParamètreSens
"read"La politique dans laquelle cette requête a été comptée.
qLe quota : les requêtes permises par fenêtre.
wLa fenêtre, en secondes.
rCe qu'il reste à cet instant.
tLes secondes avant que le quota soit de nouveau entier.

Myle tourne sur plusieurs serveurs, chacun appliquant sa part du quota : un 429 peut parfois arriver un peu avant le chiffre annoncé. Suivez les en-têtes plutôt que de compter vous-même.

Quand vous recevez un 429

CLI

#!/usr/bin/env bash
# rate-limits-retry-after: the myle CLI (key from `myle login` or MYLE_API_KEY).
# On a 429 the CLI waits Retry-After and sends the call again, up to 2 times (--max-retries <n>);
# a POST is retried with the same Idempotency-Key. --format json: stderr holds the error object alone.
if ! error=$(myle products create --organization organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d \
    --number A0042 --name 'Paille de blé, botte' --vat-rate 10 --format json 2>&1 >/dev/null); then
  # Still refused after the retries: the policy, and Retry-After as retry_after (seconds).
  jq -r 'select(.code == "core.rate-limited") | "policy \(.context.policy): retry in \(.retry_after) s"' <<<"$error"
fi

HTTP

HTTP/1.1 429 Too Many Requests
Retry-After: 17
RateLimit-Policy: "write";q=120;w=60
RateLimit: "write";r=0;t=17

{
  "code": "core.rate-limited",
  "context": { "policy": "write" },
  "error": "Trop de requêtes ; réessayez plus tard.",
  "request_id": "01M803CAJ14DSK72C4MKMWBPT7"
}

TypeScript

import { CoreRateLimitedError, Myle } from '@myleapp/myle';

// On a 429 the SDK waits Retry-After and sends the call again, up to maxRetries times
// (2 by default); a POST is retried with the same Idempotency-Key.
const myle = new Myle({ maxRetries: 4 });

try {
  await myle.organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d').products.create({ number: 'A0042', name: 'Paille de blé, botte', vatRate: '10' });
} catch (e) {
  if (!(e instanceof CoreRateLimitedError)) throw e;
  // Still refused after the retries, or asked to wait more than 60 s.
  console.log(`policy ${e.context.policy}: retry in ${e.retryAfter} s`);
}

Python

from myle import CoreRateLimitedError, Myle

# On a 429 the SDK waits Retry-After and sends the call again, up to max_retries times
# (2 by default); a POST is retried with the same Idempotency-Key.
myle = Myle(max_retries=4)

try:
    myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products.create(number="A0042", name="Paille de blé, botte", vat_rate="10")
except CoreRateLimitedError as e:
    # Still refused after the retries, or asked to wait more than 60 s.
    print(f"policy {e.context.policy}: retry in {e.retry_after} s")

Go

package main

import (
    "context"
    "errors"
    "fmt"
    "log"

    myle "github.com/myleapp/myle-go"
)

func main() {
    // On a 429 the SDK waits Retry-After and sends the call again, up to WithMaxRetries times
    // (2 by default); a POST is retried with the same Idempotency-Key.
    client := myle.NewClient(myle.WithMaxRetries(4))

    org := client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d")
    _, err := org.Products.Create(context.Background(), &myle.ProductCreateParams{Number: "A0042", Name: "Paille de blé, botte", VatRate: "10"})
    var limited *myle.CoreRateLimitedError
    switch {
    case errors.As(err, &limited) && limited.RetryAfter != nil:
        // Still refused after the retries, or asked to wait more than 60 s.
        fmt.Printf("policy %s: retry in %s\n", limited.Context.Policy, *limited.RetryAfter)
    case err != nil:
        log.Fatal(err)
    }
}

Java

import fr.myleapp.myle.CoreRateLimitedException;
import fr.myleapp.myle.MyleClient;
import fr.myleapp.myle.ProductCreateParams;
import java.time.Duration;

public class Example {
    public static void main(String[] args) {
        // On a 429 the SDK waits Retry-After and sends the call again, up to maxRetries times
        // (2 by default); a POST is retried with the same Idempotency-Key.
        MyleClient client = MyleClient.builder().maxRetries(4).build();

        try {
            client.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products().create(
                    ProductCreateParams.builder().number("A0042").name("Paille de blé, botte").vatRate("10").build());
        } catch (CoreRateLimitedException e) {
            // Still refused after the retries, or asked to wait more than 60 s.
            Long seconds = e.retryAfter().map(Duration::toSeconds).orElse(null);
            System.out.println("policy " + e.context().policy() + ": retry in " + seconds + " s");
        }
    }
}

Scala

import fr.myleapp.myle.{CoreRateLimitedError, MyleClient, MyleConfig}
import fr.myleapp.myle.models.CreateProduct

object RateLimitsRetryAfter {
  def main(args: Array[String]): Unit = {
    // On a 429 the SDK waits Retry-After and sends the call again, up to maxRetries times
    // (2 by default); a POST is retried with the same Idempotency-Key.
    val myle = MyleClient(MyleConfig(maxRetries = 4))

    try myle.organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").products.create(CreateProduct(number = "A0042", name = "Paille de blé, botte", vatRate = "10"))
    catch {
      case e: CoreRateLimitedError =>
        // Still refused after the retries, or asked to wait more than 60 s.
        println(s"policy ${e.context.policy}: retry in ${e.retryAfter.map(_.toSeconds).getOrElse(0L)} s")
    }
  }
}

PHP

<?php

require __DIR__ . '/vendor/autoload.php';

use Myle\Client;
use Myle\Exception\CoreRateLimitedException;

// On a 429 the SDK waits Retry-After and sends the call again, up to maxRetries times
// (2 by default); a POST is retried with the same Idempotency-Key.
$myle = new Client(maxRetries: 4);

try {
    $myle->organization('organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d')->products->create(number: 'A0042', name: 'Paille de blé, botte', vatRate: '10');
} catch (CoreRateLimitedException $e) {
    // Still refused after the retries, or asked to wait more than 60 s.
    echo "policy {$e->context()->policy}: retry in {$e->retryAfter} s\n";
}

C#

using Myle;

// On a 429 the SDK waits Retry-After and sends the call again, up to MaxRetries times
// (2 by default); a POST is retried with the same Idempotency-Key.
using var client = new MyleClient(new MyleClientOptions { MaxRetries = 4 });

try
{
    await client.Organization("organization_7f2c41d0-8a3b-4c6e-9f12-5d7e8a9b0c1d").Products
        .CreateAsync(new ProductCreateParams { Number = "A0042", Name = "Paille de blé, botte", VatRate = "10" });
}
catch (CoreRateLimitedException e)
{
    // Still refused after the retries, or asked to wait more than 60 s.
    Console.WriteLine($"policy {e.Context.Policy}: retry in {e.RetryAfter?.TotalSeconds} s");
}
  1. Attendez le nombre de secondes de Retry-After, puis renvoyez la requête.
  2. Réessayez un POST avec la même Idempotency-Key.
  3. Plusieurs processus partagent une clé : ajoutez un délai aléatoire d'une ou deux secondes, pour qu'ils ne reviennent pas tous en même temps.
  4. Ralentissez durablement quand r atteint 0 à répétition : étalez une tâche de nuit sur quelques minutes plutôt que de tout envoyer dans les premières secondes.

Il en va de même pour 503 core.unavailable, qui porte aussi Retry-After.

Rester sous les quotas