Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
🛢️SLEX Offers Low Trading Fees!
🚀Only for Community members, SLEX develops offers to trade commodities with low trading fees. And if you are holding SLEX tokens, you can get even more — a 20% discount on all trading fees for commodity trading📈
💼Join SLEX and be ready to diversify your portfolio between commodities and cryptocurrencies.
#SLEX#CommodityTrading#LowFees#TradeSmart
Email | Telegram | Reddit | Facebook | Instagram | Medium | Linkedin | Twitter
🚀 PRECIOUS METALS | Spot Silver Drops 4% to $72.72 per Ounce
Spot silver experienced a significant decline, dropping 4% to currently trade at $72.72 per ounce. According to Jin10, this decrease reflects ongoing market volatility and investor sentiment shifts in the precious metals sector. The decline in silver prices comes amid broader market movements and economic factors influencing commodity trading.
#preciousmetals#spotSilver#silverprice#commoditytrading#marketvolatility#investorsentiment#economicfactors
🚀 Abraxas Capital Closes Major Oil Short Positions, Shifts Focus to Bitcoin and Gold
On April 10, Hyperinsight monitoring revealed that Abraxas Capital, previously the largest oil short seller on the Hyperliquid platform, closed its significant WTIOIL and BRENTOIL short positions this morning. According to BlockBeats, the positions, valued at approximately $160 million, were closed at average prices of $95 and $95.5, respectively, resulting in a total profit of around $10.15 million.
Following the closure of these positions, the entity has not initiated any large-scale new positions. Currently, its main holdings include a long position in Bitcoin valued at $20.5 million and a short position in gold amounting to $30.8 million.
It is reported that since March 26, the address had aggressively opened oil short positions, with the position size peaking at $160 million. After recent ceasefire news, the holdings shifted from an unrealized loss of $9.7 million to a profit, which at one point expanded to nearly $10 million, before profit-taking began yesterday afternoon.
#AbraxasCapital#OilShort#Bitcoin#Gold#WTIOIL#BRENTOIL#Hyperliquid#CryptoInvesting#CommodityTrading#BTC
🚀 Crude Oil Short Position Faces $2 Million Loss Amid Negative Funding Fees
A wallet identified as 0x63c has opened a significant short position on crude oil through Hyperliquid, initially valued at $30 million. According to NS3.AI, this position is currently experiencing a floating loss of $2 million. Despite the loss, the position is generating approximately $388,000 daily in funding fees due to negative crude oil funding rates.
#CrudeOil#ShortPosition#Loss#FundingFees#Hyperliquid#NS3AI#Finance#Investing#CommodityTrading