Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🔥Tangem presents integrated with
💳Visacrypto wallet
Tangem has developed a new wallet that supports direct payments through the Visa payment system. The new product for business (B2B) and consumers (B2C) will be released under the #Tangem brand and is expected to be launched by the end of the year, Tangem chief technical officer (CTO) Andrey Lazutkin told Cointelegraph.
Tangem Hardware Wallet Technology Certified by Visa✅️
The new Tangem crypto wallet will support Tangem Pay, a payment technology that allows users to spend cryptocurrency directly from a self-custody wallet through payment terminals or online payment tools. Tangem Pay is based on a smart contract and comes with one card without a seed phrase, Lazutkin said.
This is a significant step towards bringing the traditional banking sector and digital assets closer together, making it easier for everyday users to navigate and benefit from both worlds.
The team recently announced support for tokens created on the #TON network and another 1800+ other cryptocurrencies from different blockchains, allowing you to swap between them through the DEX built into the application.
🛍🛍Easy buy a cold wallet Tangem with a 10% discount promo code: FG7L9X attangem.com
Tangem Core. Reliability. ❤️
✅ Three similar devices offer a second and third chance to recover your assets in case of accidents or loss.
✅ The #Tangem chip is a product of a collaboration with Samsung Semiconductors, Inc. Its incredible performance and reliability.
✅ The chip is fortified against electromagnetic pulses (EMP), electrostatic discharge (ESD), and X-rays, adhering to the stringent ISO 7816-1 standard for security.
✅ The entire wallet is IP69K certified, offering full dust and water resistance. It functions optimally in temperatures between –25°C and +50°C.
✅Tangem devices have an impressive 25-year replacement warranty, reflecting our confidence in their longevity and durability.
✅ As a monolithic device, no components have a shorter lifespan or are vulnerable to damage or hacking.
🛡When it comes to safeguarding your assets, nothing is more crucial than unwavering reliability.🤜
🛍🛍Easy buy a cold wallet Tangem with a 10% discount promo code: FG7L9X at tangem.com
#Safepal#Ledger#Trezor#TON
Tangem Core: Security❤️
What's inside?
✅Certified equipment: The highest level of safety among consumer devices — EAL 6+.
✅Firmware tested twice: First in 2018 by the Swiss company Kudelski Security and again in 2023 by the international laboratory Riscure. Both audits confirmed the absence of vulnerabilities and backdoors in the firmware, which cannot be updated.
✅Open Source Software: Fully transparent and available for review on GitHub.
✅Anti-counterfeit protection: When you activate your wallet, the app verifies the secure element, confirming its authenticity with #Tangem.
✅Private Key Security: Private keys are generated inside the chip when the wallet is activated using a hardware random number generator. No one, including Tangem, has access to these keys.
✅Smart Backup: Three hardware devices instead of one, each providing the same high level of security. No unsafe copies required.
✅Absolute privacy: Your private keys cannot be disclosed under any circumstances.
✅User-controlled access: The wallet is protected by your access code and biometric authentication.
🛡This is what absolute safety means!
🛍🛍Easy buy a cold wallet Tangem with a 10% discount promo code: FG7L9X attangem.com
#Safepal#Ledger#Trezor#TON
OKX DEX — DEX aggregator and cross-chain bridge — now available on Tangem!⚪️
With a new provider — new opportunities:
- Over 1,000,000 new exchange pair options.
- Over 1,500 new tokens available for swap.
- No KYC.
The team is improving the versatility and usability of the Tangem app by integrating more and more providers.
Update your app and start exchanging crypto right now!🔄
🛍 Buy a cold wallet #Tangem with a 10% discountfrom our channel using the promo code:FG7L9X
#safepal#ledger#trezor#ton#okx
OKX DEX — DEX aggregator and cross-chain bridge — now available on Tangem Express!⚪️
With the new provider you can enjoy the following features:
↔️Over 1,000,000 new exchange pair options
↔️Over 1,500 new tokens available for swap
↔️KYC/AML not required🔥
Enjoy the ability to easily exchange crypto between different networks via the new OKX DEX directly in the Tangem app. Swap now!
🛍Buy a cold wallet #Tangem with a 10% discount from our channel using the promo code: FG7L9X
#Safepal#Ledger#Trezor#TON#OKX#DEX