SlideShare a Scribd company logo
Spilo,
highly-available
PostgreSQL cluster
Oleksii Kliukin
Zalando SE
Zalando
• 15 EU countries
• 3 fulfilment

centers
• 15+ million

active customers
• 2.2 billion €

revenue 2014

150 000+ products
We are growing!
Zalando platform
Our databases
• >150 production Postgresql
databases
• >13.5 TB data
• >5 TB biggest DB
• 400-1000+ write tps
• >2 DB failures/month
Zalando never sleeps
Infrastructure bottleneck
ACID Team
create
alter
deploy
migrate
failover
upgrade
80+ teams
Radical
Agility
Purpose
Autonomy
Mastery
Cloud
• 2013: ZCloud

• 2014: project Pequod

• 2015: Let’s just use AWS…
Amazon 3-letter words
• AWS - amazon web services
• EC2 - elastic compute cloud
• ELB - elastic load balancer
• RDS - relational DB service
AWS
• One account per team
• Microservices
• REST/OAuth2
• Deployment with Docker
Autonomous teams on AWS
REST
INTERNET
Autonomous teams
• Team decides which product to
build
• … and which technologies to use

• REST/OAuth2 mandatory

• Team is responsible for its
infrastructure
Databases?
• Developers should take care
of infrastructure

• ..including production
databases

• On AWS!
Isn’t it dangerous?
DBAs running with scissors, by Gavin M. Roy: https://www.flickr.com/photos/gavinmroy/4638958958
ACID team
provides
PostgreSQL
trainings
What about failover?
Autofailover tasks
• Detect the master failure
• Elect a new master
• Redirect clients
Autofailover issues
• Discarded writes
• Split-brain
• False positives
RDS?
• Support for PostgreSQL
• Automatic failover
• Most extensions
• Automatic backups
RDS?
• Vendor lock
• No superuser
• No untrusted languages
• No logical decoding plugins
• Rather expensive
EC2 + Linux HA
• Complex setup
• Lots of manual steps

