Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Honored by Prof. Hiroshi Takahashi's generosity in sharing his AAS Review Paper on land-surface influences on Asian monsoon precipitation and recommending the full special issue. Grateful for such support in advancing #climatescience ! Explore his study: https://link.springer.com/article/10.1007/s00376-026-5209-3#AAS
via @aasjournal.bsky.social - Adv. Atmos. Sci.
At the Ocean-Monsoon Conference 2026, @agturnermonsoon.bsky.social of the University of Reading presented a striking visual: the same location in India, captured under drought and active monsoon conditions. Two extremes. One region. A powerful reminder of what is at stake. 🧵👇#AAS#Climatescience
via @aasjournal.bsky.social - Adv. Atmos. Sci.
#Scientific_American🇺🇸📕[PDF]⬇️
#December2025
#Monthly_Magazines
For learning, for free(dom).
@backupofmagazines
NASA faces a stalled Mars sample-return mission as funding reshapes priorities in #TechPolicy, while a promising mRNA-based personalized cancer vaccine struggles amid shrinking research budgets in the U.S., underscoring a rising #HealthCrisis. Scientists also warn that deepfakes demand new “face-ownership” rights, adding momentum to global #AIRegulation. Fresh insights into black-hole limits and rare-earth formation expand our cosmic and geologic imagination, even as #ClimateScience pushes oil and gas giants to pivot toward plastics. New antidepressant treatments and studies on small daily joys highlight a parallel #MentalHealth shift across society.
#The_National_Geographic🇺🇸📕[PDF]⬇️
#December2025
#Monthly_Magazines
For learning, for free(dom).
@backupofmagazines
This issue captures a world in transition, from ancient engineering puzzles to the fragile future of memory. Stunning visuals highlight global migration, ecological risk and cultural resilience, while scientists push deeper into #ClimateScience and #Neuroscience. A precise Mesopotamian map surprises historians, and a tribute to Jane Goodall reflects on her transformative legacy in #WildlifeResearch. The “Pictures of the Year” series showcases unforgettable scenes shaped by conflict, migration and #GlobalCulture. As melting ice reveals prehistoric secrets, explorers race against time, reminding us how fragile our world is in the age of #EarthChange and #FutureTech.
#The_Science🇺🇸📕[PDF]⬇️
16 #October2025
#Weekly_Magazines
For learning, for free(dom).
@backupofmagazines
This week’s Science dives deep into the frontiers of #Nanoscopy, visualizing neural circuits with stunning 3D precision. From Arctic #Permafrost preserving ancient RNA viruses to #Ant colonies evolving architectural immunity, the issue spans from the microscopic to the planetary. Groundbreaking work tracks #SeaLevel change over 4.5 million years and explores durable #Hydrogen production membranes and electric control in #2Dmaterials. The “#ColdStorage” feature warns of hidden viral archives in melting ice—a chilling insight into #ClimateScience and future pandemics. A visionary issue linking biology, chemistry, and global sustainability through the lens of innovation.