danylokhodus commited on
Commit
ec80222
·
1 Parent(s): 7fc9995

feat(AI): add retry loop with exponential backoff for transient HTTP status codes (503, 429, 500)

Browse files
FlowAPI.Application/Services/AIService.cs CHANGED
@@ -178,13 +178,31 @@ namespace FlowAPI.Application.Services
178
 
179
  using var httpClient = new HttpClient();
180
  var jsonPayload = JsonSerializer.Serialize(requestBody);
181
- var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
182
-
183
- var response = await httpClient.PostAsync(url, content);
184
- var responseString = await response.Content.ReadAsStringAsync();
185
-
186
- if (!response.IsSuccessStatusCode)
 
 
187
  {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  throw new Exception($"Gemini API error (Status {response.StatusCode}): {responseString}");
189
  }
190
 
 
178
 
179
  using var httpClient = new HttpClient();
180
  var jsonPayload = JsonSerializer.Serialize(requestBody);
181
+
182
+ HttpResponseMessage? response = null;
183
+ string responseString = string.Empty;
184
+
185
+ int maxRetries = 3;
186
+ int delayMs = 1500; // 1.5s base delay
187
+
188
+ for (int attempt = 1; attempt <= maxRetries; attempt++)
189
  {
190
+ using var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
191
+ response = await httpClient.PostAsync(url, content);
192
+ responseString = await response.Content.ReadAsStringAsync();
193
+
194
+ if (response.IsSuccessStatusCode)
195
+ {
196
+ break;
197
+ }
198
+
199
+ int statusCode = (int)response.StatusCode;
200
+ if (attempt < maxRetries && (statusCode == 503 || statusCode == 429 || statusCode == 500))
201
+ {
202
+ await Task.Delay(delayMs * attempt);
203
+ continue;
204
+ }
205
+
206
  throw new Exception($"Gemini API error (Status {response.StatusCode}): {responseString}");
207
  }
208