PostgreSQL 10 發表

PostgreSQL 10 發表,有不少重要的功能 (進步):「PostgreSQL 10 Released」。

首先提到的是 Logical Replication:

Logical Replication - A publish/subscribe framework for distributing data

以往內建的 replication 是 block level change (同步哪個 block 改變的內容),對於版本不同的 PostgreSQL 就會痛。所以在 10 之前,想要處理 PostgreSQL 版本不同的問題都會使用第三方套件 (一種常見的情境就是資料庫的版本升級)。在 10 內建支援 Logical Replication 後就不需要掛其他套件了:

Logical replication extends the current replication features of PostgreSQL with the ability to send modifications on a per-database and per-table level to different PostgreSQL databases. Users can now fine-tune the data replicated to various database clusters and will have the ability to perform zero-downtime upgrades to future major PostgreSQL versions.

於是就可以達到 zero-downtime upgrade,這對於商業維運考量是個很重要的進展。

另外一個是 Improved Query Parallelism (在 9.6 就有,現在又再改善了),針對可平行化的 CPU-bounded SQL query 可以利用多 CPU 大幅加速,這點也是目前在 MySQL 上還沒看到的:

PostgreSQL 10 provides better support for parallelized queries by allowing more parts of the query execution process to be parallelized. Improvements include additional types of data scans that are parallelized as well as optimizations when the data is recombined, such as pre-sorting. These enhancements allow results to be returned more quickly.

上面提到這兩點其實對於某些需求是相輔相成的。

因為很多報表分析是可平行化的 CPU-bounded SQL query,但以前在 RDBMS 都不能被平行運算,於是很多單位就會想要倒出來到其他類型的資料庫運算 (以現在比較紅的產品,像是 Amazon RedshiftAmazon Athena,或是 BigQuery,甚至是丟進 ELK 裡)。但你用 PostgreSQL 又會痛在沒辦法很方便的把資料同步拉出來... (於是就會稍微妥協,用 cron job 每天倒資料)

現在 10 的這兩個功能剛好從兩個面向解決:一個是對於剛開使用 PostgreSQL 的人,他們可以繼續只用 PostgreSQL 撐久一點,因為報表需求的 SQL query 快很多;另外一方面也讓目前用 cron job 每天倒資料的人有了同步的選擇 (用 replication 同步到其他系統上)。

再來是 Quorum Commit for Synchronous Replication 這個功能,把分散式架構中需要「正確性」的底層技術做起來:

PostgreSQL 10 introduces quorum commit for synchronous replication, which allows for flexibility in how a primary database receives acknowledgement that changes were successfully written to remote replicas. An administrator can now specify that if any number of replicas has acknowledged that a change to the database has been made, then the data can be considered safely written.

整體來說,PostgreSQL 10 有非常多進步,而且這些進步對於商業營運考量都很有幫助...

Heimdall Data:自動 Cache RDBMS 資料增加效能

看到 AWS 的「Automating SQL Caching for Amazon ElastiCache and Amazon RDS」這篇裡面介紹了 Heimdall Data – SQL caching and performance optimization 這個產品。

從官網的介紹也可以看出來是另外疊一層 proxy,但自動幫你處理 cache invalidation 的問題:

But what makes Heimdall Data unique in industry is its auto-cache AND auto-invalidation capability. Our machine learning algorithms determine what queries to cache while invalidating to ensure maximum performance and data integrity.

看起來支援了四個蠻常見的 RDBMS:

Heimdall Data supports most all relational database (e.g. MySQL, Postgres, Amazon RDS, Oracle, SQL Server, MariaDB).

看起來是一個花錢直接買效能的方案... 不過 cache invalidation 的部分不知道要怎麼跨機器做,在 FAQ 沒看到 cluster 情況下會怎麼解決。

對於按讚數排名的方法

前幾天看到一篇 2009 年的老文章,在討論使用者透過「喜歡」以及「不喜歡」投票後,要怎麼排名的方法:「How Not To Sort By Average Rating」。

基本的概念是當使用者投票數愈多時就會愈準確,透過統計方法可以算一個信賴區間,再用區間的下限來排... 但沒想到公式「看起來」這麼複雜 XDDD

