API Timeout Configuration
Configure appropriate timeouts for reliable and resilient API integrations.
Timeouts are a crucial but often neglected element of API configuration. A timeout defines how long your application waits for a response before giving up and considering the request failed. Without appropriate timeout, a request can block indefinitely, gradually paralyzing your entire application.
Choosing the timeout is a delicate balance. Too short: legitimate but slow requests fail unnecessarily. Too long: your application becomes vulnerable to slow or unavailable services, accumulating blocked connections and waiting threads.
This guide will help you understand different timeout types, choose appropriate values according to context, and implement robust error handling strategies to create resilient API integrations.
Types of Timeout
Several timeout types intervene at different request stages:
- Connection timeout: maximum time to establish TCP connection. Typically 5-10 seconds. Failure indicates unreachable server or network issue.
- Read timeout (socket timeout): maximum time to receive data once connection is established. Depends on server-side operation complexity.
- Total timeout: maximum time for entire request (connection + processing + response). Useful as global safeguard.
- Idle timeout: maximum inactivity time on keepalive connection before closing. Manages persistent connections.
Valeurs Recommandées par Cas d'Usage
Les timeouts optimaux varient selon le type d'opération :
- Healthcheck / Status : connection: 3s, read: 5s. Un healthcheck doit répondre rapidement, sinon il indique déjà un problème.
- Lecture simple (GET) : connection: 5s, read: 15s. La plupart des lectures devraient répondre en quelques secondes.
- Écriture (POST/PUT) : connection: 5s, read: 30s. Les écritures peuvent impliquer des validations et des transactions plus longues.
- Opérations lourdes (exports, rapports) : connection: 10s, read: 300s+. Préférez les opérations asynchrones avec polling ou webhooks.
Implémentation des Timeouts
Voici comment configurer les timeouts dans différents contextes :
// PHP avec cURL
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_CONNECTTIMEOUT => 5, // Connection timeout: 5s
CURLOPT_TIMEOUT => 30, // Total timeout: 30s
CURLOPT_RETURNTRANSFER => true,
]);
$response = curl_exec($ch);
if (curl_errno($ch)) {
$error = curl_error($ch);
// Gérer l'erreur de timeout
}
curl_close($ch);
// JavaScript avec fetch et AbortController
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 30000); // 30s timeout
try {
const response = await fetch(url, {
signal: controller.signal
});
clearTimeout(timeoutId);
return await response.json();
} catch (error) {
if (error.name === 'AbortError') {
console.error('Request timeout');
}
throw error;
}
Ces exemples montrent la configuration de timeouts en PHP (cURL) et JavaScript (fetch). Adaptez les valeurs selon votre cas d'usage spécifique.
Timeout Best Practices
Optimize your timeout configuration with these practices:
- Always configure timeout: never leave a request without timeout. System defaults are often too long or infinite.
- Adapt to context: a healthcheck and report export don't need the same timeout. Configure per endpoint type.
- Circuit breaker: after multiple timeouts on same service, temporarily stop calling it to avoid saturating your resources.
- Retry with backoff: on timeout, retry with exponential delay. Avoid hammering an already struggling server.
Timeout Configuration Checklist
- Connection timeout configured on all HTTP clients
- Read timeout adapted to operation type
- Total timeout as global safeguard
- Retry strategy with exponential backoff
- Circuit breaker for critical services
- Timeout logging for diagnosis
Frequently Asked Questions - Timeout
What's the difference between connection and read timeout?
Connection timeout limits TCP connection establishment time. Read timeout limits data reception time once connection is established. Both should be configured.
What timeout to use by default?
For standard REST APIs: connection 10s, read 30s is a reasonable starting point. Adjust based on observed performance of each endpoint.
How to handle timeout in code?
Catch timeout exceptions specifically. Log the incident, apply retry strategy if appropriate, and return meaningful error to user/calling service.
Does MoniTao have a configurable timeout?
Yes, you can configure check timeout according to your endpoints. MoniTao measures and reports actual response time to detect near-timeout degradations.
Comment tester que mes timeouts fonctionnent ?
Créez un endpoint de test qui dort pendant X secondes avant de répondre. Appelez-le avec différentes configurations de timeout pour vérifier le comportement.
Le timeout côté client doit-il être plus court que côté serveur ?
Idéalement oui. Si le serveur a un timeout de 30s, le client devrait avoir 25-28s. Cela permet de recevoir une erreur propre du serveur plutôt qu'un timeout brut côté client.
Well-Configured Timeouts Prevent Cascades
Timeout is your last line of defense against unavailable or slow services. Without it, a single slow dependency can bring down your entire application by exhausting threads, connections, and memory.
With MoniTao, monitor your endpoint response times to detect when they approach configured timeout. A proactive alert on high latency allows you to act before the complete failure.
Ready to Sleep Soundly?
Start free, no credit card required.