Notes on Retriable HTTP Client (with Golang/Rust example
A fault-tolerance HTTP client needs to retry on recoverable errors.
When the server is able to send a response, the client can retry on 429 Too Many Requests
or any status code equal to or greater than 500.
When the client is unable to receive a response from the server, it will encounter an error or exception from the underlying network libraries. There are various cases that can lead to these errors:
- The connection cannot be established. The URL schema may be invalid, DNS resolution could fail for the hostname, or the server may temporarily be down for an upgrade and not listening on the socket
- The connection is established but is aborted before the server sends a response back
When a reverse proxy is placed behind the application server, a client error in the proxy will be translated into a response with a 502 Bad Gateway
status code.
Some errors are recoverable, while others are not.
A client can retry on certain recoverable errors.
Here’s a Go example.
|
|
Here’s a Rust example based on reqwest. It’s a simplified version ported from TrueLayer/reqwest-middleware.
|
|
Clients can also retry any error except for certain unrecoverable errors, as demonstrated by hashicorp/go-retryablehttp.
As the examples show, retrying based on status codes is quite similar, but retrying based on library errors is highly language-specific.
The full code for all the samples in this post is available on GitHub.
Writing your own retry code from nothing is not recommended; it is better to use or learn from mature libraries.
- Golang: hashicorp/go-retryablehttp
- Rust: TrueLayer/reqwest-middleware
In Java, HTTP client implementations such as Apache HttpClient and OkHttp have retry policies based on Java’s Exception mechanism.
Author Zeng Xu
LastMod 2023-12-29 17:36
License 本作品采用 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议 进行许可,转载时请注明原文链接。