Score = Lower bound of Wilson score confidence interval for a Bernoulli parameter

但實際的運算其實沒那麼複雜,像是 Ruby 的程式碼可以看出大多都是系統內的運算就可以算出來。其中的 z 在大多數的情況下是常數。

require 'statistics2'

def ci_lower_bound(pos, n, confidence)
    if n == 0
        return 0
    end
    z = Statistics2.pnormaldist(1-(1-confidence)/2)
    phat = 1.0*pos/n
    (phat + z*z/(2*n) - z * Math.sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n)
end

The z-score in this function never changes, so if you don't have a statistics package handy or if performance is an issue you can always hard-code a value here for z. (Use 1.96 for a confidence level of 0.95.)

作者後來在 2012 年與 2016 年也分別給了 SQL 以及 Excel 的範例程式碼出來,裡面 hard-code 了 95% 信賴區間的部份:

SELECT widget_id, ((positive + 1.9208) / (positive + negative) - 
                   1.96 * SQRT((positive * negative) / (positive + negative) + 0.9604) / 
                          (positive + negative)) / (1 + 3.8416 / (positive + negative)) 
       AS ci_lower_bound FROM widgets WHERE positive + negative > 0 
       ORDER BY ci_lower_bound DESC;
=IFERROR((([@[Up Votes]] + 1.9208) / ([@[Up Votes]] + [@[Down Votes]]) - 1.96 * 
    SQRT(([@[Up Votes]] *  [@[Down Votes]]) / ([@[Up Votes]] +  [@[Down Votes]]) + 0.9604) / 
    ([@[Up Votes]] +  [@[Down Votes]])) / (1 + 3.8416 / ([@[Up Votes]] +  [@[Down Votes]])),0)

而更多的說明在維基百科的「Binomial proportion confidence interval」可以翻到,裡面也有其他的方法可以用。

AWS 東京區支援 Amazon Athena 了

很簡單但也很直接的消息公佈,AWS 宣佈在東京區與新加坡區支援 Amazon Athena 了:「Amazon Athena is now available in Asia Pacific (Singapore) and Asia Pacific (Tokyo)」。

這樣就不需要在美國跑完丟回日本了...

MySQL 總算要拔掉 mysql_query_cache 了

半官方的 MySQL blog 上宣佈了拔掉 mysql_query_cache 的計畫:「MySQL 8.0: Retiring Support for the Query Cache」。

作者開頭引用了 ProxySQL 的人對 MySQL Query Cache 的說明:

Although MySQL Query Cache was meant to improve performance, it has serious scalability issues and it can easily become a severe bottleneck.

主要問題在於 MySQL Query Cache 在多 CPU 環境下很難 scale,很容易造成一堆 thread 在搶 lock。而且作者也同意 ProxySQL 的說法,將 cache 放到 client 的效能比較好:

We also agree with Rene’s conclusion, that caching provides the greatest benefit when it is moved closer to the client:

可以看到 Query Cache 在複雜的環境下對效能極傷。而之前也提到過類似的事情了:「Percona 對 mysql_query_cache 的測試 (以 Magento 為例)」、「關閉 MySQL 的 Query Cache」。

一般如果要 cache 的話,透過 InnoDB 裡良好的 index 應該還可以撐不少量起來。

CockroachDB 1.0

CockroachDB 推出 1.0 版:「CockroachDB 1.0 is Production-Ready」。CockroachDB 是希望在分散式環境裡打造出有 ACID 特性的服務,這點類似於 GoogleSpanner 架構。

整個系統主要是用 Go 寫成,支援 PostgreSQL 協定,這讓許多現成的應用可以接上去:

Use existing PostgreSQL client drivers or supported ORMs.

而另外一邊有支援 MySQL 協定的 TiDB (剛好也是用 Go 寫的),整個 NewSQL 領域東西愈來愈多了...

SQL 的各種 JOIN

SQL 的各種 JOIN 其實是個很好玩的主題,不是很難,但沒有仔細練習過一次通常只能答出常用的那幾種... 而且過一陣子又會忘記 XD

