Etsy 使用 Vitess 的過程

Etsy 寫了三偏關於使用 Vitess 解決資料庫效能問題的文章:「Scaling Etsy Payments with Vitess: Part 1 – The Data Model」、「Scaling Etsy Payments with Vitess: Part 2 – The “Seamless” Migration」、「Scaling Etsy Payments with Vitess: Part 3 – Reducing Cutover Risk」。

Vitess 是 YouTube 團隊開發出來的東西,試著透過一層 proxy 解決後端 MySQL 資料庫在 sharding 後查詢邏輯的問題。

有一些地方的資訊整理出來:

首先是現代暴力解的能耐,從維基百科可以查到 Etsy 在 2015 年就上市了,但到了 2020 年年底撞到 vertically scaling 的天花板 (這邊是指 GCP 的上限),可以看到現在的暴力法可以撐超久... 如果再多考慮到實體機房的話應該可以找到更大台的機器。

第二個是 Etsy 在 2020 年年底開始從資料庫搬資料,一路到 2022 年五月,算起來差不多搬了一年半,總共轉移了 4 個 database 到 Vitess 的 cluster 上,共 23 張表格與 40B rows。

第三個是利用 Vindexes 這個技術降低 sharding 時所帶來的限制。這個之前沒研究過:

A Vindex provides a way to map a column value to a keyspace ID.

從「Older Version Docs」這邊翻舊版的文件,發現 5.0+ 都有,再往 GitHub 上面的資料翻,看起來從 2016 年的版本就有了,不過當時看起來還一直在擴充:「Vitess v2.0.0-rc.1」。

回來看現在的功能,有 primary vindex 的設計:

The Primary Vindex for a table is analogous to a database primary key. Every sharded table must have one defined. A Primary Vindex must be unique: given an input value, it must produce a single keyspace ID.

然後是 secondary vindex(es) 的設計,指到 keyspace id(s),然後這個資訊會被用在 routing 上:

Secondary Vindexes are additional vindexes against other columns of a table offering optimizations for WHERE clauses that do not use the Primary Vindex. Secondary Vindexes return a single or a limited set of keyspace IDs which will allow VTGate to only target shards where the relevant data is present. In the absence of a Secondary Vindex, VTGate would have to send the query to all shards (called a scatter query).

It is important to note that Secondary Vindexes are only used for making routing decisions. The underlying database shards will most likely need traditional indexes on those same columns, to allow efficient retrieval from the table on the underlying MySQL instances.

然後是 functional vindex 與 lookup vindex,前者用演算法定義 keyspace id,後者讓你查:

A Functional Vindex is a vindex where the column value to keyspace ID mapping is pre-established, typically through an algorithmic function. In contrast, a Lookup Vindex is a vindex that provides the ability to create an association between a value and a keyspace ID, and recall it later when needed. Lookup Vindexes are sometimes also informally referred to as cross-shard indexes.

然後 lookup vindex 還有對 consistent hashing 的支援:

Consistent lookup vindexes use an alternate approach that makes use of careful locking and transaction sequences to guarantee consistency without using 2PC. This gives the best of both worlds, with the benefit of a consistent cross-shard vindex without paying the price of 2PC. To read more about what makes a consistent lookup vindex different from a standard lookup vindex read our consistent lookup vindexes design documentation.

這樣整體看起來,Vitess 把所有常見的 sharding 方式都包進去了,如果以後真的遇到這個量的話,也不需要自己在 application 或是 library 做一堆事情了...

GitHub 的 MySQL 架構與數字

前幾天 GitHub 有寫一篇文章提到他們的 MySQL 是怎麼 scale 的,另外裡面也有一些數字可以看:「Partitioning GitHub’s relational databases to handle scale」。

他們最主要的 database cluster 叫做 mysql1,裡面有提到 2019 年的時候這個 cluster 是 950K qps,其中 primary 有 50K qps:

In 2019, mysql1 answered 950,000 queries/s on average, 900,000 queries/s on replicas, and 50,000 queries/s on the primary.

在 2021 年的時候變成 1.125M qps,其中 75K qps 在 primary 上:

Today, in 2021, the same database tables are spread across several clusters. In two years, they saw continued growth, accelerating year-over-year. All hosts of these clusters combined answer 1,200,000 queries/s on average (1,125,000 queries/s on replicas, 75,000 queries/s on the primaries). At the same time, the average load on each host halved.

