Skip to content

feat: implement graceful backoff on rate limits - #176

Closed
binbandit wants to merge 13 commits into
openai:mainfrom
binbandit:feat/rate-limit-backoff
Closed

binbandit wants to merge 13 commits into
openai:mainfrom
binbandit:feat/rate-limit-backoff

Conversation

@binbandit

Copy link
Copy Markdown
Contributor

Description

This PR implements a more sophisticated rate limit handling mechanism with exponential backoff and jitter (Fixes #137). When the API returns a rate limit error, the client will now use a configurable exponential backoff strategy with jitter to avoid the "thundering herd" problem.

Changes

  • Added configurable rate limit settings to the app configuration
  • Implemented exponential backoff with jitter for rate limit retries
  • Added support for parsing and respecting API-suggested retry times
  • Updated tests to verify both default and custom rate limit configurations
  • Made all rate limit parameters configurable (max retries, initial delay, max delay, jitter factor)

Benefits

  • More resilient handling of rate limit errors
  • Reduced likelihood of cascading failures when multiple clients retry simultaneously
  • Better adherence to API-suggested retry times
  • Configurable settings allow users to customize retry behavior

Testing

  • Added tests for both default and custom rate limit configurations
  • Verified that the exponential backoff and jitter are correctly applied
  • Confirmed that API-suggested retry times are respected when provided

Additional Notes

The default settings are:

  • Max retries: 5
  • Initial retry delay: 2500ms
  • Maximum retry delay: 60000ms (1 minute)
  • Jitter factor: 0.25 (25% random jitter)

@tibo-openai

Copy link
Copy Markdown
Collaborator

ci failure

> @openai/[email protected] format
> prettier --check src tests

Checking formatting...
[warn] src/utils/agent/agent-loop.ts
[warn] src/utils/config.ts
[warn] tests/agent-rate-limit-error.test.ts
[warn] Code style issues found in 3 files. Forgot to run Prettier?

change looks great in general, ty!

@binbandit

Copy link
Copy Markdown
Contributor Author

ci failure

> @openai/[email protected] format
> prettier --check src tests

Checking formatting...
[warn] src/utils/agent/agent-loop.ts
[warn] src/utils/config.ts
[warn] tests/agent-rate-limit-error.test.ts
[warn] Code style issues found in 3 files. Forgot to run Prettier?

change looks great in general, ty!

addressed

@binbandit
binbandit force-pushed the feat/rate-limit-backoff branch from d3df4a7 to 7b6f490 Compare April 17, 2025 06:00
@main-horse

main-horse commented Apr 17, 2025 •

Copy link
Copy Markdown

the underlying cause of the failed type check here is the lack of the .summary attribute in the Reasoning interface until the most recent openai-node SDK update

I have the type-checking fixed here (ideally just cherry-pick d212c5b275b7779aeb265749ce158772d60ac805) but my PR got locked 😬

@main-horse

Copy link
Copy Markdown

also, like other users in #137, rate_limit_exceeded crashes still occur in both the main branch, and also on this PR branch

@tibo-openai

tibo-openai commented Apr 17, 2025 •

Copy link
Copy Markdown
Collaborator

@main-horse fixed the type error in #228, please incorporate that here and I will merge

@main-horse

main-horse commented Apr 17, 2025 •

Copy link
Copy Markdown

to be clear, this pull request does not appear to fully resolve the issue. here is an example result from my last commit:

[Error]: Rate limit reached for o4-mini in organization org-gHZLO7nuyDlyd5zXmeMhgfLC on tokens per min (TPM): Limit 200000, Used 153935, Requested 50854. Please try again in 1.436s. Visit https://platform.openai.com/account/rate-limits to learn more.
    at e.a [as iterator] (file:///home/main/codex/codex-cli/dist/cli.js:445:1514)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async E0.run (file:///home/main/codex/codex-cli/dist/cli.js:462:3049) {
  status: undefined,
  headers: undefined,
  request_id: undefined,
  error: {
    type: 'tokens',
    code: 'rate_limit_exceeded',
    message: 'Rate limit reached for o4-mini in organization org-gHZLO7nuyDlyd5zXmeMhgfLC on tokens per min (TPM): Limit 200000, Used 153935, Requested 50854. Please try again in 1.436s. Visit https://platform.openai.com/account/rate-limits to learn more.',
    param: null
  },
  code: 'rate_limit_exceeded',
  param: null,
  type: 'tokens'
}

you can also see exactly what i did as an asciinema recording in case it helps

(also I hope some maintainer can delete the PR I made... it's locked and I can't modify it)

@tibo-openai

tibo-openai commented Apr 17, 2025 •

Copy link
Copy Markdown
Collaborator

(also I hope some maintainer can delete the PR I made... it's locked and I can't modify it)

Doing that.

@tibo-openai

Copy link
Copy Markdown
Collaborator

this pull request does not appear to fully resolve the issue. here is an example result from my last commit

Do you have a suggested fix here, would be stellar to dig further into this and fix the root cause. Lots of folks are running into rate limiting issues.

Comment thread codex-cli/pnpm-lock.yaml Resolved
Comment thread codex-cli/src/utils/agent/agent-loop.ts Resolved
Comment thread README.md Resolved
Comment thread codex-cli/src/utils/config.ts Resolved
@tibo-openai

Copy link
Copy Markdown
Collaborator

Solves for #233

Comment thread README.md Resolved
@pourhadi

Copy link
Copy Markdown

Unfortunately I am still hitting the rate limit and crashing out with these changes.
image

@jonchurch

Copy link
Copy Markdown
Contributor

Checkout #266 @tibo-openai

I think this might be a much simpler bug than we imagine

@notatestuser

notatestuser commented Apr 18, 2025 •

Copy link
Copy Markdown

@jonchurch I'm still getting this with gpt-4.1. Built from main including your PR #266 - 0.1.2504161551.

e [Error]: Rate limit reached for gpt-4.1 in organization org-xxx on tokens per min (TPM): Limit 30000, Used 20978, Requested 9625. Please try again in 1.206s. Visit https://platform.openai.com/account/rate-limits to learn more.
    at e.a [as iterator] (file:///Users/xxx/codex/codex-cli/dist/cli.js:449:1514)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async T0.run (file:///Users/xxx/codex/codex-cli/dist/cli.js:466:2933) {
  status: undefined,
  headers: undefined,
  request_id: undefined,
  error: {
    type: 'tokens',
    code: 'rate_limit_exceeded',
    message: 'Rate limit reached for gpt-4.1 in organization org-xxx on tokens per min (TPM): Limit 30000, Used 20978, Requested 9625. Please try again in 1.206s. Visit https://platform.openai.com/account/rate-limits to learn more.',
    param: null
  },
  code: 'rate_limit_exceeded',
  param: null,
  type: 'tokens'
}

@tibo-openai

Copy link
Copy Markdown
Collaborator

@crazywolf132 are you still interested in pushing this forward? The changes in this PR are good to have and would like to decide whether to let others implement something similar or whether this one is the one that should get through.

@binbandit

Copy link
Copy Markdown
Contributor Author

Planning on continuing this PR, will return in around 24 hours.
Currently celebrating the easter holiday with my family 😃

If the issue is too critical, more than happy for someone else to take over so I am not a blocker

This was referenced Apr 20, 2025
@binbandit

Copy link
Copy Markdown
Contributor Author

@tibo-openai good to go

@samyarkd

Copy link
Copy Markdown

why is this not merged yet

@scottleibrand

Copy link
Copy Markdown
Contributor

This branch (specifically the version at https://github.com/scottleibrand/codex/tree/feat/rate-limit-backoff with merge conflicts and tests fixed) does not resolve the issue for me:

/Users/sleibrand/src/codex/codex-cli/node_modules/openai/src/streaming.ts:76
              throw new APIError(undefined, data.error, data.message, undefined);
                    ^


_APIError: Rate limit reached for organization org-<snip> on tokens per min (TPM): Limit 250000, Used 199752, Requested 55233. Please try again in 1.196s. Visit https://platform.openai.com/account/rate-limits to learn more.
    at _Stream.iterator (/Users/sleibrand/src/codex/codex-cli/node_modules/openai/src/streaming.ts:76:21)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at AgentLoop.run (/Users/sleibrand/src/codex/codex-cli/src/utils/agent/agent-loop.ts:802:28) {
  status: undefined,
  headers: undefined,
  request_id: undefined,
  error: {
    type: 'tokens',
    code: 'rate_limit_exceeded',
    message: 'Rate limit reached for organization org-<snip> on tokens per min (TPM): Limit 250000, Used 199752, Requested 55233. Please try again in 1.196s. Visit https://platform.openai.com/account/rate-limits to learn more.',
    param: null
  },
  code: 'rate_limit_exceeded',
  param: null,
  type: 'tokens'
}

Node.js v21.7.2

Will try #357 next.

@scottleibrand

Copy link
Copy Markdown
Contributor

FWIW I also opened #506 with an attempt at a minimal implementation of #357. I'm not sure if that is more of a substitute or a complement to the changes here: I'll defer to someone who actually knows what's going on to decide whether my observations are relevant to whether to continue forward with this PR.

@binbandit

Copy link
Copy Markdown
Contributor Author

@scottleibrand Please verify if the last version of this branch addresses the issue

@rjlee

rjlee commented Apr 22, 2025 •

Copy link
Copy Markdown

I've checked out the latest version of the branch and I still receive the error:

npm list -g
/Users/me/.nvm/versions/node/v22.14.0/lib
├── @openai/[email protected] -> ./../../../../../code/codex/codex-cli

codex "my command"
...

e [Error]: Rate limit reached for o4-mini in organization org-XXX on tokens per min (TPM): Limit 200000, Used 168651, Requested 39149. Please try again in 2.34s. Visit https://platform.openai.com/account/rate-limits to learn more.
    at e.a [as iterator] (file:///Users/robertlee/code/codex/codex-cli/dist/cli.js:475:1514)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async oE.run (file:///Users/robertlee/code/codex/codex-cli/dist/cli.js:492:3075) {
  status: undefined,
  headers: undefined,
  request_id: undefined,
  error: {
    type: 'tokens',
    code: 'rate_limit_exceeded',
    message: 'Rate limit reached for o4-mini in organization org-XXX on tokens per min (TPM): Limit 200000, Used 168651, Requested 39149. Please try again in 2.34s. Visit https://platform.openai.com/account/rate-limits to learn more.',
    param: null
  },
  code: 'rate_limit_exceeded',
  param: null,
  type: 'tokens'
}

It seemed to take longer to hit the limit, but it's still been hit.

@tibo-openai

Copy link
Copy Markdown
Collaborator

We have merged a number of improvements here and I will now close this one as I judge it as not necessary anymore. Thank you for the effort that went into making hitting rate limits more resilient!

@github-actions github-actions Bot locked and limited conversation to collaborators Apr 23, 2025
Nitjsefnie added a commit to Nitjsefnie-OSC/codex that referenced this pull request Aug 10, 2026
Return drained tool errors to the turn loop so code-mode infrastructure failures abort cleanly instead of panicking a worker and timing out the session.

Closes openai#176

Co-authored-by: GPT-5.6 Sol <[email protected]>
Nitjsefnie added a commit to Nitjsefnie-OSC/codex that referenced this pull request Aug 12, 2026
Return drained tool errors to the turn loop so code-mode infrastructure failures abort cleanly instead of panicking a worker and timing out the session.

Closes openai#176

Co-authored-by: GPT-5.6 Sol <[email protected]>
Nitjsefnie added a commit to Nitjsefnie-OSC/codex that referenced this pull request Aug 14, 2026
Return drained tool errors to the turn loop so code-mode infrastructure failures abort cleanly instead of panicking a worker and timing out the session.

Closes openai#176

Co-authored-by: GPT-5.6 Sol <[email protected]>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Graceful backoff on rate limits

10 participants