這幾天不知道哪邊看到的舊文章「Say NO to Venn Diagrams When Explaining JOINs」,這篇作者大聲疾呼不要用 Venn diagram 解釋 SQL 的 JOIN,把比較特別的 JOIN 拿出來舉例...

因為 Venn diagram 是講集合交聯集這類的操作,但 JOIN 不僅僅是如此... 舉例來說,CROSS JOIN 對應到 cartesian product 就沒辦法用 Venn diagram 簡單的表示出來,而必須畫的更「具體」:

Google 的 Cloud Spanner

GoogleCloud Spanner 這個服務拿出來賣了:「Introducing Cloud Spanner: a global database service for mission-critical applications」,以及說明的「Inside Cloud Spanner and the CAP Theorem」。

Cloud Spanner 的規劃上是希望有 RDBMS 的能力 (像是 ACID 特性),又有強大的擴充能力 (scalability) 與可用性 (availability):

Today, we’re excited to announce the public beta for Cloud Spanner, a globally distributed relational database service that lets customers have their cake and eat it too: ACID transactions and SQL semantics, without giving up horizontal scaling and high availability.

在說明裡有提到 Cloud Spanner 是做到 CAP theorem 裡面的 CP:

The purist answer is “no” because partitions can happen and in fact have happened at Google, and during some partitions, Spanner chooses C and forfeits A. It is technically a CP system.

然後把 A 拉高到使用者不會在意 downtime 的程度:

However, no system provides 100% availability, so the pragmatic question is whether or not Spanner delivers availability that is so high that most users don't worry about its outages.

當然,比較讓人爭議的是 Twitter 上 Google Cloud 官方帳號的 tweet,直接講同時解決了 CAP 三個條件:

價錢不算便宜,不過對於想要找方案的人至少有選擇...

Swap 對 InnoDB 的影響

Percona 的老大拿 5.7 版做實驗,確認 swap 對 InnoDB 的影響:「The Impact of Swapping on MySQL Performance」。

測試的機器是 32GB RAM,作業系統 (以及 swap) 裝在已經有點年紀的 Intel 520 SSD 上,而 MySQL 則是裝在 Intel 750 NVMe 上。透過對 innodb_buffer_pool 的調整來看情況。

可以看到設為 24GB (記憶體 75% 的量) 時很穩定的在 44K QPS 與 3.5ms (95%):

This gives us about 44K QPS. The 95% query response time (reported by sysbench) is about 3.5ms.

而當設成 32GB 的時候開始可以觀察到 swap i/o,掉到 20K QPS 與 9ms (95%):

We can see that performance stabilizes after a bit at around 20K QPS, with some 380MB/sec disk IO and 125MB/sec swap IO. The 95% query response time has grown to around 9ms.

當拉到 48GB 的時候就更掉更多,6K QPS 與 35ms (95%):

Now we have around 6K QPS. Disk IO has dropped to 250MB/sec, and swap IO is up to 190MB/sec. The 95% query response time is around 35ms.

作者發現掉的比率沒有想像中大:

When I started, I expected severe performance drop even with very minor swapping. I surprised myself by getting swap activity to more than 100MB/sec, with performance “only” halved.

這邊測試用的是 SSD,如果是傳統用磁頭的硬碟,對 random access 應該會很敏感而掉更多:

This assumes your swap space is on an SSD, of course! SSDs handle random IO (which is what paging activity usually is) much better than HDDs.

基本上還是要避免碰到 swap 啦,另外 comment 的地方剛好有提到前陣子在猜測的 best practice,測試時的 vm.swappiness 是設成 1,這應該是作者的 best practice:

Swappiness was set to 1 in this case. I was not expecting this to cause significant impact as swapping is caused by genuine (intended) missconfiguration with more memory required than available.

Amazon Aurora 支援 Auditing

AWS 的人把 auditing plugin 移植到 Amazon AuroraMySQL 環境上了:「Auditing an Amazon Aurora Cluster」。

官方宣稱的效能很好,打開後不會掉太多:

主要原因是把寫 auditing log 這塊改寫掉:

這樣看起來頗不錯,平常其實可以開起來讓他記錄?