(i.e. new replica creation)
Spilo
(!"#$%)
Spilo does
• Rapid deployment of
PostgreSQL on AWS EC2
instances

• Streaming replication with
auto-failover
Spilo on AWS
Spilo
MASTER
Spilo
REPLICA
Spilo
REPLICA
Master connection
Application DB request
ETCD cluster status
update
Failover
Spilo
REPLICA
Spilo
REPLICA
Master connection
Application DB request
ETCD cluster status
update
Failover
Spilo
MASTER
Spilo
REPLICA
Master connection
Application DB request
ETCD cluster status
update
NEW
SPILO
STARTS…
Failover
Spilo
MASTER
Spilo
REPLICA
Master connection
Application DB request
ETCD cluster status
update
Spilo
REPLICA
What is Spilo?
c
Patroni
MASTER
c
Patroni
REPLICA
c
Patroni
REPLICA
Auto-scaling group Auto-scaling group
Patroni ("&'(%)#)
• Handles new replicas and
failover

• Based on ideas and code of
the Compose Governor

• Open-source
Compose Governor idea


Core to our PostgreSQL HA
system is the Governor application
which uses etcd as its repository of
truth to discover which database
instance is leader.





Distributed configuration systems
• Fault tolerant

• Reliably store small amounts of
strongly-consistent data
between distributed nodes
• Good for storing the PostgreSQL
cluster state
Distributed consensus
LEADER
CLIENT CLIENT CLIENT
Distributed consensus
LEADER
CLIENT CLIENT CLIENT
Cluster state in etcd
$ etcdctl ls --recursive
/service
/service/batman
/service/batman/optime
/service/batman/optime/leader
/service/batman/members
/service/batman/members/postgresql0
/service/batman/members/postgresql1
/service/batman/initialize
/service/batman/leader
Leader key
$ etcdctl get /service/batman/leader
postgresql0
• Points to the member key
• Has a TTL, autoexpires
• Acts as an exclusive lock
• Only the leader can become
the master
Leader TTL
$ http http://127.0.0.1:2379/v2/keys/service/batman/
leader
…
{
"action": "get",
"node": {
"createdIndex": 48723,
"expiration": "2015-10-23T14:51:49.686506977Z",
"key": "/service/batman/leader",
"modifiedIndex": 49037,
"ttl": 27,
"value": "postgresql0"
}
}
Member key
$ etcdctl get /service/batman/members/
postgresql0
{“role":"master",
“state”:"running",
“conn_url”:"postgres://replicator:rep-
pass@127.0.0.1:5432/postgres",
“api_url”:"http://127.0.0.1:8008/
patroni",
"xlog_location":67108960}



Connection and API URL
c
Patroni
c
Patroni
API URL

(check health

during promotion)
MASTER
REPLICA
CONNECTION URL
MASTER LB
REPLICA LB
CONNECTION URL
Initialize key
$ etcdctl get /service/batman/initialize
6208852353820383446
• PostgreSQL cluster system ID
• Created by the first node that
joins the cluster
• Nodes with different system
ID are not allowed to join
Patroni modules
ETCD ZOOKEEPER
ABSTRACT DCS PostgreSQL REST API
High availability
Asynchronous executor
Callbacks
Demo time!
https://asciinema.org/a/29087
From Governor to Patroni
Governor
Patroni
Location of etcd: original
c
Governor
c
Governor
c
Governor
Replace etcd with proxy
c
Governor
c
Governor
c
Governor
Proxy
Proxy
Proxy
Embed etcd client in Patroni
c
Patroni
c
Patroni
c
Patroni
Patroni improvements
• Robust exception handling
• Run long-running tasks (i.e.
base backup in a separate
thread)
• ETCD + Zookeeper
• Rest API
Patroni improvements
• Configurable replica imaging
• Support for pg_rewind
Patroni improvements
• Manual failover
• Initialize from external
cluster
• Attach to already running
PostgreSQL nodes
• Tags (i.e. nofailover)
What you should monitor
• replication lag
• unhealthy member
• no leader
• etcd/

Zookeeper
Thank you!
• Spilo:

github.com/zalando/spilo

spilo.readthedocs.org

• Patroni:

github.com/zalando/patroni

patroni.readthedocs.org

• Feedback: @alexeyklyukin

More Related Content

PPTX
HighLoad Solutions On MySQL / Xiaobin Lin (Alibaba)
PDF
Making the case for write-optimized database algorithms / Mark Callaghan (Fac...
PPTX
MySQL Replication — Advanced Features / Петр Зайцев (Percona)
PPT
Tarantool: как сэкономить миллион долларов на базе данных на высоконагруженно...
PDF
Tarantool как платформа для микросервисов / Антон Резников, Владимир Перепели...
PDF
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
PDF
[245] presto 내부구조 파헤치기
PDF
Frontera распределенный робот для обхода веба в больших объемах / Александр С...
HighLoad Solutions On MySQL / Xiaobin Lin (Alibaba)
Making the case for write-optimized database algorithms / Mark Callaghan (Fac...
MySQL Replication — Advanced Features / Петр Зайцев (Percona)
Tarantool: как сэкономить миллион долларов на базе данных на высоконагруженно...
Tarantool как платформа для микросервисов / Антон Резников, Владимир Перепели...
Postgres & Redis Sitting in a Tree- Rimas Silkaitis, Heroku
[245] presto 내부구조 파헤치기
Frontera распределенный робот для обхода веба в больших объемах / Александр С...

What's hot (20)

PDF
Troubleshooting redis
PPTX
Как построить видеоплатформу на 200 Гбитс / Ольховченков Вячеслав (Integros)
ODP
Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...
PDF
Meet Spilo, Zalando’s HIGH-AVAILABLE POSTGRESQL CLUSTER - Feike Steenbergen
PDF
Background Tasks in Node - Evan Tahler, TaskRabbit
PDF
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
PDF
Patroni - HA PostgreSQL made easy
PDF
«Scrapy internals» Александр Сибиряков, Scrapinghub
PDF
PostgreSQL Configuration for Humans / Alvaro Hernandez (OnGres)
PDF
ELK: Moose-ively scaling your log system
PDF
Streaming huge databases using logical decoding
PDF
Move Over, Rsync
PPTX
RedisConf17- Using Redis at scale @ Twitter
PPTX
Scylla Summit 2018: In-Memory Scylla - When Fast Storage is Not Fast Enough
PDF
High Availability PostgreSQL with Zalando Patroni
PDF
Как PostgreSQL работает с диском
PPTX
Understanding and tuning WiredTiger, the new high performance database engine...
PPTX
Scylla Summit 2018: Keeping Your Latency SLAs No Matter What!
PDF
PostgreSQL on AWS: Tips & Tricks (and horror stories)
PDF
Deploying postgre sql on amazon ec2
Troubleshooting redis
Как построить видеоплатформу на 200 Гбитс / Ольховченков Вячеслав (Integros)
Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...
Meet Spilo, Zalando’s HIGH-AVAILABLE POSTGRESQL CLUSTER - Feike Steenbergen
Background Tasks in Node - Evan Tahler, TaskRabbit
Leonid Vasilyev "Building, deploying and running production code at Dropbox"
Patroni - HA PostgreSQL made easy
«Scrapy internals» Александр Сибиряков, Scrapinghub
PostgreSQL Configuration for Humans / Alvaro Hernandez (OnGres)
ELK: Moose-ively scaling your log system
Streaming huge databases using logical decoding
Move Over, Rsync
RedisConf17- Using Redis at scale @ Twitter
Scylla Summit 2018: In-Memory Scylla - When Fast Storage is Not Fast Enough
High Availability PostgreSQL with Zalando Patroni
Как PostgreSQL работает с диском
Understanding and tuning WiredTiger, the new high performance database engine...
Scylla Summit 2018: Keeping Your Latency SLAs No Matter What!
PostgreSQL on AWS: Tips & Tricks (and horror stories)
Deploying postgre sql on amazon ec2
Ad

Viewers also liked (20)

PDF
Танцующий кластер. Практическое руководство дрессировщика PostgreSQL / Алексе...
PDF
Сага о кластере. Все что вы хотели знать про горизонтальное масштабирование в...
PDF
PostgreSQL в высоконагруженных проектах
PDF
Что нового и полезного в PostgreSQL 9.5 / Илья Космодемьянский (PostgreSQL-Co...
PDF
Linux Cluster next generation
PPTX
Chronicle Map — key-value хранилище для трейдинга на Java / Левентов Роман (C...
PDF
Павел Лузанов, Postgres Professional. «PostgreSQL для пользователей Oracle»
PDF
Кластеры баз данных делаем сложные вещи просто / Андрей Тихонов (Avito)
PPTX
Учебный план для highload гуру / Андрей Аксёнов (Sphinx Technologies Inc.)
PDF
NVMf: 5 млн IOPS по сети своими руками / Андрей Николаенко (IBS)
PDF
Как мы сбежали от PostgreSQL или когда реляционная БД не справляется, Куманяе...
PDF
Как мы строили аналитическую платформу на несколько миллиардов событии в меся...
PDF
Skytools: PgQ Queues and applications
PDF
Эффективные алгоритмы поиска подобных объектов для терабайтов данных / Евгени...
PDF
Использование очередей асинхронных сообщений с PostgreSQL (Илья Космодемьянский)
PDF
Краткий обзор новинок PostgreSQL 9.4 – Николай Самохвалов
PDF
Синие против красных
PDF
~20081006 Highload2008 Postgresql самохвалов
PDF
Сравнительный анализ хранилищ данных, Олег Царев, Кирилл Коринский
PDF
2014.09.24 история небольшого успеха с PostgreSQL (Yandex)
Танцующий кластер. Практическое руководство дрессировщика PostgreSQL / Алексе...
Сага о кластере. Все что вы хотели знать про горизонтальное масштабирование в...
PostgreSQL в высоконагруженных проектах
Что нового и полезного в PostgreSQL 9.5 / Илья Космодемьянский (PostgreSQL-Co...
Linux Cluster next generation
Chronicle Map — key-value хранилище для трейдинга на Java / Левентов Роман (C...
Павел Лузанов, Postgres Professional. «PostgreSQL для пользователей Oracle»
Кластеры баз данных делаем сложные вещи просто / Андрей Тихонов (Avito)
Учебный план для highload гуру / Андрей Аксёнов (Sphinx Technologies Inc.)
NVMf: 5 млн IOPS по сети своими руками / Андрей Николаенко (IBS)
Как мы сбежали от PostgreSQL или когда реляционная БД не справляется, Куманяе...
Как мы строили аналитическую платформу на несколько миллиардов событии в меся...
Skytools: PgQ Queues and applications
Эффективные алгоритмы поиска подобных объектов для терабайтов данных / Евгени...
Использование очередей асинхронных сообщений с PostgreSQL (Илья Космодемьянский)
Краткий обзор новинок PostgreSQL 9.4 – Николай Самохвалов
Синие против красных
~20081006 Highload2008 Postgresql самохвалов
Сравнительный анализ хранилищ данных, Олег Царев, Кирилл Коринский
2014.09.24 история небольшого успеха с PostgreSQL (Yandex)
Ad

Similar to Spilo, отказоустойчивый PostgreSQL кластер / Oleksii Kliukin (Zalando SE) (20)

PDF
In-memory ColumnStore Index
PPTX
Big Data Goes Airborne. Propelling Your Big Data Initiative with Ironcluster ...
PPTX
Experience sql server on l inux and docker
PPTX
Brk2051 sql server on linux and docker
PPTX
PASS Summit 2020
PDF
Does Anyone Really Need RAC?
 
PDF
A Big Data Lake Based on Spark for BBVA Bank-(Oscar Mendez, STRATIO)
PPTX
Database As A Service: OEM + ODA (OOW 15 Presentation)
PDF
Aws-What You Need to Know_Simon Elisha
PDF
What's New in Apache Hive
PDF
Run Cloud Native MySQL NDB Cluster in Kubernetes
PDF
Building scalbale cloud native apps with .NET 8
PPTX
Building a Pluggable Analytics Stack with Cassandra (Jim Peregord, Element Co...
PPTX
Simplify IT: Oracle SuperCluster
PPTX
Achieve big data analytic platform with lambda architecture on cloud
PPTX
Journey Towards Scaling Your Application to Million Users
PDF
Getting started with MariaDB with Docker
PDF
Netflix presents at MassTLC Cloud Summit 2013
PPTX
Running Presto and Spark on the Netflix Big Data Platform
PPTX
Whd master deck_final
In-memory ColumnStore Index
Big Data Goes Airborne. Propelling Your Big Data Initiative with Ironcluster ...
Experience sql server on l inux and docker
Brk2051 sql server on linux and docker
PASS Summit 2020
Does Anyone Really Need RAC?
 
A Big Data Lake Based on Spark for BBVA Bank-(Oscar Mendez, STRATIO)
Database As A Service: OEM + ODA (OOW 15 Presentation)
Aws-What You Need to Know_Simon Elisha
What's New in Apache Hive
Run Cloud Native MySQL NDB Cluster in Kubernetes
Building scalbale cloud native apps with .NET 8
Building a Pluggable Analytics Stack with Cassandra (Jim Peregord, Element Co...
Simplify IT: Oracle SuperCluster
Achieve big data analytic platform with lambda architecture on cloud
Journey Towards Scaling Your Application to Million Users
Getting started with MariaDB with Docker
Netflix presents at MassTLC Cloud Summit 2013
Running Presto and Spark on the Netflix Big Data Platform
Whd master deck_final

More from Ontico (20)

PDF
One-cloud — система управления дата-центром в Одноклассниках / Олег Анастасье...
PDF
Масштабируя DNS / Артем Гавриченков (Qrator Labs)
PPTX
Создание BigData-платформы для ФГУП Почта России / Андрей Бащенко (Luxoft)
PDF
Готовим тестовое окружение, или сколько тестовых инстансов вам нужно / Алекса...
PDF
Новые технологии репликации данных в PostgreSQL / Александр Алексеев (Postgre...
PDF
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
PDF
Опыт разработки модуля межсетевого экранирования для MySQL / Олег Брославский...
PPTX
ProxySQL Use Case Scenarios / Alkin Tezuysal (Percona)
PDF
Внутренний open-source. Как разрабатывать мобильное приложение большим количе...
PPTX
Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...
PPTX
Балансировка на скорости проводов. Без ASIC, без ограничений. Решения NFWare ...
PDF
Перехват трафика — мифы и реальность / Евгений Усков (Qrator Labs)
PPT
И тогда наверняка вдруг запляшут облака! / Алексей Сушков (ПЕТЕР-СЕРВИС)
PPTX
Как мы заставили Druid работать в Одноклассниках / Юрий Невиницин (OK.RU)
PPTX
Разгоняем ASP.NET Core / Илья Вербицкий (WebStoating s.r.o.)
PPTX
100500 способов кэширования в Oracle Database или как достичь максимальной ск...
PPTX
Apache Ignite Persistence: зачем Persistence для In-Memory, и как он работает...
PDF
Механизмы мониторинга баз данных: взгляд изнутри / Дмитрий Еманов (Firebird P...
PDF
Как мы учились чинить самолеты в воздухе / Евгений Коломеец (Virtuozzo)
PPTX
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)
One-cloud — система управления дата-центром в Одноклассниках / Олег Анастасье...
Масштабируя DNS / Артем Гавриченков (Qrator Labs)
Создание BigData-платформы для ФГУП Почта России / Андрей Бащенко (Luxoft)
Готовим тестовое окружение, или сколько тестовых инстансов вам нужно / Алекса...
Новые технологии репликации данных в PostgreSQL / Александр Алексеев (Postgre...
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Опыт разработки модуля межсетевого экранирования для MySQL / Олег Брославский...
ProxySQL Use Case Scenarios / Alkin Tezuysal (Percona)
Внутренний open-source. Как разрабатывать мобильное приложение большим количе...
Подробно о том, как Causal Consistency реализовано в MongoDB / Михаил Тюленев...
Балансировка на скорости проводов. Без ASIC, без ограничений. Решения NFWare ...
Перехват трафика — мифы и реальность / Евгений Усков (Qrator Labs)
И тогда наверняка вдруг запляшут облака! / Алексей Сушков (ПЕТЕР-СЕРВИС)
Как мы заставили Druid работать в Одноклассниках / Юрий Невиницин (OK.RU)
Разгоняем ASP.NET Core / Илья Вербицкий (WebStoating s.r.o.)
100500 способов кэширования в Oracle Database или как достичь максимальной ск...
Apache Ignite Persistence: зачем Persistence для In-Memory, и как он работает...
Механизмы мониторинга баз данных: взгляд изнутри / Дмитрий Еманов (Firebird P...
Как мы учились чинить самолеты в воздухе / Евгений Коломеец (Virtuozzo)
Java и Linux — особенности эксплуатации / Алексей Рагозин (Дойче Банк)

Recently uploaded (20)

PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
composite construction of structures.pdf
PPT
Project quality management in manufacturing
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
Geodesy 1.pptx...............................................
PPTX
Safety Seminar civil to be ensured for safe working.
PPTX
CH1 Production IntroductoryConcepts.pptx
PDF
737-MAX_SRG.pdf student reference guides
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
DOCX
573137875-Attendance-Management-System-original
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
CYBER-CRIMES AND SECURITY A guide to understanding
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
composite construction of structures.pdf
Project quality management in manufacturing
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
Automation-in-Manufacturing-Chapter-Introduction.pdf
Geodesy 1.pptx...............................................
Safety Seminar civil to be ensured for safe working.
CH1 Production IntroductoryConcepts.pptx
737-MAX_SRG.pdf student reference guides
Internet of Things (IOT) - A guide to understanding
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Foundation to blockchain - A guide to Blockchain Tech
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
bas. eng. economics group 4 presentation 1.pptx
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
573137875-Attendance-Management-System-original

Spilo, отказоустойчивый PostgreSQL кластер / Oleksii Kliukin (Zalando SE)