Share
Embed
Лаборатория для баз данных
DevOpsDaysMoscow, 07-12-2019, Анатолий Станслер
DevOpsDaysMoscow
December 07, 2019
Transcript
30 slides
-
v3 Лаборатория для баз данных. Снимаем боль backend-разработки с Postgres.
Получаем за секунды полную копию "продуктовой" БД. Анатолий Станслер -
2 Кто использует: chewy.com Ускоряем процесс разработки, убирая задержки, связанные
с Postgres, у разработчиков, DBA и QA -
4 Подход #1 Разработка на тестовых данных или на реальном
“проде” Production Разработчики -
6 Production Staging Разработчики Подход #2 Разработка на тестовых данных,
тестирование на staging -
9 DB Lab Подход #4 Database Lab Разработчики Production Staging
Thin provisioning получение полноразмерной копии БД за секунды и без дополнительных трат -
Пример: БД: 4.5 TiB Получение независимой копии – менее 30
сек до момента готовности выполнения SQL 10 -
11 Copy-on-write файловая система Умеет создавать снапшоты и клоны Надежная
и масштабируемая Простая в управлении Другие варианты: LVM СХД (например, Pure Storage) -
12 Дерево блоков ZFS snapshot 2 snapshot 1 Начальное состояние
После записи https://www.youtube.com/watch?v=MsY-BafQgj4 Data blocks Meta blocks -
13 Клонирование Сжатие данных Не зависит от хранилища Общий кэш
клонов Развертка Самообслуживание Быстрая развертка Возможность откатываться Источник Обновление данных Разработчики/DBA QA/Тестировщики/CI Аналитики Репликация Бэкапы Дампы DB Lab Данные Клоны REST API -
14 Разработчик должен “дорасти“, чтобы иметь возможность тестить на полноразмерных
данных Как расти, если такого доступа нет, а значит, и учиться не на чем? Замкнутый круг -
15 Slack-бот в качестве первого интерфейса Низкий порог вхождения: -
Thin provisioning по сообщению - Объясняем метрики - Визуализируем explain - Даем рекомендации Возможность совершать ошибки и быстро откатываться Коллаборация Ускоряемся еще: DBA-бот Joe для SQL оптимизации! -
16 Коллаборация explain select p.* from posts as p join
boards as b on p."boardId" = b.id join "pnct_NetworkFollowBoard" as fb on fb."boardId" = b.id and fb."userId" = 1 order by p.id desc limit 10; -
18 Пример оптимизации explain select count(*) from posts where likes
> 10 and created > '2019-10-01' Рекомендации: (автоматические, на основе полученного плана и метрик) Query processes too much data to return a relatively small number of rows – Reduce data cardinality as early as possible during the execution, using one or several of the following techniques: new indexes, partitioning, query rewriting, denormalization. See the visualization of the plan to understand which plan nodes are the main bottlenecks. Specialized index needed – The index(es) currently used does not serve quite well for the needs of this query (notice Rows Removed by Filter: ..., meaning that the index fetched many non-target rows). Consider adding more specialized index(es). Время выполнения: 2.5 минуты -
19 Пример оптимизации Cost: 276857.33 Time: 2.476 min - planning:
1.165 ms - execution: 2.476 min Shared buffers: - hits: 4803 (~37.50 MiB) from the buffer pool - reads: 165789 (~1.30 GiB) from the OS file cache, including disk I/O - dirtied: 0 - writes: 0 explain select count(*) from posts where likes > 10 and created > '2019-10-01' Рекомендации: - Query processes too much data to return a relatively small number of rows - Specialized index needed Читаем 1.30 GiB с диска или кэша ОС -
20 Пример оптимизации Aggregate (cost=276857.32..276857.33 rows=1 width=8) (actual time=148536.494..148536.495 rows=1
loops=1) Buffers: shared hit=4803 read=165789 -> Index Scan using iiii on public.posts (cost=0.56..276856.00 rows=528 width=0) (actual time=25230.526..148536.091 rows=142 loops=1) Index Cond: (posts.likes > 10) Filter: (posts.created > '2019-10-01 00:00:00'::timestamp without time zone) Rows Removed by Filter: 170975 Buffers: shared hit=4803 read=165789 explain select count(*) from posts where likes > 10 and created > '2019-10-01' Рекомендации: - Query processes too much data to return a relatively small number of rows - Specialized index needed Читаем 1.30 GiB с диска или кэша ОС, чтобы достать 142 строки. Хотя Index Scan и выполнится должен был быстро. -
21 Пример оптимизации explain select count(*) from posts where likes
> 10 and created > '2019-10-01' Рекомендации: - Query processes too much data to return a relatively small number of rows - Specialized index needed Читаем 1.30 GiB с диска или кэша ОС, чтобы достать 142 строки. Хотя Index Scan и выполнится должен был быстро. Условие запроса частично не совпадает с условием индекса. Нужен специализированный индекс. Aggregate (cost=276857.32..276857.33 rows=1 width=8) (actual time=148536.494..148536.495 rows=1 loops=1) Buffers: shared hit=4803 read=165789 -> Index Scan using iiii on public.posts (cost=0.56..276856.00 rows=528 width=0) (actual time=25230.526..148536.091 rows=142 loops=1) Index Cond: (posts.likes > 10) Filter: (posts.created > '2019-10-01 00:00:00'::timestamp without time zone) Rows Removed by Filter: 170975 Buffers: shared hit=4803 read=165789 -
23 Пример оптимизации Cost: 4147.02 Time: 157.236 ms - planning:
1.185 ms - execution: 156.051 ms Shared buffers: - hits: 69 (~552.00 KiB) from the buffer pool - reads: 778 (~6.10 MiB) from the OS file cache, including disk I/O - dirtied: 0 - writes: 0 explain select count(*) from posts where likes > 10 and created > '2019-10-01' -
24 Пример оптимизации Aggregate (cost=4147.01..4147.02 rows=1 width=8) (actual time=155.973..155.974 rows=1
loops=1) Buffers: shared hit=69 read=778 -> Index Only Scan using improved_ix_posts on public.posts (cost=0.56..4145.69 rows=528 width=0) (actual time=3.981..155.870 rows=142 loops=1) Index Cond: ((posts.likes > 10) AND (posts.created > '2019-10-01 00:00:00'::timestamp without time zone)) Heap Fetches: 142 Buffers: shared hit=69 read=778 explain select count(*) from posts where likes > 10 and created > '2019-10-01' -
25 Установка 1. Сбилдить 2. Настроить хранилище ZFS и перенести
данные 3. Настроить Slack App 4. Запустить -
26 Как сделать чтобы планы на “проде” и на тестовых
стендах были одинаковые? Одинаковые данные Одинаковая конфигурация (почти) Желательно такое же железо, но может отличаться -
27 Работа с памятью в Postgres Postgres Backend Postgres Backend
... ... Postgres Shared Buffer Cache Postgres Backend Postgres Backend ... ... Postgres Shared Buffer Cache ... Disk Blocks Kernel Disk Buffer Cache ... Клон #1 Клон #2 -
28 Тюним конфигурацию клонов effective_cache_size: делаем как на “проде” –
получаем такой же план память не аллоцируется, нет необходимости в железе shared_buffer: компромисс между таймингом и количеством клонов