Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
📊📊Can Circle handle the $USDC withdrawal on Monday when the banks are open? Let's review some stats
➡️CEX USDC Balances: total 7.189B
Top 3:
1. #Binance : 5.16B
2. #cryptocom: 785M
3. #Okx: 421M
➡️Netflow to CEX is also increasing over the hours in the past 2 days.
Dune link:https://dune.com/spotonchain/spotonchain-cex-usdc-flow
😎 Trump launches #ETF without #Coinbase
Trump Media has announced a partnership with Crypto.Com to launch the #ETF line, it will include cue ball and “pro—American” assets, all under the “Made in America” brand
Why #CryptoCom was chosen, and not #Coinbase — through which $529,325BTC has already passed in an ETF — remains a question.
Bitcoin Drops Below $97,000
Bitcoin fell below $97,000 during the night. Liquidation volumes topped $625 million within 24 hours. In Kazakhstan, regulators have blocked over 3,500 illegal crypto exchanges, including Coinbase, for violating digital asset laws. On January 7, the Bitcoin spot ETF net inflow reached $52.39 million, while BlackRock's ETF IBIT saw $596 million in inflow, bringing the total net asset value of Bitcoin spot ETFs to $110.115 billion. Additionally, a large transfer of 250,080,000 #CRO ($36.78M) was made from #CryptoCom to an unknown wallet.
#Bitcoin#Crypto#Kazakhstan#ETF#CRO#CryptoCom#WhaleAlert#Finance#MarketUpdate#Liquidation#News#Blockchain#Regulators#Assets#Investment#DigitalAssets#CryptoNews#MarketTrends#CryptoExchange#CryptoRegulation
Major Crypto Movements and Developments
🚨 1,823,409 #SOL ($274M) transferred to Coinbase Institutional. Whale Alert details multiple transfers.
ANTHROPIC achieves $61.5B valuation; former FTX stake now worth $5B.
Michael Saylor predicts Bitcoin market cap could reach $20-$200 trillion. His company paused BTC purchases; only 904 BTC away from 500,000 total.
ZKnox launches with Ethereum Foundation support, focusing on post-quantum cryptography to enhance Ethereum security.
Congressmen Emmer & Torres establish 'Congressional Crypto Caucus' for pro-crypto legislation.
Crypto.com’s Cronos protocol debates reissuing 70B burned CRO tokens; community vote shows over 86% against the proposal.
Links: ZKnox Launch, Cronos Proposal
#SOL#Bitcoin#Crypto#AI#Ethereum#ZKnox#Congress#Legislation#Caucus#ANTHROPIC#FTX#CRO#CryptoCom#PostQuantum#Security#Efficiency#Strategy#NFT#DeFi#MarketCap