Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
from fastapi.concurrency import run_in_threadpool
async def execute(data: DataRequest) -> DataResponse:
try:
result = await run_in_threadpool(sync_function, data)
return DataResponse(data=result)
except Exception as e:
return DataResponse(
error=str(e),
success=False,
)
В общем работает нормально. Для всех вызовов под капотом используется общий тредпул, всё работает предсказуемо.
Но потребовалось изменить количество запускаемых в пуле потоков (по умолчанию создается 40 воркеров).
Так как дело происходит с FastAPI, делается это через lifespan используя настройки anyio:
import anyio
@asynccontextmanager
async def lifespan(app: FastAPI):
limiter = anyio.to_thread.current_default_thread_limiter()
limiter.total_tokens = 100
yield
# если вдруг нужно вернуть обратно
limiter.total_tokens = 40
Зачем менять количество воркеров?
- уменьшить, если оперативки мало (один тред занимает ~8мб)
- увеличить чтобы выдержать нагрузку
Если есть предложения получше при тех же вводных - предлагайте😉
#async
Latest offers:
Máster en Comercio Electrónico con WordPress 2026 by Renato Jesús Yacolca Neyra
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Master Course : Making the Business Case for Sustainability by Dr. José Prabhu J
👉Go To The Course
-----------
Teaching Methods, Teaching Quality & Teaching Delivery 3.0 by Dr. José Prabhu J
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Professional Diploma in Project Management by Md. Aliful Islam
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Master Course in Smart Cities, Urban Planning & Development by Dr. José Prabhu J
👉Go To The Course
-----------
Master Course in Corporate Social Responsibility (CSR) by Dr. José Prabhu J
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Master Course in Project Management 2.0 by Dr. José Prabhu J
👉Go To The Course
-----------
Multigenerational Leadership & Reskilling Your Organization by Dr. José Prabhu J
👉Go To The Course
-----------
Master Course in Climate Change Impact on Business by Dr. José Prabhu J
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
NumPy, SciPy, Matplotlib & Pandas A-Z: Machine Learning by Sara Academy
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Certificado Profissional em Liderança e Gestão by MTF Institute of Management, Technology and Finance
👉Go To The Course
-----------
Curso Completo de Mikrotik. Configuraciones y mucha Práctica by Alvaro Chirou , Kevin Lopez , Walter Coto , Ciberseguridad Hacking Seguridad Informática
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Programador Java en 37 Días Con práctica de Entrevista y más by Alvaro Chirou , Walter Coto , Kevin Lopez , Programación | Desarrollador Full Stack | FrontEnd | BackEnd | BD
👉Go To The Course
-----------
The Complete JavaScript Course: From Zero to Expert by Sara Academy
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Language Learning with AI: Practical Skills Guide by Andrii Piatakha
👉Go To The Course
-----------
AI for Customer Success: Transforming Customer Relationships by Andrii Piatakha
👉Go To The Course
-----------
AI for Business Analysts by Agile Enterprise Coach London
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Carbon Capture (CCUS): Governance, Policy, & Social License by Alex Chyzh
👉Go To The Course
-----------
Mastering Manus: AI Automation for Marketing & Content by Anton Voroniuk , Anton Voroniuk Support
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse
Latest offers:
Innovative AI Practices in Telemedicine & Virtual Care by Starweaver Team , Paul Siegel , Renate Zara
👉Go To The Course
-----------
Emotional Intelligence in Teams and Collaboration ( EQ ) by Starweaver Team , Paul Siegel , Eric Zackrison
👉Go To The Course
-----------
⚔️⚔️⚔️⚔️⚔️⚔️
Visit WebSite
@DiscountedCourseNinja
#FreeLearning#FreeCoupon
#UdemyCoupons#DiscountedCourse