Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🎄✨ Celebrate the joy of the season with Loot Baba [Official]!🎉
Wishing you a magical Merry Christmas 2025🎅 and a prosperous New Year ahead! ⭐️💎
Let’s welcome the future with endless opportunities and happiness! 🎁🔥
#merrychristmas@LootBaba_Officiall
Wishing all Nigerians a healthy and joyful Christmas! 🎄
May the spirit of the season bring happiness and well-being to your homes.
Stay safe, cherish moments, and embrace the gift of good health.
#MerryChristmas!🎄🎄
🇮🇩 Public Holidays in Bali
🎅 December 25 and 26 are official public holidays across Indonesia.
On these days, government institutions will be closed (including banks, tax offices, municipal offices, and other public services).
#MerryChristmas@BaliNews
¡Ay papá! Se acerca el #24Dic y lo que viene es rumba. Salí con Cilita a dar un recorrido por las calles de Caracas, vimos las fiestas navideñas; nuestro Pueblo está ejerciendo el derecho más bonito que tiene: el de la felicidad, vivir en Paz y disfrutar de este tiempo de unión. “¡No War!” #MerryChristmas
«Эта ночь принадлежит кроткому, посему пусть каждый отложит ярость и суровость, – принадлежит смиренному, пусть каждый обуздает свою гордость и смирит свое высокомерие. Ныне воссиял день милости, да не преследует же никто мщением нанесенной ему обиды; настал день радости, да не будет же никто виною печали и скорби для другого». (Ефрем Сирин. Слово на Рождество Христово). #καλαχριστουγεννα#merrychristmas
🎄✨ Merry Christmas from SingSing! 🎄✨
As the year comes to a close, we want to take a moment to express our heartfelt gratitude to our incredible SingSing community. 💖 Your unwavering support, enthusiasm, and passion have been the driving force behind everything we’ve accomplished together this year.
From building a thriving ecosystem to launching exciting games and features, none of this would have been possible without YOU. 🌟
🎁 This holiday season, we wish you and your loved ones endless joy, peace, and togetherness. May your days be filled with laughter, love, and the magic of Christmas. 🎅
Here’s to an even brighter and more exciting year ahead! Together, we’ll continue to grow, achieve, and make SingSing the #1 platform for all. 🚀
With love and gratitude,
The SingSing Team 💎
#SingSing#MerryChristmas#HappyHolidays
🎅Дорогие подписчики Легкого Неба!
🎉От лица руководства канала мы поздравляем вас с 2026 годом, желаем вам счастья, здоровья и главное - чистого и Лёгкого неба над головой!
🎅Надеемся, совсем скоро дед Мороз прилетит по Лёгкому небу к вам!
❄️Happy New Year!
Команда Легкое Небо
#merrychristmas#newyear#happy