The method greatly improve the performance MS SQL Server

В вопросах повышения производительности часто отталкиваются от производительности конкретного запроса. И это правильно. Но на сервере работает много запросов, много пользователей. Бывают моменты, когда запросы начинают взаимные блокировки. Иногда запросы начинают излишне активно обращаться к системе хранения данных. Каждый отдельный запрос может создавать пики потребления ресурсов, пики блокировок. Продолжаются они зачастую недолго, но в случае совпадения таких пиков нарушение работы сервера гарантировано. В лучшем случае катастрофическое снижение производительности.

То есть, повышать нужно не только производительность каждого запроса. Нужно повышать производительность сервера в целом. А как? Самые простые методы известны- разнести ресурсоемкие процессы во времени. Допустим, операции обслуживания базы данных, процедуры архивирования и сложные расчеты переносятся на ночное время, тогда активность пользователей минимальна.

Недавно выполнял одну тяжелую задачу для слабого сервера. Задача разбивается на отдельные части, но когда они выполняются на сервере блокируются все остальные задачи. Когда выполняется другая задача блокируется моя задача. Что делать?

Решение оказалось простым и изящным- написал цикл, при котором задача перед выполнением опрашивает системные счетчики. Если сервер перегружен- задача ждет минуту и повторно опрашивает счетчики. Фактически задача выполняется медленней, чем могла бы выполняться в идеальных условиях, но на практике скорость ее выполнения резко снизилась, жалобы на блокировки прекратились.

На практике предваряя этим скриптом сложные расчеты или операции обслуживания можно резко снизить вероятность конфликта процессов, взаимных блокировок. Отдельный процесс может работать медленней, но общая продолжительность выполнения процессов резко снижается.

Фактически это автомобильный регулировщик, который запрещает выезд автомобилям на перекресток в случае затора.

 

script without formatting

 

— При запуске процессов с невысоким приоритетом определяется нагрузка на сервер.
— Если она высока- есть заблокированные процессы, мало ожидаемое время страницы по любой из нод
— Объем блокировок более 30% (с 40 эксклация блокировок)- ждать минуту и после еще раз проверить
— When you start the process with a low priority is determined by the workload on the server.
— If it is high- blocked processes, low Page life expectancy on any of the nodes
— Lock more 30% (from 40% escalation locks) — wait a minute and then recheck
— The values of the permissible level meters can be set priority
— Important tasks can be run when the counters emerge from the critical values
— Background tasks will wait for values indicative of the comfortable status of the server
— Dmitry Gorchilin 20161018->20161020 digger.dp.ua
WHILE EXISTS (
SELECT ‘*’ FROM sys.dm_os_performance_counters where
((counter_name LIKE ‘%Processes blocked%’)AND (cntr_value>0))
OR
((counter_name LIKE ‘%Page life expectancy%’)AND (cntr_value<300)) UNION all select ‘*’ FROM sys.dm_os_performance_counters p1,sys.dm_os_performance_counters p2 where p1.counter_name = ‘Lock Blocks Allocated’ and p2.counter_name = ‘Lock Blocks’ AND p1.cntr_value>0 and 30< 100.*p2.cntr_value/p1.cntr_value UNION ALL select ‘*’ FROM sys.dm_os_performance_counters p1,sys.dm_os_performance_counters p2 where p1.counter_name = ‘Lock Owner Blocks Allocated’ and p2.counter_name = ‘Lock Owner Blocks’ AND p1.cntr_value>0 and 30<100.*p2.cntr_value/p1.cntr_value
)
begin
waitfor delay ’00:01:00′
END

 

In matters of increasing productivity are often repelled by the performance of a particular query. And it is right. But on the server runs a lot of requests, a lot of users. There are times when questions begin to deadlocks. Sometimes questions are beginning to actively seek unnecessarily to the storage system. Every single request can create resource consumption peaks locks peaks. They often continue for long, but in the case of coincidence of peaks violation of server operation is guaranteed. In the best case, a catastrophic reduction in performance.

That is, not only the need to increase the productivity of each request. It is necessary to increase the overall performance of the server. But as? The simplest methods are the known spread-intensive processes in time. For example, operations database maintenance, backup procedures and complex calculations are carried at night, when user activity is minimal.

Recently performed a hard task for the faint server. The problem is divided into separate parts, but when they are executed on the server block all other tasks. When performing other tasks blocked my task. What to do?
The solution was simple- wrote a cycle in which the task before executing queries system counters. If the server is overloaded task waiting for a moment and re-polls counters. In fact, the problem is slower than it could be carried out in ideal conditions, but in practice the speed of its implementation has fallen sharply, blocking complaints ceased.

In practice, anticipating this script complex calculations or maintenance operations can dramatically reduce the likelihood of conflict processes, deadlocks. A separate process may work slower, but the total duration of the process is significantly reduced.

In fact, this car regulator, which prohibits leaving cars at the intersection in the case of congestion.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *