{"course":{"slug":"building-with-ai","title":"Building with AI","url":"https://addaly.com/learn/building-with-ai","level":"intermediate","track":"build"},"lesson":{"slug":"retries-that-do-not-make-it-worse","title":"Errors, retries, and how a retry loop takes down your own service","url":"https://addaly.com/learn/building-with-ai/retries-that-do-not-make-it-worse","position":7,"of":80,"minutes":9,"answer":"Retry only what a second attempt could fix, with jittered backoff under a wall-clock deadline and a concurrency cap, or your retry logic will convert a slow provider into your own outage.","keyIdea":"Retry only what a second attempt could fix, with jittered backoff under a wall-clock deadline and a concurrency cap, or your retry logic will convert a slow provider into your own outage."},"body":{"format":"markdown","text":"## Decide whether another attempt can help\n\nInspect the provider's documented status and error body. Correct an invalid request or permission problem before sending it again. A rate limit or temporary server error may justify a bounded later attempt. A timeout or broken connection can leave the first request's outcome uncertain.\n\nFor the Claude Python SDK, automatic retries are enabled by default for selected failures. When you implement an outer retry loop, disable SDK retries so the two policies do not multiply attempts. The example below retries only the selected HTTP status failures. It lets connection and timeout exceptions reach the caller for an explicit decision. [SDK retries and errors](https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python).\n\n## Backoff, with jitter, and why jitter is not optional\n\n```python\nimport random\nimport time\nfrom anthropic import APIStatusError\n\nRETRYABLE = {429, 500, 502, 503, 529}\n\ndef create_with_retries(\n    client, request, attempts=4, budget_s=25\n):\n    if attempts < 1 or budget_s <= 0:\n        raise ValueError(\n            \"Attempts and time budget \"\n            \"must be positive\"\n        )\n    api = client.with_options(max_retries=0)\n    expires = time.monotonic() + budget_s\n    for attempt in range(attempts):\n        remaining = expires - time.monotonic()\n        if remaining <= 0:\n            raise TimeoutError(\n                \"No time remains for another attempt\"\n            )\n        try:\n            return api.messages.create(\n                **request, timeout=remaining\n            )\n        except APIStatusError as error:\n            if error.status_code not in RETRYABLE:\n                raise\n            if attempt == attempts - 1:\n                raise\n            header = error.response.headers.get(\"retry-after\")\n            try:\n                wait = max(0.0, float(header))\n            except (TypeError, ValueError):\n                wait = min(2 ** attempt, 8) * (\n                    0.5 + random.random()\n                )\n            if wait >= expires - time.monotonic():\n                raise TimeoutError(\n                    \"Retry would exceed the time budget\"\n                ) from error\n            time.sleep(wait)\n```\n\nPass the helper a request dictionary containing the model, messages and output cap, as in the earlier examples. The helper checks the remaining budget before each attempt and wait, and passes that remaining time as the request timeout. This is client-side scheduling, not a guarantee that server execution stops at that instant. SDK HTTP timeouts also have transport-level semantics, so measure elapsed time and enforce any stricter outer deadline in the application.\n\nThe example handles a numeric `retry-after` value in seconds. A production adapter should also support an HTTP-date header when the provider uses that form. Its fallback uses exponential backoff with jitter. Keep the total attempt and elapsed-time policy visible in logs.\n\n> Figure: How a retry loop turns slow into down. Steps: 1. The provider slows down (Suppose requests that took two seconds now take twenty.); 2. Your ten-second timeout fires (The first request may still be running. Its outcome needs checking.); 3. Retries add overlapping work (More simultaneous attempts can exhaust available capacity.); 4. You cross your own rate limit (Application or provider limits may reject additional work.); 5. The loop retries the 429s (An attempt counter with no deadline keeps spending the request's budget.); 6. Your service is down (The application may fail under amplified load.). A hypothetical slowdown can amplify load if new attempts overlap uncertain earlier requests. Concurrency limits, a retry budget and a circuit breaker address different parts of the failure chain.\n\n## The retry storm that is your fault\n\nHere is the failure mode worth internalising, because it is self-inflicted.\n\nSuppose a provider slows from two seconds to twenty. If a ten-second client timeout triggers another request while the first is still running, work can overlap. Repeated across many users, extra attempts can exhaust your concurrency or rate limits. Whether the first call continues and is billed depends on its outcome and the provider. Log uncertain outcomes and avoid treating a dropped connection as proof that no generation occurred.\n\nThe defences are all boring:\n\n- **A concurrency cap**: a semaphore around outbound calls. Above it, queue or shed load. A number you chose beats a number your connection pool chose for you.\n- **A circuit breaker.** After N consecutive failures, stop calling for 30 seconds and fail fast. This is counter-intuitive and correct: when a dependency is unhealthy, the kindest thing you can do is stop sending it traffic.\n- **A total budget per user request**: attempts and seconds, both capped.\n- **Shed the retry on non-interactive paths.** A background job can wait a minute. A user cannot.\n\n## Timeouts on a streaming call\n\nA stream may need both an inactivity timeout and a total elapsed-time budget. The inactivity limit catches a stalled connection. The total budget limits how long the task may occupy resources. Select both for the task and the deployed infrastructure.\n\n## Retries and duplicates\n\nA retry can create another generation and another charge when the provider accepts and processes it. The returned text can differ. Before retrying an uncertain outcome, consider whether the original request or a tool it triggered could already have changed external state.\n\nSo: **keep side effects out of the retried region**, or make them idempotent. If your loop retries an entire agent turn, and step three of that turn charged a card, a network blip has now charged it twice. Give every externally visible action a key derived from the request, store the key, and make the second attempt a no-op. This is ordinary distributed-systems hygiene, and putting a model in the loop does not exempt you from it: it makes it more likely, because agent loops retry more."},"check":{"question":"A service retries slow requests while the original calls may still be running. Which mechanism can raise its own error rate?","options":[{"text":"Slow responses are truncated by the provider, so the results fail validation.","correct":false,"tempting":"Confuses latency with truncation; a slow response still completes normally and carries a normal stop reason."},{"text":"The model degrades under load and produces malformed output.","correct":false,"tempting":"Attributes a queueing problem to generation quality, when the same weights produce the same distribution regardless of how busy the servers are."},{"text":"Overlapping attempts multiply work until concurrency or rate limits are exhausted.","correct":true},{"text":"The retries are being served by a different, weaker model as a fallback.","correct":false,"tempting":"Assumes a fallback that only exists if you wrote one, and would not by itself produce a sixfold error rate."}]},"prev":{"slug":"reading-the-response","title":"Every field in the response, and the two that catch bugs","url":"https://addaly.com/learn/building-with-ai/reading-the-response"},"next":{"slug":"choosing-a-model","title":"Choosing a model, and designing so you can change your mind","url":"https://addaly.com/learn/building-with-ai/choosing-a-model"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Errors, retries, and how a retry loop takes down your own service', in Building with AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/building-with-ai/retries-that-do-not-make-it-worse (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Errors, retries, and how a retry loop takes down your own service","courseTitle":"Building with AI","module":{"index":1,"slug":"the-call-underneath-everything","title":"The call underneath everything"},"answer":null,"keyIdea":"Retry only what a second attempt could fix, with jittered backoff under a wall-clock deadline and a concurrency cap, or your retry logic will convert a slow provider into your own outage.","hero":{"kind":"figure","figure":{"t":"figure","label":"Figure","figure":{"type":"flow","title":"How a retry loop turns slow into down","caption":"A hypothetical slowdown can amplify load if new attempts overlap uncertain earlier requests. Concurrency limits, a retry budget and a circuit breaker address different parts of the failure chain.","steps":[{"label":"The provider slows down","detail":"Suppose requests that took two seconds now take twenty."},{"label":"Your ten-second timeout fires","detail":"The first request may still be running. Its outcome needs checking."},{"label":"Retries add overlapping work","detail":"More simultaneous attempts can exhaust available capacity."},{"label":"You cross your own rate limit","detail":"Application or provider limits may reject additional work."},{"label":"The loop retries the 429s","detail":"An attempt counter with no deadline keeps spending the request’s budget."},{"label":"Your service is down","detail":"The application may fail under amplified load."}]},"alt":"Figure: How a retry loop turns slow into down. Steps: 1. The provider slows down (Suppose requests that took two seconds now take twenty.); 2. Your ten-second timeout fires (The first request may still be running. Its outcome needs checking.); 3. Retries add overlapping work (More simultaneous attempts can exhaust available capacity.); 4. You cross your own rate limit (Application or provider limits may reject additional work.); 5. The loop retries the 429s (An attempt counter with no deadline keeps spending the request’s budget.); 6. Your service is down (The application may fail under amplified load.). A hypothetical slowdown can amplify load if new attempts overlap uncertain earlier requests. Concurrency limits, a retry budget and a circuit breaker address different parts of the failure chain."}},"blocks":[{"t":"h2","id":"decide-whether-another-attempt-can-help","runs":[{"text":"Decide whether another attempt can help"}]},{"t":"p","runs":[{"text":"Inspect the provider’s documented status and error body. Correct an invalid request or permission problem before sending it again. A rate limit or temporary server error may justify a bounded later attempt. A timeout or broken connection can leave the first request’s outcome uncertain."}]},{"t":"p","runs":[{"text":"For the Claude Python SDK, automatic retries are enabled by default for selected failures. When you implement an outer retry loop, disable SDK retries so the two policies do not multiply attempts. The example below retries only the selected HTTP status failures. It lets connection and timeout exceptions reach the caller for an explicit decision. "},{"text":"SDK retries and errors","href":"https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/python"},{"text":"."}]},{"t":"h2","id":"backoff-with-jitter-and-why-jitter-is-not-optional","runs":[{"text":"Backoff, with jitter, and why jitter is not optional"}]},{"t":"code","lang":"python","label":"Python","text":"import random\nimport time\nfrom anthropic import APIStatusError\n\nRETRYABLE = {429, 500, 502, 503, 529}\n\ndef create_with_retries(\n    client, request, attempts=4, budget_s=25\n):\n    if attempts < 1 or budget_s <= 0:\n        raise ValueError(\n            \"Attempts and time budget \"\n            \"must be positive\"\n        )\n    api = client.with_options(max_retries=0)\n    expires = time.monotonic() + budget_s\n    for attempt in range(attempts):\n        remaining = expires - time.monotonic()\n        if remaining <= 0:\n            raise TimeoutError(\n                \"No time remains for another attempt\"\n            )\n        try:\n            return api.messages.create(\n                **request, timeout=remaining\n            )\n        except APIStatusError as error:\n            if error.status_code not in RETRYABLE:\n                raise\n            if attempt == attempts - 1:\n                raise\n            header = error.response.headers.get(\"retry-after\")\n            try:\n                wait = max(0.0, float(header))\n            except (TypeError, ValueError):\n                wait = min(2 ** attempt, 8) * (\n                    0.5 + random.random()\n                )\n            if wait >= expires - time.monotonic():\n                raise TimeoutError(\n                    \"Retry would exceed the time budget\"\n                ) from error\n            time.sleep(wait)"},{"t":"p","runs":[{"text":"Pass the helper a request dictionary containing the model, messages and output cap, as in the earlier examples. The helper checks the remaining budget before each attempt and wait, and passes that remaining time as the request timeout. This is client-side scheduling, not a guarantee that server execution stops at that instant. SDK HTTP timeouts also have transport-level semantics, so measure elapsed time and enforce any stricter outer deadline in the application."}]},{"t":"p","runs":[{"text":"The example handles a numeric "},{"text":"retry-after","code":true},{"text":" value in seconds. A production adapter should also support an HTTP-date header when the provider uses that form. Its fallback uses exponential backoff with jitter. Keep the total attempt and elapsed-time policy visible in logs."}]},{"t":"h2","id":"the-retry-storm-that-is-your-fault","runs":[{"text":"The retry storm that is your fault"}]},{"t":"p","runs":[{"text":"Here is the failure mode worth internalising, because it is self-inflicted."}]},{"t":"p","runs":[{"text":"Suppose a provider slows from two seconds to twenty. If a ten-second client timeout triggers another request while the first is still running, work can overlap. Repeated across many users, extra attempts can exhaust your concurrency or rate limits. Whether the first call continues and is billed depends on its outcome and the provider. Log uncertain outcomes and avoid treating a dropped connection as proof that no generation occurred."}]},{"t":"p","runs":[{"text":"The defences are all boring:"}]},{"t":"ul","items":[[{"text":"A concurrency cap","b":true},{"text":": a semaphore around outbound calls. Above it, queue or shed load. A number you chose beats a number your connection pool chose for you."}],[{"text":"A circuit breaker.","b":true},{"text":" After N consecutive failures, stop calling for 30 seconds and fail fast. This is counter-intuitive and correct: when a dependency is unhealthy, the kindest thing you can do is stop sending it traffic."}],[{"text":"A total budget per user request","b":true},{"text":": attempts and seconds, both capped."}],[{"text":"Shed the retry on non-interactive paths.","b":true},{"text":" A background job can wait a minute. A user cannot."}]]},{"t":"h2","id":"timeouts-on-a-streaming-call","runs":[{"text":"Timeouts on a streaming call"}]},{"t":"p","runs":[{"text":"A stream may need both an inactivity timeout and a total elapsed-time budget. The inactivity limit catches a stalled connection. The total budget limits how long the task may occupy resources. Select both for the task and the deployed infrastructure."}]},{"t":"h2","id":"retries-and-duplicates","runs":[{"text":"Retries and duplicates"}]},{"t":"p","runs":[{"text":"A retry can create another generation and another charge when the provider accepts and processes it. The returned text can differ. Before retrying an uncertain outcome, consider whether the original request or a tool it triggered could already have changed external state."}]},{"t":"p","runs":[{"text":"So: "},{"text":"keep side effects out of the retried region","b":true},{"text":", or make them idempotent. If your loop retries an entire agent turn, and step three of that turn charged a card, a network blip has now charged it twice. Give every externally visible action a key derived from the request, store the key, and make the second attempt a no-op. This is ordinary distributed-systems hygiene, and putting a model in the loop does not exempt you from it: it makes it more likely, because agent loops retry more."}]}],"check":{"question":[{"text":"A service retries slow requests while the original calls may still be running. Which mechanism can raise its own error rate?"}],"options":[{"text":[{"text":"Slow responses are truncated by the provider, so the results fail validation."}],"correct":false,"tempting":[{"text":"Confuses latency with truncation; a slow response still completes normally and carries a normal stop reason."}]},{"text":[{"text":"The model degrades under load and produces malformed output."}],"correct":false,"tempting":[{"text":"Attributes a queueing problem to generation quality, when the same weights produce the same distribution regardless of how busy the servers are."}]},{"text":[{"text":"Overlapping attempts multiply work until concurrency or rate limits are exhausted."}],"correct":true,"tempting":null},{"text":[{"text":"The retries are being served by a different, weaker model as a fallback."}],"correct":false,"tempting":[{"text":"Assumes a fallback that only exists if you wrote one, and would not by itself produce a sixfold error rate."}]}],"order":[3,2,0,1],"why":null},"prev":{"slug":"reading-the-response","title":"Every field in the response, and the two that catch bugs","minutes":8},"next":{"slug":"choosing-a-model","title":"Choosing a model, and designing so you can change your mind","minutes":9}}}