Retry API Requests (auto-retry
)
The auto-retry plugin is everything you need to handle flood limits, i.e. errors with code 429. It can be used for every bot during normal operation, but it will come especially handy during broadcasting.
This plugin is an API transformer function, which means that it let’s you intercept and modify outgoing HTTP requests on the fly. More specifically, this plugin will automatically detect if an API requests fails with a retry
value, i.e. because of rate limiting. It will then catch the error, wait the specified period of time, and then retry the request.
In addition to handling flood limits, this plugin will retry a request if it fails with an internal server error, i.e. errors with code 500 or larger. Networking errors (those that throw an Http
in grammY) will cause a retry, too. Retrying such requests is more or less the only sane strategy to handle these two types of errors. Since neither of them provide a retry
value, the plugin employs exponential backoff starting at 3 seconds and capped at one hour.
Installation
You can install this plugin on the bot
object:
import { autoRetry } from "@grammyjs/auto-retry";
// Use the plugin.
bot.api.config.use(autoRetry());
2
3
4
const { autoRetry } = require("@grammyjs/auto-retry");
// Use the plugin.
bot.api.config.use(autoRetry());
2
3
4
import { autoRetry } from "https://deno.land/x/grammy_auto_retry@v2.0.2/mod.ts";
// Use the plugin.
bot.api.config.use(autoRetry());
2
3
4
If you now call e.g. send
and run into a rate limit, it will look like the request just takes unusually long. Under the hood, multiple HTTP requests are being performed, with the appropriate delays in between.
Configuration
You may pass an options object that specifies a maximum number of retries (max
), or a threshold for a maximum time to wait (max
).
Limiting Retries
As soon as the maximum number of retries is exhausted, subsequent errors for the same request will not be retried again. Instead, the error object from Telegram is passed on, effectively failing the request with a Grammy
.
Similarly, if the request ever fails with retry
larger than what is specified by the option max
, the request will fail immediately.
autoRetry({
maxRetryAttempts: 1, // only repeat requests once
maxDelaySeconds: 5, // fail immediately if we have to wait >5 seconds
});
2
3
4
Rethrowing Internal Server Errors
You can use rethrow
to opt out of handling internal server errors as described above. Again, the error object from Telegram is passed on, effectively failing the request with a Grammy
.
autoRetry({
rethrowInternalServerErrors: true, // do not handle internal server errors
});
2
3
Rethrowing Networking Errors
You can use rethrow
to opt out of handling networking errors as described above. If enabled, the thrown Http
instances are passed on, failing the request.
autoRetry({
rethrowHttpErrors: true, // do not handle networking errors
});
2
3