另外這幾年比較成熟的方案都拿出來用了,包括用 ProxySQL 降低連線數的壓力 (connection pool 的概念):

[W]e started using ProxySQL to reduce the number of connections opened against our primary MySQL instances.

ProxySQL is used for multiplexing client connections to MySQL primaries.

另外用 Vitess 協助 sharding 之間的轉移:

Vitess is a scaling layer on top of MySQL that helps with sharding needs. We use its vertical sharding feature to move sets of tables together in production without downtime.

這兩套應該是已經蠻成熟的了... 另外也可以發現老方法還是很好用,就算在 GitHub 這種量還是可以暴力解決很多事情。

Amazon Aurora PostgreSQL 多支援了一些 extension

Amazon Aurora PostgreSQL 多支援了一些 extension,剛好看到一些對我還蠻有用的東西。

第一個是 pg_cron,就如同名字所說的,可以拿來安排 cron job:「Amazon Aurora PostgreSQL supports pg_cron extension for scheduling database jobs」。

第二個是 pg_proctab,可以拿來看系統狀態,這在 Aurora 裡面算是沒有 shell 的替代方案:「Amazon Aurora PostgreSQL Supports the pg_proctab Extension to access PostgreSQL system stats」。

第三個是 pg_partman,可以對 serial id 切到不同的 partition:「Amazon Aurora PostgreSQL supports the pg_partman extension for managing time or serial id based table partitioning」。

這幾個在一定的量下應該都用的到...

在 SQL 裡面避免大量刪除資料的方式

看到 Percona 的「An Overview of Sharding in PostgreSQL and How it Relates to MongoDB’s」這篇,雖然是在講 PostgreSQL 上的 sharding (以及 partition),突然想到好像沒寫過要怎麼避免大量刪除資料的操作...

一個常見的情境是,想要讓某個表格只保留這一個月的資料,所以每個月開頭都會跑一隻 cron job 負責刪掉上個月的資料,像是 DELETE FROM xxx WHERE timestamp < yyy; 這樣的指令。

這個方式無論是在 PostgreSQL 或是 MySQL 都需要很多時間與 I/O 資源,而透過 partition 將不同時間區段切開到不同的表格,再用 TRUNCATE 直接清空表格剛好可以解這樣的問題。

Percona 的文章裡說了一些 PostgreSQL 的歷史與目前的進展。

在 PostgreSQL 9 或更早以前的版本,一個常見的作法是透過 table inheritance 實做 partition,然後用再用 function 實做 INSERT

CREATE TABLE temperature (
  id BIGSERIAL PRIMARY KEY NOT NULL,
  city_id INT NOT NULL,
  timestamp TIMESTAMP NOT NULL,
  temp DECIMAL(5,2) NOT NULL
);

CREATE TABLE temperature_201901 (CHECK (timestamp >= DATE '2019-01-01' AND timestamp <= DATE '2019-01-31')) INHERITS (temperature);
CREATE TABLE temperature_201902 (CHECK (timestamp >= DATE '2019-02-01' AND timestamp <= DATE '2019-02-28')) INHERITS (temperature);
CREATE TABLE temperature_201903 (CHECK (timestamp >= DATE '2019-03-01' AND timestamp <= DATE '2019-03-31')) INHERITS (temperature);

CREATE OR REPLACE FUNCTION temperature_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN
    IF ( NEW.timestamp >= DATE '2019-01-01' AND NEW.timestamp <= DATE '2019-01-31' ) THEN INSERT INTO temperature_201901 VALUES (NEW.*);
    ELSIF ( NEW.timestamp >= DATE '2019-02-01' AND NEW.timestamp <= DATE '2019-02-28' ) THEN INSERT INTO temperature_201902 VALUES (NEW.*);
    ELSIF ( NEW.timestamp >= DATE '2019-03-01' AND NEW.timestamp <= DATE '2019-03-31' ) THEN INSERT INTO temperature_201903 VALUES (NEW.*);
    ELSE RAISE EXCEPTION 'Date out of range!';
    END IF;
    RETURN NULL;
END;
$$
LANGUAGE plpgsql;

在 PostgreSQL 10 之後,就直接支援一些與 partition 相關的設計,像是這樣:

CREATE TABLE temperature (
  id BIGSERIAL NOT NULL,
  city_id INT NOT NULL,
  timestamp TIMESTAMP NOT NULL,
  temp DECIMAL(5,2) NOT NULL
) PARTITION BY RANGE (timestamp);

