Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
⚡️xRocket News: EVAA DeFi Quest Claim Phase Begins
#xRocket#TON
The xRocket News announces the official start of the Claim phase for the EVAA DeFi Quest on April 16, lasting until April 24. Over 30,000 participants were involved, with anti-fraud measures successfully eliminating dishonest play, ensuring fair reward distribution.
Source: link
@tonlines
⚡️xRocket News: Staking Contest Success and Future Campaigns
#xRocket#Telegram
The recent staking contest on swap.coffee saw participants collect over 5,000 lottery tickets by staking more than 2,500,000 $XROCK, showing strong trust in xRocket's growth. While prizes have already been distributed, xRocket News announces a new campaign arriving next week, encouraging the community to achieve new trading milestones.
Source: link
@tonlines
xRocket News: Exciting Contests and Prizes in May
#xRocket#crypto
xRocket News reports on the exciting contests rolled out in early May, despite the chilly weather. The channel announced winners for several events, including a lottery and a P2P traders contest, with impressive prize pools. Enthusiasts can still participate in an ongoing raffle by staking $XROCK.
Source: link
@tonlines
xRocket News: Celebrate Cosmonautics Day with Stellar Prizes
#xRocket#Web3
xRocket News is celebrating Cosmonautics Day with a special giveaway. Participants can win cosmic-themed prizes by purchasing and holding $XROCK tokens. Winners will be announced on April 18, with prize distribution on April 21.
Source: link
@tonlines
xRocket News Highlights Staking Benefits on Swap.coffee
#staking#xRocket
xRocket News shares details about the staking opportunities for $XROCK tokens on swap.coffee. With a distribution of 333,333 tokens monthly and an APR of approximately 22.63%, users can benefit from staking. The initiative aims to support the xRocket ecosystem and offers increased returns for longer staking durations.
Source: link
@tonlines
⚠️Beware of scammers!
Since the very morning, spam transactions appeared in the @xRocket bot with a message about the pre-sale of the $XROCK token. The official channel xRocket News✔️announced a reminder:
We want to remind you that we held no presales or any sales at the moment, especially outside the bot. Don't send your funds to any wallets in order to buy $XROCK. All trades will be in pair XROCK-USDT at 11-00 UTC. There is no other place where you can buy $XROCK
Attention! The #SCAM message comes specifically from the #xRocket bot and looks like a native message from the project, but it is just a comment on the transaction for 0.002 USDT
Trading Competition: Baby Doge Coin on xRocket
#xRocket#BabyDoge
xRocket News announces the listing of Baby Doge Coin on xRocket with a trading competition. Participants trading the $1MBABYDOGE/$TON pair can win a share of the $5,000 prize pool, with the competition running from May 21 to May 28. Baby Doge Coin, a popular meme token on Binance Smart Chain, is now integrated with xRocket’s SocialFi tools.
Source: link
@tonlines
xRocket News: xJourney Launches Wheel of Fortune
#xRocket#xJourney
xRocket News announces the launch of xJourney’s Wheel of Fortune, a new feature that allows community members to use xPoints for valuable prizes including tickets for mega-prize giveaways. The event will start once 500,000,000 xPoints are burned, with prizes such as a PlayStation 5 and $XROCK available.
Source: link
@tonlines
⚡️xRocket News: Exciting Updates for xJourney
#xRocket#xJourney
xRocket News announces major updates in the xRocket ecosystem with xJourney now offering daily $XROCK payouts. The top 3 users on the leaderboard earn significant bonuses while others have opportunities through a daily raffle. Daily leaderboard resets ensure continuous engagement and reward distribution.
Source: link
@tonlines
⚡️xRocket News: Epic Star Wars Giveaway Details!
#xRocket#StarWars
xRocket News presents an exciting Star Wars-themed giveaway with over 20 prizes worth more than 1,000 USDT for fans. Participants can earn tickets by purchasing and holding 500 $XROCK, with winners announced on May 14. All prize details are available on @rocketman's profile.
Source: link
@tonlines
✉ xQuest — What's Next?
💬The Earn phase in xQuest Launch has officially ended. Over 125,000 users completed various quest tasks: from learning basic xRocket features to mastering trading and staking. This impressive result demonstrates high interest in the new platform.
⏺➕Now the Calculationphase is going, during which the campaign results will be summarize.
💰 After calculations, the Сlaim phase will begin – from March 3rd to March 10th, participants of the first xQuest campaign can claim their earned rewards and share the prize pool of 300,000 $XROCK (~$7750).
Trade on xRocket exchange
#xQuest#xRocket
🚀$XROCK is now on CoinMarketCap and CoinGecko
$XROCK token appeared on CoinMarketCapandCoinGecko, the largest crypto platforms. This means that you can now track all project information on independent sites in a convenient format.
CoinMarketCap is the world's most popular cryptocurrency price tracking website, with over 350 million monthly visitors !
CoinGecko is one of the largest aggregators of information related to cryptocurrencies, tokens, crypto exchanges, NFTs, DeFi, which offers more than 11 thousand coins
⭐ Placing on these platforms will allow you to attract the attention of even more users and conquer new blockchain peaks!
#TON#xRocket#token