Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🥰 The New and Improved Nest.store is Live!
After a short break, the marketplace for trading 📶Telegram gifts — nest.storeis back — refreshed and ready for a new season of digital deals.
🎁What’s new?
✔️ A complete redesign with an even more user-friendly interface — perfect for beginners 🎁
✔️ Faster transactions and stronger protection
✔️ New mechanics for giveaways and great-value deals
✔️Just 5% commission🎁 — one of the lowest on the market!
With nest.store, it’s not just about buying and selling Telegram gifts — it’s about winning, swapping smart, and enjoying the ride! 💙
🎁Explore nest.store — it’s live!
#Nest#TelegramGifts#TON
🔥NEST Exchange NFT Sale Begins!🎰🎰
🪺DEX Aggregator Nest is more than just a DEX. It is a multifunctional platform with many features. The long-awaited product launch is coming soon. It is currently in the MVP stage, token swaps should be launched today.
NEST NFTs are digital assets that provide access to unique features of the NEST platform. Owning these NFTs improves trading capabilities and unlocks additional privileges.
🪺Main types of NFTs
Fast Transaction — access to the fast transaction mode, where transactions are carried out several times faster than on standard DEX exchanges.
Sniper — the ability to almost instantly, automatically buy tokens when liquidity appears, which allows you to get the best entry point at the time of listing
🪺Benefits for NFT holders
⚡️For Fast Transaction NFT holders:
✔️ Unlimited access to fast transaction mode. Owners of these NFTs get lifetime access to fast swaps, which significantly reduces the time it takes to complete transactions.
✔️ Access to the closed NEST community
Holders will be able to join an exclusive community where they can share experiences and knowledge.
✔️ Direct communication with the project team and the founder
The privilege of interacting directly with the developers.
✔️ NEST merch and physical goods
Unique products and merch provided exclusively for NFT holders.
✔️ Cashback 7.5% of transactions
✔️ Advanced referral system
Increased bonuses for attracting new users.
✔️ Additional income in project points (NP)
These points can be exchanged for tokens after the $NEST launch, increasing long-term profitability.
✔️ Airdrops from collaborations with other projects
Owners will receive exclusive drops from NEST partner projects.
➡️For Sniper NFT holders:
✔️ Unlimited access to Quick Transaction Mode and Sniper Mode. Sniper NFT holders will be able to use Sniper Mode without restrictions.
✔️ Access to the closed NEST community and communication with the team. Includes all the perks of Fast Transaction NFT, but with additional opportunities for snipers.
✔️ NEST merch and physical goods
Like Fast Transaction NFT holders, they will receive unique physical goods.
✔️ Cashback 10% from transactions
✔️ Expanded referral system and additional income in points (NP). Attracting users and participating in trading will bring Sniper NFT owners additional bonuses and points, which can be exchanged for $NEST token in the future.
👤Whitelist for participation in the $NEST token presale
Sniper NFT holders will have privileged access to early rounds of the token sale, opening up additional investment opportunities.
🎁 Airdrops from collaborations with other projects
Just like the Fast Transaction NFT, Sniper NFT holders will receive drops from partners.
🪺Limited quantity
NFTs will be released in limited quantities via the #NEST platform Launchpad, increasing their value.
🔥Participate NFT-sale
🎰🎰Discount for whitelist owners. If you are not there yet, you should hurry:Mint\Add to Whitelist
#NFT#TON#DEX#DYOR#NFR
🪺The new Telegram Gifts marketplace is here!
🎁Nest Store is the first p2p Telegram gift marketplace where all transactions are fully automated and easy to use.
The marketplace is based on the P2P principle — a direct transaction between users without intermediaries and without the need to transfer gifts to the guarantor. Everything is as transparent and safe as possible.
🍪
🍪
The commission is only 5% per transaction, and for NEST NFT owners, trading is completely commission-free!
For now, Nest Store is only for gift trading, but very soon the following will appear:
✔️ NFT marketplace
✔️ Sticker store
✔️ Star Shop
🎁Invite your friends and get a 40% commission on the sale of his gifts.The action is available for 3 days! 🎆
🍭Try Nest Store right now!
#Nest#Telegram#p2p#Gifts