Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Channel: GOLD SCALPING TRADING SIGNALS
Members: ~4.4K
💢 Username: @gold_scalping_tradings
Description:
We are the best in Day trading and SCALPING. Contact our admin for your investment and copy trading @Gold_scalping_admin
🏷 Tags: #crypto_fx_trading
#gold#forex#trading#scalping#signals
https://telegramchannels.me/channels/gold_scalping_tradings
Group: Pip Pro Trader Fx
Members: ~2.68K
💢 Username: @pip_pro_traderfx
Description:
Learn Forex trading with real-time signals. Master gold trading, day trading, and scalping with expert strategies and daily motivation. Join our community and start your journey to financial freedom
🏷 Tags: #crypto_fx_trading
#forex_trading#day_trading#scalping#forex_signals#gold_signals
https://telegramchannels.me/groups/pip_pro_traderfx
🪙$STORM Token: Rising Success in the Market
A week after the listing, the $STORM token draws an upward curve on the chart. Let's try to figure out what the growth is connected with and what awaits us in the near future.
Let us remind you that Storm Trade— is not just another trading platform, they are pioneers setting trends in the world of decentralized finance, providing a unique trading experience on the largest derivatives #DEX on the #TON network.
Roadmap and development of Storm Trade
⚡️Storm Trade V2
Adding new pairs and trading instruments such as commodities ( #crudeoil, #gold etc.) and currencies (#Forex) will open doors to new markets, increasing your ability to diversify your trading strategies.
⚡️ Significant reduction in time to open positions, fixed closing price and guaranteed execution of SL/TP orders will make the trading experience precise and efficient.
The next versions of the protocol (V3 and beyond) will feature 1-click trading and gas-free trading. This will make your trading not only efficient but also accessible, lowering entry barriers for beginners.
🏆SocialFi and Copy Trading
Trading doesn't have to be boring. With the introduction of copy trading, you will be able to not only trade, but also follow the best traders, copying their successful strategies. Leaderboards of the strongest will encourage traders to compete, achieving better results, and the functions for creating teams (squads) will help find like-minded people and trade together.
🔮Leveraged Prediction Markets
Traders will be able to bet on the outcomes of various events, including economic indicators and sports results, with the possibility of using leverage. This will increase potential profits while minimizing investments and will attract the attention of not only cryptocurrency traders, but also those who want to speculate on real events.
📈Options, Spot Trading and Limit Orders
The introduction of options will allow users to apply more flexible and advanced strategies. The ability to hed and work with volatility will be an important addition to the main trading instruments, attracting experienced traders.
Limit orders will allow traders to use more complex strategies such as #scalping or grid orders, which can be profitable in conditions of high market volatility. #StormTrade will provide users with tools to automate such strategies, making them more efficient.
🪄AI Trading
Artificial Intelligence in Action
The team began experimenting with the use of artificial intelligence developed by partners to participate in a hackathon, and conducted the first experience of implementing #AI in Storm Trade. The built-in AI proved itself to be effective, helping to find optimal entry and exit points, predict market movements, and minimize risks.
The full list of tools planned for implementation can be found here:
🔗Read the article
StormTrade | Bot | Chat | Channel