Недавно делал быстрый прототип асинхронного приложения в котором требовалось вызывать много синхронного кода. Да, я знаю, что это не лучший дизайн, но нужно было быстрое решение на один процесс и без очередей. Поэтому я выполнял код в потоках.
Выглядело это примерно так:
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
📰 A sharp and unexpected #failure of the Cloudflare hosting provider affected not only many popular sites and services, but also Fragment, the Tonnel gift marketplace and others. 🌩 Developers are studying this problem.
UPD: hosting has been restored.
#failure📰Domain Link Previews t.me stopped being generated. However, previews of old links can be provided, and the links themselves are fully functional.
UPD: problem solved.
#failure📰 Domains t.me, telegram.org,fragment.com and stel.com were not working and were partially down and were restored to service a few minutes ago. VPN did not solve the problem partially either.
⚡️Airbus A320 Уральских Авиалиний, следовавший из Дубая в Екатеринбург, произвел экстренную посадку в Ашхабаде (Туркменистан).
❗️Самолет, после 2-х часов полета перед пересечением границы Ирана с Туркменистаном на высоте 10.000м, подал сигнал бедствия и запросил экстренную посадку в ближайшем аэропорту.
💬 Как сообщают Уральские Авиалинии, у двигателей была разница в показаниях топлива. В связи с этим командир принял решение выключить 1 двигатель.
Лёгкое небо
#emergency#uralairlines#failure#engine#landing
Avoid Copycat Mistakes
Copying strategies without understanding their context can harm startups. From the experience of a former CTO, mindless imitation of established B2B products leads to failure. Large companies aim to protect their gains, while startups focus on growth. Analyze original strategies instead of copying them blindly. Discover more about proper implementation in the provided link.
#Startup#B2B#SaaS#Strategy#Growth#Analysis#Innovation#Business#Entrepreneurship#CTO#Imitation#Failure#Success#Marketing#Learning#Education#BusinessStrategy
Crypto Scandal: LIBRA's Dramatic Fall
Dave Portnoy attempts to buy tokens after repurposing LIBRA, mistakenly investing $200K in a fraudulent version, which plummeted 93%. Meanwhile, President Javier Milei faces allegations of fraud linked to the LIBRA token. A lawsuit by Argentine lawyers cites the former Central Bank head. CEO Hayden Davis of Kelsier Ventures blames insider selling for the crash. Investigations are ongoing amidst claims of insider knowledge in the token launch. For more insights, check the full news: Forklog News.
#Crypto#Argentina#Libra#Miley#Scandal#Failure#InsiderTrading#Lawsuit#Kelsier#Token#Blockchain#Finance#Investigation#HaydenDavis#Fraud#News#Market#Trends#Regulations#DeFi