{"id":"6b093ddfbd4755deb67ee092","slug":"retry-with-backoff","title":"Retry with exponential backoff","summary":"A function that retries a failed operation after 100, 200, 400… ms, with a cap and an error filter. The sleep function is injected, so tests never wait a millisecond.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"easy","topics":["circuit-breaker"],"techs":["typescript","javascript","python","dotnet","java","go"],"tags":["resilience","backoff","higher-order-functions","dependency-injection","async"],"languages":[{"lang":"typescript","runner":"browser","starter":"interface RetryOptions {\n  retries: number;\n  baseDelayMs: number;\n  maxDelayMs?: number;\n  shouldRetry?: (error: unknown) => boolean;\n  sleep?: (ms: number) => Promise<void>;\n}\n\n/**\n * Calls operation(attempt) until it succeeds, at most retries + 1 times.\n * Delay before the k-th retry: min(maxDelayMs, baseDelayMs * 2^(k-1)).\n */\nasync function retry<T>(operation: (attempt: number) => T | Promise<T>, options: RetryOptions): Promise<T> {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":9,"tests":"function failingTimes(n, value = 'ok') {\n  const attempts = [];\n  const operation = (attempt) => {\n    attempts.push(attempt);\n    if (attempts.length <= n) throw new Error('fail ' + attempts.length);\n    return value;\n  };\n  return { operation, attempts };\n}\n\nfunction recorder() {\n  const delays = [];\n  return { delays, sleep: async (ms) => { delays.push(ms); } };\n}\n\ntest('returns the result of the first successful attempt', async () => {\n  const { operation, attempts } = failingTimes(0, 42);\n  const { delays, sleep } = recorder();\n  expect(await retry(operation, { retries: 3, baseDelayMs: 100, sleep })).toBe(42);\n  expect(attempts).toEqual([1]);\n  expect(delays).toEqual([]);\n});\n\ntest('retries with doubling delays until success', async () => {\n  const { operation, attempts } = failingTimes(2);\n  const { delays, sleep } = recorder();\n  expect(await retry(operation, { retries: 5, baseDelayMs: 100, sleep })).toBe('ok');\n  expect(attempts).toEqual([1, 2, 3]);\n  expect(delays).toEqual([100, 200]);\n});\n\ntest('gives up after retries + 1 attempts and rethrows the last error', async () => {\n  const { operation, attempts } = failingTimes(99);\n  const { delays, sleep } = recorder();\n  let caught = null;\n  try {\n    await retry(operation, { retries: 3, baseDelayMs: 100, sleep });\n  } catch (e) {\n    caught = e;\n  }\n  expect(caught).toBeInstanceOf(Error);\n  expect(caught.message).toBe('fail 4');\n  expect(attempts).toEqual([1, 2, 3, 4]);\n  expect(delays).toEqual([100, 200, 400]);\n});\n\ntest('retries = 0 means a single attempt', async () => {\n  const { operation, attempts } = failingTimes(1);\n  const { delays, sleep } = recorder();\n  let caught = null;\n  try {\n    await retry(operation, { retries: 0, baseDelayMs: 100, sleep });\n  } catch (e) {\n    caught = e;\n  }\n  expect(caught && caught.message).toBe('fail 1');\n  expect(attempts).toEqual([1]);\n  expect(delays).toEqual([]);\n});\n\ntest('delays are capped by maxDelayMs', async () => {\n  const { operation } = failingTimes(5);\n  const { delays, sleep } = recorder();\n  await retry(operation, { retries: 5, baseDelayMs: 100, maxDelayMs: 300, sleep });\n  expect(delays).toEqual([100, 200, 300, 300, 300]);\n});\n\ntest('shouldRetry = false stops immediately', async () => {\n  const fatal = new Error('fatal');\n  let calls = 0;\n  const operation = () => {\n    calls++;\n    throw calls === 1 ? new Error('transient') : fatal;\n  };\n  const { delays, sleep } = recorder();\n  let caught = null;\n  try {\n    await retry(operation, { retries: 10, baseDelayMs: 50, sleep, shouldRetry: (e) => e.message === 'transient' });\n  } catch (e) {\n    caught = e;\n  }\n  expect(caught).toBe(fatal);\n  expect(calls).toBe(2);\n  expect(delays).toEqual([50]);\n});\n\ntest('async operations and sleep are awaited', async () => {\n  let slept = 0;\n  const sleep = (ms) => new Promise((resolve) => setTimeout(() => { slept += ms; resolve(); }, 0));\n  const operation = async (attempt) => {\n    if (attempt === 1) throw new Error('first');\n    if (slept !== 100) throw new Error('sleep was not awaited');\n    return 'done';\n  };\n  expect(await retry(operation, { retries: 2, baseDelayMs: 100, sleep })).toBe('done');\n});\n\ntest('default sleep uses real timers', async () => {\n  const { operation, attempts } = failingTimes(2);\n  expect(await retry(operation, { retries: 2, baseDelayMs: 1 })).toBe('ok');\n  expect(attempts).toEqual([1, 2, 3]);\n});\n\ntest('many retries: delays never exceed the cap', async () => {\n  const { operation, attempts } = failingTimes(1000);\n  const { delays, sleep } = recorder();\n  try {\n    await retry(operation, { retries: 100, baseDelayMs: 1000, maxDelayMs: 30000, sleep });\n  } catch (e) {\n    /* expected */\n  }\n  expect(attempts).toHaveLength(101);\n  expect(delays).toHaveLength(100);\n  expect(delays.every((d) => d > 0 && d <= 30000)).toBe(true);\n  expect(delays[99]).toBe(30000);\n});\n"},{"lang":"javascript","runner":"browser","starter":"/**\n * Calls operation(attempt) until it succeeds, at most retries + 1 times.\n * Delay before the k-th retry: min(maxDelayMs, baseDelayMs * 2^(k-1)).\n * @param {(attempt: number) => any} operation\n * @param {{ retries: number, baseDelayMs: number, maxDelayMs?: number,\n *           shouldRetry?: (error: unknown) => boolean, sleep?: (ms: number) => Promise<void> }} options\n */\nasync function retry(operation, options) {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":9,"tests":"function failingTimes(n, value = 'ok') {\n  const attempts = [];\n  const operation = (attempt) => {\n    attempts.push(attempt);\n    if (attempts.length <= n) throw new Error('fail ' + attempts.length);\n    return value;\n  };\n  return { operation, attempts };\n}\n\nfunction recorder() {\n  const delays = [];\n  return { delays, sleep: async (ms) => { delays.push(ms); } };\n}\n\ntest('returns the result of the first successful attempt', async () => {\n  const { operation, attempts } = failingTimes(0, 42);\n  const { delays, sleep } = recorder();\n  expect(await retry(operation, { retries: 3, baseDelayMs: 100, sleep })).toBe(42);\n  expect(attempts).toEqual([1]);\n  expect(delays).toEqual([]);\n});\n\ntest('retries with doubling delays until success', async () => {\n  const { operation, attempts } = failingTimes(2);\n  const { delays, sleep } = recorder();\n  expect(await retry(operation, { retries: 5, baseDelayMs: 100, sleep })).toBe('ok');\n  expect(attempts).toEqual([1, 2, 3]);\n  expect(delays).toEqual([100, 200]);\n});\n\ntest('gives up after retries + 1 attempts and rethrows the last error', async () => {\n  const { operation, attempts } = failingTimes(99);\n  const { delays, sleep } = recorder();\n  let caught = null;\n  try {\n    await retry(operation, { retries: 3, baseDelayMs: 100, sleep });\n  } catch (e) {\n    caught = e;\n  }\n  expect(caught).toBeInstanceOf(Error);\n  expect(caught.message).toBe('fail 4');\n  expect(attempts).toEqual([1, 2, 3, 4]);\n  expect(delays).toEqual([100, 200, 400]);\n});\n\ntest('retries = 0 means a single attempt', async () => {\n  const { operation, attempts } = failingTimes(1);\n  const { delays, sleep } = recorder();\n  let caught = null;\n  try {\n    await retry(operation, { retries: 0, baseDelayMs: 100, sleep });\n  } catch (e) {\n    caught = e;\n  }\n  expect(caught && caught.message).toBe('fail 1');\n  expect(attempts).toEqual([1]);\n  expect(delays).toEqual([]);\n});\n\ntest('delays are capped by maxDelayMs', async () => {\n  const { operation } = failingTimes(5);\n  const { delays, sleep } = recorder();\n  await retry(operation, { retries: 5, baseDelayMs: 100, maxDelayMs: 300, sleep });\n  expect(delays).toEqual([100, 200, 300, 300, 300]);\n});\n\ntest('shouldRetry = false stops immediately', async () => {\n  const fatal = new Error('fatal');\n  let calls = 0;\n  const operation = () => {\n    calls++;\n    throw calls === 1 ? new Error('transient') : fatal;\n  };\n  const { delays, sleep } = recorder();\n  let caught = null;\n  try {\n    await retry(operation, { retries: 10, baseDelayMs: 50, sleep, shouldRetry: (e) => e.message === 'transient' });\n  } catch (e) {\n    caught = e;\n  }\n  expect(caught).toBe(fatal);\n  expect(calls).toBe(2);\n  expect(delays).toEqual([50]);\n});\n\ntest('async operations and sleep are awaited', async () => {\n  let slept = 0;\n  const sleep = (ms) => new Promise((resolve) => setTimeout(() => { slept += ms; resolve(); }, 0));\n  const operation = async (attempt) => {\n    if (attempt === 1) throw new Error('first');\n    if (slept !== 100) throw new Error('sleep was not awaited');\n    return 'done';\n  };\n  expect(await retry(operation, { retries: 2, baseDelayMs: 100, sleep })).toBe('done');\n});\n\ntest('default sleep uses real timers', async () => {\n  const { operation, attempts } = failingTimes(2);\n  expect(await retry(operation, { retries: 2, baseDelayMs: 1 })).toBe('ok');\n  expect(attempts).toEqual([1, 2, 3]);\n});\n\ntest('many retries: delays never exceed the cap', async () => {\n  const { operation, attempts } = failingTimes(1000);\n  const { delays, sleep } = recorder();\n  try {\n    await retry(operation, { retries: 100, baseDelayMs: 1000, maxDelayMs: 30000, sleep });\n  } catch (e) {\n    /* expected */\n  }\n  expect(attempts).toHaveLength(101);\n  expect(delays).toHaveLength(100);\n  expect(delays.every((d) => d > 0 && d <= 30000)).toBe(true);\n  expect(delays[99]).toBe(30000);\n});\n"},{"lang":"python","runner":"browser","starter":"import time\n\n\ndef retry(operation, retries, base_delay, max_delay=float(\"inf\"), should_retry=None, sleep=time.sleep):\n    \"\"\"Calls operation(attempt) until it succeeds, at most retries + 1 times.\n    Delay before the k-th retry: min(max_delay, base_delay * 2 ** (k - 1)).\"\"\"\n    raise NotImplementedError\n","testCount":8,"tests":"class Failing:\n    def __init__(self, times, value=\"ok\"):\n        self.times, self.value, self.attempts = times, value, []\n\n    def __call__(self, attempt):\n        self.attempts.append(attempt)\n        if len(self.attempts) <= self.times:\n            raise ConnectionError(f\"fail {len(self.attempts)}\")\n        return self.value\n\n\ndef eq(got, expected, what):\n    assert got == expected, f\"{what}: expected {expected!r}, got {got!r}\"\n\n\ndef test_returns_result_of_first_successful_attempt():\n    op, delays = Failing(0, 42), []\n    eq(retry(op, 3, 100, sleep=delays.append), 42, \"result\")\n    eq(op.attempts, [1], \"attempts\")\n    eq(delays, [], \"delays\")\n\n\ndef test_retries_with_doubling_delays_until_success():\n    op, delays = Failing(2), []\n    eq(retry(op, 5, 100, sleep=delays.append), \"ok\", \"result\")\n    eq(op.attempts, [1, 2, 3], \"attempts\")\n    eq(delays, [100, 200], \"delays\")\n\n\ndef test_gives_up_and_reraises_the_last_error():\n    op, delays = Failing(99), []\n    with raises(ConnectionError, match=\"fail 4\"):\n        retry(op, 3, 100, sleep=delays.append)\n    eq(op.attempts, [1, 2, 3, 4], \"attempts\")\n    eq(delays, [100, 200, 400], \"delays\")\n\n\ndef test_zero_retries_means_a_single_attempt():\n    op, delays = Failing(1), []\n    with raises(ConnectionError, match=\"fail 1\"):\n        retry(op, 0, 100, sleep=delays.append)\n    eq(op.attempts, [1], \"attempts\")\n    eq(delays, [], \"delays\")\n\n\ndef test_delays_are_capped():\n    op, delays = Failing(5), []\n    retry(op, 5, 100, max_delay=300, sleep=delays.append)\n    eq(delays, [100, 200, 300, 300, 300], \"delays\")\n\n\ndef test_should_retry_false_stops_immediately():\n    fatal = ValueError(\"fatal\")\n    calls = []\n\n    def op(attempt):\n        calls.append(attempt)\n        raise ConnectionError(\"transient\") if attempt == 1 else fatal\n\n    delays = []\n    try:\n        retry(op, 10, 50, sleep=delays.append, should_retry=lambda e: isinstance(e, ConnectionError))\n        raise AssertionError(\"expected ValueError\")\n    except ValueError as e:\n        assert e is fatal, \"the original error object should be re-raised\"\n    eq(calls, [1, 2], \"attempts\")\n    eq(delays, [50], \"delays\")\n\n\ndef test_works_with_float_seconds():\n    op, delays = Failing(3), []\n    retry(op, 3, 0.25, max_delay=1.0, sleep=delays.append)\n    eq(delays, [0.25, 0.5, 1.0], \"delays\")\n\n\ndef test_many_retries_never_exceed_the_cap():\n    op, delays = Failing(1000), []\n    with raises(ConnectionError):\n        retry(op, 100, 1000, max_delay=30000, sleep=delays.append)\n    eq(len(op.attempts), 101, \"attempts\")\n    eq(len(delays), 100, \"sleeps\")\n    assert all(0 < d <= 30000 for d in delays), \"every delay must be in (0, 30000]\"\n    eq(delays[-1], 30000, \"last delay\")\n"},{"lang":"csharp","runner":"judge0","starter":"using System;\n\npublic static class Solution\n{\n    /// <summary>\n    /// Calls operation(attempt) until it succeeds, at most retries + 1 times.\n    /// Delay before the k-th retry: min(maxDelayMs, baseDelayMs * 2^(k-1)).\n    /// </summary>\n    public static T Retry<T>(Func<int, T> operation, int retries, int baseDelayMs, int maxDelayMs,\n        Action<int> sleep, Func<Exception, bool> shouldRetry = null)\n    {\n        throw new NotImplementedException();\n    }\n}\n","testCount":7},{"lang":"java","runner":"judge0","starter":"import java.util.function.*;\n\nclass Solution {\n    /**\n     * Calls operation(attempt) until it succeeds, at most retries + 1 times.\n     * Delay before the k-th retry: min(maxDelayMs, baseDelayMs * 2^(k-1)). shouldRetry may be null.\n     */\n    static <T> T retry(IntFunction<T> operation, int retries, long baseDelayMs, long maxDelayMs,\n                       LongConsumer sleep, Predicate<RuntimeException> shouldRetry) {\n        throw new UnsupportedOperationException(\"Not implemented\");\n    }\n}\n","testCount":7},{"lang":"go","runner":"judge0","starter":"package main\n\nimport \"time\"\n\n// Retry calls operation(attempt) until it returns nil, at most retries+1 times.\n// Delay before the k-th retry: min(maxDelay, baseDelay * 2^(k-1)).\n// A nil shouldRetry retries every error. Returns nil or the last error.\nfunc Retry(operation func(attempt int) error, retries int, baseDelay, maxDelay time.Duration,\n\tsleep func(time.Duration), shouldRetry func(error) bool) error {\n\tpanic(\"not implemented\")\n}\n","testCount":7}],"questionCount":null,"xp":10,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:55.300Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"An external API sometimes answers 503, but works again a moment later. Instead of giving up immediately we retry – waiting "},{"type":"text","text":"twice as long","marks":[{"type":"bold"}]},{"type":"text","text":" each time so we do not hammer an overloaded service. The sleep function is "},{"type":"text","text":"injected","marks":[{"type":"bold"}]},{"type":"text","text":", so tests check the delays without really waiting."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"paragraph","content":[{"type":"text","text":"retry","marks":[{"type":"code"}]},{"type":"text","text":" calls "},{"type":"text","text":"operation(attempt)","marks":[{"type":"code"}]},{"type":"text","text":" (attempt numbers start at 1):"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"success → return the operation's result,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"error → if retries are left and the error is retryable, sleep for "},{"type":"text","text":"delay","marks":[{"type":"code"}]},{"type":"text","text":" and try again,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"the delay before the "},{"type":"text","text":"k","marks":[{"type":"code"}]},{"type":"text","text":"-th retry is "},{"type":"text","text":"min(maxDelay, baseDelay · 2^(k−1))","marks":[{"type":"code"}]},{"type":"text","text":" – i.e. "},{"type":"text","text":"base","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"2·base","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"4·base","marks":[{"type":"code"}]},{"type":"text","text":"… up to the cap,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"there are at most "},{"type":"text","text":"retries + 1","marks":[{"type":"code"}]},{"type":"text","text":" attempts in total; after the last failed attempt the function throws the "},{"type":"text","text":"last","marks":[{"type":"bold"}]},{"type":"text","text":" error (the same object, not wrapped),"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"shouldRetry(error)","marks":[{"type":"code"}]},{"type":"text","text":" returning false stops retrying immediately (no sleep) and throws that error; no "},{"type":"text","text":"shouldRetry","marks":[{"type":"code"}]},{"type":"text","text":" = retry every error."}]}]}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Language"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Signature"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"JS/TS"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"await retry(operation, { retries, baseDelayMs, maxDelayMs = Infinity, shouldRetry?, sleep? })","marks":[{"type":"code"}]},{"type":"text","text":" – "},{"type":"text","text":"operation","marks":[{"type":"code"}]},{"type":"text","text":" may return a value or a "},{"type":"text","text":"Promise","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"sleep(ms)","marks":[{"type":"code"}]},{"type":"text","text":" returns a "},{"type":"text","text":"Promise","marks":[{"type":"code"}]},{"type":"text","text":" (defaults to "},{"type":"text","text":"setTimeout","marks":[{"type":"code"}]},{"type":"text","text":")"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Python"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"retry(operation, retries, base_delay, max_delay=inf, should_retry=None, sleep=time.sleep)","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"C#"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Solution.Retry<T>(Func<int, T> operation, int retries, int baseDelayMs, int maxDelayMs, Action<int> sleep, Func<Exception, bool> shouldRetry = null)","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Java"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Solution.retry(IntFunction<T> operation, int retries, long baseDelayMs, long maxDelayMs, LongConsumer sleep, Predicate<RuntimeException> shouldRetry)","marks":[{"type":"code"}]},{"type":"text","text":" – "},{"type":"text","text":"shouldRetry","marks":[{"type":"code"}]},{"type":"text","text":" may be "},{"type":"text","text":"null","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Go"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Retry(operation func(attempt int) error, retries int, baseDelay, maxDelay time.Duration, sleep func(time.Duration), shouldRetry func(error) bool) error","marks":[{"type":"code"}]},{"type":"text","text":" – "},{"type":"text","text":"nil","marks":[{"type":"code"}]},{"type":"text","text":" means success"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"example"},"content":[{"type":"text","text":"Example"}]},{"type":"paragraph","content":[{"type":"text","text":"retries = 3","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"baseDelay = 100","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"maxDelay = 300","marks":[{"type":"code"}]},{"type":"text","text":", the operation succeeds on the fourth attempt:"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Attempt"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Result"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Then"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"1"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"error"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"sleep(100)","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"2"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"error"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"sleep(200)","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"3"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"error"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"sleep(300)","marks":[{"type":"code"}]},{"type":"text","text":" – the cap instead of 400"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"4"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"success"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"return the result"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"constraints"},"content":[{"type":"text","text":"Constraints"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"0 ≤ retries ≤ 100","marks":[{"type":"code"}]},{"type":"text","text":", "},{"type":"text","text":"1 ≤ baseDelay ≤ maxDelay ≤ 10⁹","marks":[{"type":"code"}]},{"type":"text","text":" (C#/Java/Go)."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The delay must not overflow or turn negative, even with 100 retries."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"expected-complexity"},"content":[{"type":"text","text":"Expected complexity"}]},{"type":"paragraph","content":[{"type":"text","text":"O(retries)","marks":[{"type":"bold"}]},{"type":"text","text":" time besides the operation and the sleeping, "},{"type":"text","text":"O(1)","marks":[{"type":"bold"}]},{"type":"text","text":" memory."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[],"articles":[{"id":"6b093dbf91bd8fbaf2a0c8a7","slug":"circuit-breaker","title":"Circuit breaker: turning a slow failure into a fast one"}],"topicsInfo":[{"slug":"circuit-breaker","title":"Circuit Breaker","group":"architecture","icon":"zap-off"}],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:55.301Z","updatedAt":"2026-11-27T08:22:55.301Z"}