Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
⚡️Trending Apps: TON Nest and AdsGram Developer Workshops
#TON#Telegram#AdsGram
Trending Apps shares that TON Nest, in partnership with AdsGram and the TON Foundation, is launching a webinar series for teams developing Telegram Mini Apps. Starting tomorrow, the program will offer in-depth sessions on marketing, monetization, and user acquisition, accessible via Zoom and livestreams on YouTube and X.
Source: link
@tonlines
💥 OFFICIAL PARTNERSHIP ANNOUNCEMENT 💥
We’re pleased to announce an official partnership between Gemifaucet and AdsGram, focused on improving monetization quality and user experience across our platform.
🚀 About Gemifaucet
Gemifaucet is a Telegram mini app where users receive rewards by interacting with tasks and ads in a simple, transparent, and user-friendly environment.
📊 About AdsGram
AdsGram is a leading Telegram Native Ads platform trusted by top Telegram apps and communities. It provides seamless, non-intrusive ad solutions with strong performance, advanced analytics, and a proven monetization ecosystem.
🤝 Why this partnership matters
By this official partnership formalizes our collaboration and strengthens our monetization infrastructure.
👉 Gemifaucet: @gemifaucet_bot
👉 AdsGram: @adsgram_ai
Thank you for your continued support — more updates coming soon! 🚀
#OfficialPartnership#Gemifaucet#AdsGram#TelegramMiniApp#Announcement
October 31, Dubai 😀
Telegram Builders Day
Friendly reminder — on October 31, Dubai will host the Telegram Builders Day organized by the @epicweb3 and @ton_tongames🧞♂️
@epicweb3 is known for creating events for blockchain builders around the globe, and this will be their debut in the Telegram ecosystem!
Get ready to hear from speakers representing #Notcoin, #TonTon Games, #Catizen, #StormTrade, #Blum, #Adsgram, #Fanzee Battles, #LayerPixel, and #Adsonar, who will discuss user acquisition, attracting investments, launching successful viral projects, and the future of the ecosystem.
Tickets are FREE, but limited, so hurry up — this is the place to be! 🎟✨
#TON#networking#web3
💎I wish you all a happy weekend! Let go of your worries and enjoy these beautiful days!
💎Do you have any good plans for next week?
💎If not, expand the chicken farm bigger and bigger, so that money can flow in like eggs! Achieve financial freedom as soon as possible, let's "chickens" fly and "chickens" jump together, and turn ourselves into wealth masters!
🎁In addition, friends who have not entered the global Tencent official channel to receive the bonus and welfare red envelope, don't worry, I have sent you a tutorial, go and check it out!
💎I hope my blessings can relieve everyone's pressure.
#TONVentures#GateVentures
#MEXCVentures#KeneticCapital
#ForesightVentures#CurveFinance#MEXCVentures#Adsgram#Yescoin#CurveFinance#Invest#WealthBuilding#FinancialFreedom#Crypto#Blockchain#Decentralization
#MarketTrends#Trading#Analysis
#PassiveIncome#RealEstate#InvestmentPortfolio
#Stocks
#Tencent PP Ranch #FreeTrial #Farm Game #Earn USDT #Play with Friends
🎮 Game Assistant
🤖Game Bot
⌨Discussion Group🤩VIP Channel
🪙 Join the Game Now