Skip to content

[Serve] Set RAY_SERVE_RUN_SYNC_IN_THREADPOOL=1 to run sync in threadpool by default - #61229

Merged
abrarsheikh merged 13 commits into
ray-project:masterfrom
petern48:set_RAY_SERVE_RUN_SYNC_IN_THREADPOOL
Feb 24, 2026
Merged

abrarsheikh merged 13 commits into
ray-project:masterfrom
petern48:set_RAY_SERVE_RUN_SYNC_IN_THREADPOOL

Conversation

@petern48

@petern48 petern48 commented Feb 21, 2026 •

Copy link
Copy Markdown
Contributor

Description

Set RAY_SERVE_RUN_SYNC_IN_THREADPOOL=1 to run sync in threadpool by default

Related issues

Fixes #61225

Additional information

As requested in the issue, I've added a one-time warning that explains method calls should be thread-safe or use async def instead. Additionally, there was an existing warning that the configuration would eventually be changed to default to 1. I've modified that warning to instead say that the method blocks async operations, and they can instead run it in the thread pool by setting the configuration to 1.

I ran the following script (toggling the environment variable), and verified that the corresponding warning message only appears once for both cases.

Script and resulting output
import os
os.environ["RAY_SERVE_RUN_SYNC_IN_THREADPOOL"] = "0"
from ray import serve

@serve.deployment
class SimpleSyncCounter:
    def __init__(self):
        self.count = 0
    def __call__(self, request=None):
        self.count += 1
        return self.count

def main():
    print(f"Using RAY_SERVE_RUN_SYNC_IN_THREADPOOL={os.environ['RAY_SERVE_RUN_SYNC_IN_THREADPOOL']}\n")
    h = serve.run(SimpleSyncCounter.bind(), _local_testing_mode=True)

    # Call multiple times to verify warning is only emitted once
    for i in range(10):
        result = h.remote().result()

Output for RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0

Using RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0

