Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
Indian Delegation To Visit Russia For Next Round Of India-EAEU FTA Talks In June 2026 #Trade
🚨India, Russia-Led EAEU Bloc Had Launched Talks For An FTA On 26th November 2025
🚨The EAEU Comprises Of Russia, Kazakhstan, Armenia, Belarus, And Kyrgyzstan; With An Observer Status To Cuba, Moldova, And Uzbekistan
𝐀 𝐦𝐚𝐬𝐬𝐢𝐯𝐞 𝐰𝐢𝐧 𝐟𝐨𝐫 𝐈𝐧𝐝𝐢𝐚’𝐬 𝐞𝐱𝐩𝐨𝐫𝐭𝐞𝐫𝐬 🇮🇳🤝🇳🇿.
The India–New Zealand FTA signed today ensures 100% duty-free access across all tariff lines, eliminating earlier tariffs of up to 10% on textiles, leather, carpets, ceramics, and auto components, boosting competitiveness, cutting costs, and unlocking new markets. #Trade
Bangladesh to import 200 broad-gauge coaches from India by 2027
The project, financed by the European Investment Bank, is expected to see the coaches added to the Bangladesh Railway fleet between June 2026 and December 2027.
#trade
I’ve been on @Vault777Casino for a while now and it’s honestly one of the most engaging virtual trading platforms I’ve used to #trade
Fast predictions, leaderboards, rewards, and real strategy
⚡️ Storm Trade: Update Completed and New Features Announced
#TON#trade
The Storm Trade update has been completed successfully. The platform now uses the Pyth price feed protocol, offering faster and more accurate price updates. This upgrade enhances UI interaction and sets the stage for the upcoming V3 launch on TON.
Source: link
@tonlines
🇮🇳🤝🇰🇷 Looking forward to PM Modi visiting South Korea says SK President Lee Jae Myung
Indian Officials say an upgraded India-SK CEPA Agreement could be signed during the Visit.
2009 CEPA Agreement reduced Tariffs on 85% Indian Products to SK and 90% SK products to India
#Geopolitics#Trade
Trump sees resumption of trade with Russia as a guarantee of ending the conflict - Foreign Policy
In his policy of resolving the conflict in Ukraine, Donald Trump is betting to restore trade relations with Russia as the most important factor of peace. He argues that economic cooperation will benefit American investors and ensure stability in the region.
The US administration also believes that trade agreements with Russia, such as energy sector deals, can serve as a guarantor of peace.
#Trump#Russia#Trade
👂More on Trump's Ear
⚠️
Portals Community: Season 2 Launches with Points Farming
#Portals#trade
Portals Community announces the return of Points Farming with the launch of Season 2, allowing users to earn points and cashback on every trade. Users can enhance their progress by completing tasks, with more earning opportunities to come. Stay tuned for another major update arriving tomorrow.
Source: link
@tonlines