CREATE TABLE temperature_201901 PARTITION OF temperature FOR VALUES FROM ('2019-01-01') TO ('2019-02-01');
CREATE TABLE temperature_201902 PARTITION OF temperature FOR VALUES FROM ('2019-02-01') TO ('2019-03-01');
CREATE TABLE temperature_201903 PARTITION OF temperature FOR VALUES FROM ('2019-03-01') TO ('2019-04-01');

雖然還是有些限制,但可以看出比起以前簡單不少。

而有了 partition 後,文章的後續就在討論這跟 MongoDB 的 sharding 有什麼關係,但這就不是我關注的事情了...

Amazon ElastiCache 可以讓你動態改 Redis 大小

Amazon ElastiCacheRedis 可以動態改大小了 (Online Resizing):「Amazon ElastiCache Update – Online Resizing for Redis Clusters」。

不過目前看起來只有 Cluster Mode 的才支援:

設定要加 sharding:

然後就開始跑:

另外也可以 rebalance:

這樣就省了一些功夫...

MySQL 上 sharding 的方案

Percona 的人剛好針對 database sharding 的事情整理了一篇文章,專門講 SaaS 服務時對 sharding 的規劃:「MySQL Sharding Models for SaaS Applications」。

我主要是看這段:

When sharding today, you have a choice of rolling your own system from scratch, using comprehensive sharding platform such as Vitess or using a proxy solution to assist you with sharding. For proxy solutions, MySQL Router is the official solution. But in reality, third party solutions such as open source ProxySQL, commercial ScaleArc and semi-commercial (BSL) MariaDB MaxScale are widely used. Keep in mind, however, that traffic routing is only one of the problems that exist in large scale sharding implementations.

也就是說,除了在 application 上自己實作外,目前能用的方案 (堪用的方案) 大概就這些了,而且這些方案主要是解 routing 問題,對於跨 database server 的 join 都還是要自己小心實作。

後面提到的 sharding model 也是個蠻重要的主題,切割的方法與使用的方法有關,切的好效能就會好。

另外文章沒有提到要怎麼 balancing (甚至是 auto-balancing),這點應該也是比較需要注意的地方...

HTTP/1.1 時代的 Best Practice 變成 HTTP/2 的問題

Velocity 2015 上的「HTTP/2 is here, let's optimize!」提到了很多關於 HTTP/1.1 時代所採用的 Best Practice (或者說,workaround) 變成了 HTTP/2 的問題。

這張表整理了各種技巧在 HTTP/1.1 與 HTTP/2 的差異:

在 HTTP/2 因為有了 multiplexing 機制,用了 Apply domain sharding 後反而增加 DNS query 以及開新的連線所需要的 handshake 時間。

而 Concatenate resources 也算是 workaround 的一種,不同等級的合併會有不同的 trade-off。全站合併 assets 可以讓常逛的使用者下載的量降到最低,但會讓第一次讀取的使用者花比較多時間下載。如果是單頁合併 assets,則剛好反過來:第一次讀取的使用者較快,但常逛的使用者會下載重複的內容。

最後的 Inline resources,作者則是提出利用 HTTP/2 提供的 server push 機制來改善,不過沒看懂...

有些 workaround 總算可以拋開了...

Domain Sharding 的調整...

Domain Sharding 是針對以往瀏覽器常見的「加速技巧」(workaround),目的是突破瀏覽器對單一 domain 的最大連線速限制。像是 IE{6,7} 在 HTTP/1.1 上的限制是 2。

Steve Souders 在 2008 年整理的「Roundup on Parallel Connections」就有列出當時各瀏覽器的限制。而在 BrowserscopeNetwork 可以看到更多新的數字。

而隨著環境一直在改變,桌機限制的連線數也逐漸調高,以及 SPDY 的發展,再加上行動平台的比重愈來愈高,本來的 Domain Sharding 技巧需要重新審視。

Etsy 的「Reducing Domain Sharding」這篇文章中提到他們決定減少 Domain Sharding 的數量 (由四個變成兩個),而改善了反應時間:

  • 在圖片較多的頁面上約減少 50ms~80ms,在一般頁面則是減少 30ms~50ms。
  • 在行動平台上減少 500ms。

這兩個改善使得每次造訪的點閱率多了 0.27 page。

尤其是行動平台上對 Domain Sharding 的敏感程度,讓現在設計網站的人要考慮的更多了...