INFO 2026-02-22 09:18:30,295 serve 44725 -- Initializing local replica class for Deployment(name='SimpleSyncCounter', app='default').
/Users/peter/Documents/open-source/ray/python/ray/serve/_private/replica.py:2965: UserWarning: Calling sync method '__call__' directly on the asyncio loop because RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0. This blocks async operations. To run sync methods in a threadpool, set RAY_SERVE_RUN_SYNC_IN_THREADPOOL=1, or convert to `async def`.
  warnings.warn(

Output for RAY_SERVE_RUN_SYNC_IN_THREADPOOL=1

Using RAY_SERVE_RUN_SYNC_IN_THREADPOOL=1

INFO 2026-02-22 09:19:01,967 serve 44867 -- Initializing local replica class for Deployment(name='SimpleSyncCounter', app='default').
/Users/peter/Documents/open-source/ray/python/ray/serve/_private/replica.py:2926: UserWarning: Sync method '__call__' is running in a threadpool. Ensure your handler and shared state are thread-safe, or convert to `async def` for event-loop execution.
  warnings.warn(

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

The pull request updates the default behavior of RAY_SERVE_RUN_SYNC_IN_THREADPOOL to 1, meaning synchronous methods will now run in a threadpool by default. This change improves event loop responsiveness. The documentation and internal warnings have been updated to reflect this new default and to provide guidance on thread safety and how to opt out of the new behavior. The changes are well-documented and address the issue of blocking async operations.

Comment thread python/ray/serve/_private/constants.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/constants.py Resolved
Comment thread python/ray/serve/_private/constants.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/_private/replica.py Resolved
Comment thread python/ray/serve/tests/BUILD.bazel Resolved
@petern48

Copy link
Copy Markdown
Contributor Author

For some reason, Gemini just left a ton of review comments explaining each of my changes. None of them suggested any changes, so I just resolved them all.

@petern48
petern48 marked this pull request as ready for review February 21, 2026 18:11
@petern48
petern48 requested a review from a team as a code owner February 21, 2026 18:11
@abrarsheikh abrarsheikh added the go add ONLY when ready to merge, run all tests label Feb 21, 2026
@ray-gardener ray-gardener Bot added the community-contribution Contributed by the community label Feb 21, 2026
- The event loop is free to keep serving other requests while sync methods run.

You can opt in to the future behavior now by setting:
Ensure your handlers and shared state are thread-safe. If you opt out by setting:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good to have a code example here that shows what non-thread safe looks like.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done in 98cd89b

I also built the docs locally and verified that the code block renders properly

image

Comment on lines +2926 to +2928
warnings.warn(
RAY_SERVE_RUN_SYNC_IN_THREADPOOL_THREAD_SAFETY_WARNING.format(
method_name=callable.__name__,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please do a local run where this log line is seen, want to make sure the log is not repeated multiple times.

):
self._warned_about_sync_method_change = True
self._warned_about_sync_method_event_loop = True
warnings.warn(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please do a local run where this log line is seen. Add it to the PR description.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done and added to PR description for both warning messages

petern48 and others added 4 commits February 22, 2026 08:26
Co-authored-by: Abrar Sheikh <[email protected]>
Signed-off-by: Peter Nguyen <[email protected]>
Signed-off-by: Peter Nguyen <[email protected]>
Signed-off-by: Peter Nguyen <[email protected]>
@petern48
petern48 requested a review from abrarsheikh February 22, 2026 21:05
# __ray_parallel_end__


if __name__ == "__main__":

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please include the newly added examples under here so that they run as part of CI.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

RAY_SERVE_RUN_SYNC_IN_THREADPOOL_THREAD_SAFETY_WARNING.format(
method_name=callable.__name__,
)
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sync warning can repeat under concurrency

Medium Severity

The “warn only once” guard for the new threadpool warning uses a non-atomic check-then-set on self._warned_about_sync_method_threadpool, so concurrent requests can race and emit the warning multiple times.

Fix in Cursor Fix in Web

@abrarsheikh

Copy link
Copy Markdown
Contributor

try merging master again, I think that will fix it

@abrarsheikh
abrarsheikh merged commit 9e1fa2e into ray-project:master Feb 24, 2026
3 checks passed
@petern48
petern48 deleted the set_RAY_SERVE_RUN_SYNC_IN_THREADPOOL branch February 24, 2026 03:41
akyang-anyscale added a commit to akyang-anyscale/ray that referenced this pull request Feb 26, 2026
… threadpool by default (ray-project#61229)"

This reverts commit 9e1fa2e.

Signed-off-by: akyang-anyscale <[email protected]>
abrarsheikh pushed a commit that referenced this pull request Feb 26, 2026
#61369)

… threadpool by default (#61229)"

This reverts commit 9e1fa2e. Enabling
the flag by default introduces a significant perf regression for
lightweight workloads that are sensitive to context switching and that
do not take full advantage of offloading work from python. will post a
RFC for community feedback before making this the default

> Thank you for contributing to Ray! 🚀
> Please review the [Ray Contribution
Guide](https://docs.ray.io/en/master/ray-contribute/getting-involved.html)
before opening a pull request.

> ⚠️ Remove these instructions before submitting your PR.

> 💡 Tip: Mark as draft if you want early feedback, or ready for review
when it's complete.

## Description
> Briefly describe what this PR accomplishes and why it's needed.

## Related issues
> Link related issues: "Fixes #1234", "Closes #1234", or "Related to
#1234".

## Additional information
> Optional: Add implementation details, API changes, usage examples,
screenshots, etc.

Signed-off-by: akyang-anyscale <[email protected]>
eicherseiji added a commit that referenced this pull request Sep 29, 2026
## Description

Run synchronous deployment methods in a thread pool by default so
blocking synchronous I/O does not block the replica event loop.
`RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0` retains the legacy behavior for
deployments whose shared state is not thread-safe.

| Environment variable | `master` | After this PR |
| --- | --- | --- |
| `RAY_SERVE_RUN_SYNC_IN_THREADPOOL` | OFF | ON |

The opt-in warning has been emitted since
[#48897](#48897) merged on
November 26, 2024—667 days (about 22 months) before this default swap.
This provided an extended migration period for users to make synchronous
deployment code thread-safe or convert it to `async def`.

The documentation now describes thread safety requirements and the
opt-out. This default was previously enabled in
[#61229](#61229) and reverted in
[#61369](#61369).

## Related PRs

These default changes are independent and can merge in any order:

- [#66432 Enable HAProxy by default on
Linux](#66432)
- [#66434 Select request body forwarding by
router](#66434)
- [#66435 Apply Serve LLM replica performance
defaults](#66435)

## Tests

- `RAY_USE_UVLOOP=0 python -m pytest -q
python/ray/serve/tests/test_replica_sync_methods.py`: 9 passed. The
executor-introspection cases target the standard asyncio loop used by
this Bazel test.
- Updated the thread-pool test target description
- Pre-commit, including Ruff, Black, Buildifier, mypy, Pyrefly, docs
style, and import-order checks

## Duplicate search

I searched open Ray PRs for this environment variable and found no
active duplicate.

## AI assistance

AI assistance was used for implementation and testing. The generated
changes and test results require submitter review before the PR is
marked ready.

Signed-off-by: Seiji Eicher <[email protected]>
nadongjun pushed a commit to nadongjun/ray that referenced this pull request Oct 6, 2026
## Description

Run synchronous deployment methods in a thread pool by default so
blocking synchronous I/O does not block the replica event loop.
`RAY_SERVE_RUN_SYNC_IN_THREADPOOL=0` retains the legacy behavior for
deployments whose shared state is not thread-safe.

| Environment variable | `master` | After this PR |
| --- | --- | --- |
| `RAY_SERVE_RUN_SYNC_IN_THREADPOOL` | OFF | ON |

The opt-in warning has been emitted since
[ray-project#48897](ray-project#48897) merged on
November 26, 2024—667 days (about 22 months) before this default swap.
This provided an extended migration period for users to make synchronous
deployment code thread-safe or convert it to `async def`.

The documentation now describes thread safety requirements and the
opt-out. This default was previously enabled in
[ray-project#61229](ray-project#61229) and reverted in
[ray-project#61369](ray-project#61369).

## Related PRs

These default changes are independent and can merge in any order:

- [ray-project#66432 Enable HAProxy by default on
Linux](ray-project#66432)
- [ray-project#66434 Select request body forwarding by
router](ray-project#66434)
- [ray-project#66435 Apply Serve LLM replica performance
defaults](ray-project#66435)

## Tests

- `RAY_USE_UVLOOP=0 python -m pytest -q
python/ray/serve/tests/test_replica_sync_methods.py`: 9 passed. The
executor-introspection cases target the standard asyncio loop used by
this Bazel test.
- Updated the thread-pool test target description
- Pre-commit, including Ruff, Black, Buildifier, mypy, Pyrefly, docs
style, and import-order checks

## Duplicate search

I searched open Ray PRs for this environment variable and found no
active duplicate.

## AI assistance

AI assistance was used for implementation and testing. The generated
changes and test results require submitter review before the PR is
marked ready.

Signed-off-by: Seiji Eicher <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution Contributed by the community go add ONLY when ready to merge, run all tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Serve] set RAY_SERVE_RUN_SYNC_IN_THREADPOOL=1

2 participants